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/ADT/Statistic.h"
20 #include "llvm/ADT/TinyPtrVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/LiveStackAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
36 STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
37 STATISTIC(NumSnippets, "Number of snippets included in spills");
38 STATISTIC(NumSpills, "Number of spills inserted");
39 STATISTIC(NumReloads, "Number of reloads inserted");
40 STATISTIC(NumFolded, "Number of folded stack accesses");
41 STATISTIC(NumFoldedLoads, "Number of folded loads");
42 STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
43 STATISTIC(NumOmitReloadSpill, "Number of omitted spills after reloads");
44 STATISTIC(NumHoistLocal, "Number of locally hoisted spills");
45 STATISTIC(NumHoistGlobal, "Number of globally hoisted spills");
46 STATISTIC(NumRedundantSpills, "Number of redundant spills identified");
49 class InlineSpiller : public Spiller {
50 MachineFunctionPass &Pass;
55 MachineDominatorTree &MDT;
56 MachineLoopInfo &Loops;
58 MachineFrameInfo &MFI;
59 MachineRegisterInfo &MRI;
60 const TargetInstrInfo &TII;
61 const TargetRegisterInfo &TRI;
63 // Variables that are valid during spill(), but used by multiple methods.
65 LiveInterval *StackInt;
69 // All registers to spill to StackSlot, including the main register.
70 SmallVector<unsigned, 8> RegsToSpill;
72 // All COPY instructions to/from snippets.
73 // They are ignored since both operands refer to the same stack slot.
74 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
76 // Values that failed to remat at some point.
77 SmallPtrSet<VNInfo*, 8> UsedValues;
80 // Information about a value that was defined by a copy from a sibling
83 // True when all reaching defs were reloads: No spill is necessary.
84 bool AllDefsAreReloads;
86 // True when value is defined by an original PHI not from splitting.
89 // The preferred register to spill.
92 // The value of SpillReg that should be spilled.
95 // The block where SpillVNI should be spilled. Currently, this must be the
96 // block containing SpillVNI->def.
97 MachineBasicBlock *SpillMBB;
99 // A defining instruction that is not a sibling copy or a reload, or NULL.
100 // This can be used as a template for rematerialization.
103 // List of values that depend on this one. These values are actually the
104 // same, but live range splitting has placed them in different registers,
105 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
106 // copies of the current value and phi-kills. Usually only phi-kills cause
107 // more than one dependent value.
108 TinyPtrVector<VNInfo*> Deps;
110 SibValueInfo(unsigned Reg, VNInfo *VNI)
111 : AllDefsAreReloads(true), DefByOrigPHI(false),
112 SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
114 // Returns true when a def has been found.
115 bool hasDef() const { return DefByOrigPHI || DefMI; }
119 // Values in RegsToSpill defined by sibling copies.
120 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
121 SibValueMap SibValues;
123 // Values live-out from basic blocks. This is the same as
124 // LI.getVNInfoAt(LIS.getMBBEndIdx(MBB).getPrevSlot())
125 typedef DenseMap<MachineBasicBlock*, VNInfo*> LiveOutMap;
126 LiveOutMap LiveOutValues;
128 // Dead defs generated during spilling.
129 SmallVector<MachineInstr*, 8> DeadDefs;
134 InlineSpiller(MachineFunctionPass &pass,
139 LIS(pass.getAnalysis<LiveIntervals>()),
140 LSS(pass.getAnalysis<LiveStacks>()),
141 AA(&pass.getAnalysis<AliasAnalysis>()),
142 MDT(pass.getAnalysis<MachineDominatorTree>()),
143 Loops(pass.getAnalysis<MachineLoopInfo>()),
145 MFI(*mf.getFrameInfo()),
146 MRI(mf.getRegInfo()),
147 TII(*mf.getTarget().getInstrInfo()),
148 TRI(*mf.getTarget().getRegisterInfo()) {}
150 void spill(LiveRangeEdit &);
153 bool isSnippet(const LiveInterval &SnipLI);
154 void collectRegsToSpill();
156 bool isRegToSpill(unsigned Reg) {
157 return std::find(RegsToSpill.begin(),
158 RegsToSpill.end(), Reg) != RegsToSpill.end();
161 bool isSibling(unsigned Reg);
162 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
163 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
164 void analyzeSiblingValues();
166 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
167 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
169 void markValueUsed(LiveInterval*, VNInfo*);
170 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
171 void reMaterializeAll();
173 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
174 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
175 const SmallVectorImpl<unsigned> &Ops,
176 MachineInstr *LoadMI = 0);
177 void insertReload(LiveInterval &NewLI, SlotIndex,
178 MachineBasicBlock::iterator MI);
179 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
180 SlotIndex, MachineBasicBlock::iterator MI);
182 void spillAroundUses(unsigned Reg);
188 Spiller *createInlineSpiller(MachineFunctionPass &pass,
191 return new InlineSpiller(pass, mf, vrm);
195 //===----------------------------------------------------------------------===//
197 //===----------------------------------------------------------------------===//
199 // When spilling a virtual register, we also spill any snippets it is connected
200 // to. The snippets are small live ranges that only have a single real use,
201 // leftovers from live range splitting. Spilling them enables memory operand
202 // folding or tightens the live range around the single use.
204 // This minimizes register pressure and maximizes the store-to-load distance for
205 // spill slots which can be important in tight loops.
207 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
208 /// otherwise return 0.
209 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
210 if (!MI->isFullCopy())
212 if (MI->getOperand(0).getReg() == Reg)
213 return MI->getOperand(1).getReg();
214 if (MI->getOperand(1).getReg() == Reg)
215 return MI->getOperand(0).getReg();
219 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
220 /// It is assumed that SnipLI is a virtual register with the same original as
222 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
223 unsigned Reg = Edit->getReg();
225 // A snippet is a tiny live range with only a single instruction using it
226 // besides copies to/from Reg or spills/fills. We accept:
228 // %snip = COPY %Reg / FILL fi#
230 // %Reg = COPY %snip / SPILL %snip, fi#
232 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
235 MachineInstr *UseMI = 0;
237 // Check that all uses satisfy our criteria.
238 for (MachineRegisterInfo::reg_nodbg_iterator
239 RI = MRI.reg_nodbg_begin(SnipLI.reg);
240 MachineInstr *MI = RI.skipInstruction();) {
242 // Allow copies to/from Reg.
243 if (isFullCopyOf(MI, Reg))
246 // Allow stack slot loads.
248 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
251 // Allow stack slot stores.
252 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
255 // Allow a single additional instruction.
256 if (UseMI && MI != UseMI)
263 /// collectRegsToSpill - Collect live range snippets that only have a single
265 void InlineSpiller::collectRegsToSpill() {
266 unsigned Reg = Edit->getReg();
268 // Main register always spills.
269 RegsToSpill.assign(1, Reg);
270 SnippetCopies.clear();
272 // Snippets all have the same original, so there can't be any for an original
277 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
278 MachineInstr *MI = RI.skipInstruction();) {
279 unsigned SnipReg = isFullCopyOf(MI, Reg);
280 if (!isSibling(SnipReg))
282 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
283 if (!isSnippet(SnipLI))
285 SnippetCopies.insert(MI);
286 if (isRegToSpill(SnipReg))
288 RegsToSpill.push_back(SnipReg);
289 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
295 //===----------------------------------------------------------------------===//
297 //===----------------------------------------------------------------------===//
299 // After live range splitting, some values to be spilled may be defined by
300 // copies from sibling registers. We trace the sibling copies back to the
301 // original value if it still exists. We need it for rematerialization.
303 // Even when the value can't be rematerialized, we still want to determine if
304 // the value has already been spilled, or we may want to hoist the spill from a
307 bool InlineSpiller::isSibling(unsigned Reg) {
308 return TargetRegisterInfo::isVirtualRegister(Reg) &&
309 VRM.getOriginal(Reg) == Original;
313 static raw_ostream &operator<<(raw_ostream &OS,
314 const InlineSpiller::SibValueInfo &SVI) {
315 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
316 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
317 if (SVI.AllDefsAreReloads)
318 OS << " all-reloads";
319 if (SVI.DefByOrigPHI)
322 OS << " def: " << *SVI.DefMI;
329 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is
330 /// known. Otherwise remember the dependency for later.
332 /// @param SVI SibValues entry to propagate.
333 /// @param VNI Dependent value, or NULL to propagate to all saved dependents.
334 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVI,
336 SibValueInfo &SV = SVI->second;
339 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
341 // Should this value be propagated as a preferred spill candidate? We don't
342 // propagate values of registers that are about to spill.
343 bool PropSpill = !isRegToSpill(SV.SpillReg);
344 unsigned SpillDepth = ~0u;
346 // Further values that need to be updated.
347 SmallVector<VNInfo*, 8> WorkList;
349 // Defer propagation if the value is not known yet.
351 SV.Deps.push_back(VNI);
352 // Don't propagate to other dependents than VNI. SVI hasn't changed.
353 WorkList.push_back(VNI);
355 // No VNI given, update all Deps.
356 WorkList.append(SV.Deps.begin(), SV.Deps.end());
359 // Has the value been completely determined yet? If not, defer propagation.
363 while (!WorkList.empty()) {
364 SibValueMap::iterator DepSVI = SibValues.find(WorkList.pop_back_val());
365 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
366 SibValueInfo &DepSV = DepSVI->second;
367 bool Changed = false;
370 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
372 // Propagate defining instruction.
373 if (!DepSV.hasDef()) {
375 DepSV.DefMI = SV.DefMI;
376 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
379 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
381 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
383 DepSV.AllDefsAreReloads = false;
386 // Propagate best spill value.
387 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
388 if (SV.SpillMBB == DepSV.SpillMBB) {
389 // DepSV is in the same block. Hoist when dominated.
390 if (SV.SpillVNI->def < DepSV.SpillVNI->def) {
391 // This is an alternative def earlier in the same MBB.
392 // Hoist the spill as far as possible in SpillMBB. This can ease
393 // register pressure:
399 // Hoisting the spill of s to immediately after the def removes the
400 // interference between x and y:
407 DepSV.SpillReg = SV.SpillReg;
408 DepSV.SpillVNI = SV.SpillVNI;
409 DepSV.SpillMBB = SV.SpillMBB;
412 // DepSV is in a different block.
413 if (SpillDepth == ~0u)
414 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
416 // Also hoist spills to blocks with smaller loop depth, but make sure
417 // that the new value dominates. Non-phi dependents are always
418 // dominated, phis need checking.
419 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
420 (!DepSVI->first->isPHIDef() ||
421 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
423 DepSV.SpillReg = SV.SpillReg;
424 DepSV.SpillVNI = SV.SpillVNI;
425 DepSV.SpillMBB = SV.SpillMBB;
433 // Something changed in DepSVI. Propagate to dependents.
434 WorkList.append(DepSV.Deps.begin(), DepSV.Deps.end());
436 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
437 << DepSVI->first->def << " to:\t" << DepSV);
441 /// traceSiblingValue - Trace a value that is about to be spilled back to the
442 /// real defining instructions by looking through sibling copies. Always stay
443 /// within the range of OrigVNI so the registers are known to carry the same
446 /// Determine if the value is defined by all reloads, so spilling isn't
447 /// necessary - the value is already in the stack slot.
449 /// Return a defining instruction that may be a candidate for rematerialization.
451 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
453 // Check if a cached value already exists.
454 SibValueMap::iterator SVI;
457 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
459 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
460 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
461 return SVI->second.DefMI;
464 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
465 << UseVNI->id << '@' << UseVNI->def << '\n');
467 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
469 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
470 WorkList.push_back(std::make_pair(UseReg, UseVNI));
475 tie(Reg, VNI) = WorkList.pop_back_val();
476 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
479 // First check if this value has already been computed.
480 SVI = SibValues.find(VNI);
481 assert(SVI != SibValues.end() && "Missing SibValues entry");
483 // Trace through PHI-defs created by live range splitting.
484 if (VNI->isPHIDef()) {
485 if (VNI->def == OrigVNI->def) {
486 DEBUG(dbgs() << "orig phi value\n");
487 SVI->second.DefByOrigPHI = true;
488 SVI->second.AllDefsAreReloads = false;
489 propagateSiblingValue(SVI);
492 // Get values live-out of predecessors.
493 LiveInterval &LI = LIS.getInterval(Reg);
494 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
495 DEBUG(dbgs() << "split phi value, check " << MBB->pred_size()
497 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
498 PE = MBB->pred_end(); PI != PE; ++PI) {
499 // Use a cache of block live-out values. This is faster than using
500 // getVNInfoAt on complex intervals.
501 VNInfo *&PVNI = LiveOutValues[*PI];
503 PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
506 // Known predecessor value? Try an insertion.
508 SibValues.insert(std::make_pair(PVNI, SibValueInfo(Reg, PVNI)));
509 // This is the first time we see PVNI, add it to the worklist.
511 WorkList.push_back(std::make_pair(Reg, PVNI));
512 propagateSiblingValue(SVI, VNI);
514 // Next work list item.
518 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
519 assert(MI && "Missing def");
521 // Trace through sibling copies.
522 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
523 if (isSibling(SrcReg)) {
524 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
525 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
526 assert(SrcVNI && "Copy from non-existing value");
527 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
528 << SrcVNI->id << '@' << SrcVNI->def << '\n');
529 // Known sibling source value? Try an insertion.
530 tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
531 SibValueInfo(SrcReg, SrcVNI)));
532 // This is the first time we see Src, add it to the worklist.
534 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
535 propagateSiblingValue(SVI, VNI);
536 // Next work list item.
541 // Track reachable reloads.
542 SVI->second.DefMI = MI;
543 SVI->second.SpillMBB = MI->getParent();
545 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
546 DEBUG(dbgs() << "reload\n");
547 propagateSiblingValue(SVI);
548 // Next work list item.
552 // Potential remat candidate.
553 DEBUG(dbgs() << "def " << *MI);
554 SVI->second.AllDefsAreReloads = false;
555 propagateSiblingValue(SVI);
556 } while (!WorkList.empty());
558 // Look up the value we were looking for. We already did this lokup at the
559 // top of the function, but SibValues may have been invalidated.
560 SVI = SibValues.find(UseVNI);
561 assert(SVI != SibValues.end() && "Didn't compute requested info");
562 DEBUG(dbgs() << " traced to:\t" << SVI->second);
563 return SVI->second.DefMI;
566 /// analyzeSiblingValues - Trace values defined by sibling copies back to
567 /// something that isn't a sibling copy.
569 /// Keep track of values that may be rematerializable.
570 void InlineSpiller::analyzeSiblingValues() {
572 LiveOutValues.clear();
574 // No siblings at all?
575 if (Edit->getReg() == Original)
578 LiveInterval &OrigLI = LIS.getInterval(Original);
579 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
580 unsigned Reg = RegsToSpill[i];
581 LiveInterval &LI = LIS.getInterval(Reg);
582 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
583 VE = LI.vni_end(); VI != VE; ++VI) {
587 MachineInstr *DefMI = 0;
588 // Check possible sibling copies.
589 if (VNI->isPHIDef() || VNI->getCopy()) {
590 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
591 assert(OrigVNI && "Def outside original live range");
592 if (OrigVNI->def != VNI->def)
593 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
595 if (!DefMI && !VNI->isPHIDef())
596 DefMI = LIS.getInstructionFromIndex(VNI->def);
597 if (DefMI && Edit->checkRematerializable(VNI, DefMI, TII, AA)) {
598 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
599 << VNI->def << " may remat from " << *DefMI);
605 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
606 /// a spill at a better location.
607 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
608 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
609 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
610 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
611 SibValueMap::iterator I = SibValues.find(VNI);
612 if (I == SibValues.end())
615 const SibValueInfo &SVI = I->second;
617 // Let the normal folding code deal with the boring case.
618 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
621 // SpillReg may have been deleted by remat and DCE.
622 if (!LIS.hasInterval(SVI.SpillReg)) {
623 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
628 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
629 if (!SibLI.containsValue(SVI.SpillVNI)) {
630 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
635 // Conservatively extend the stack slot range to the range of the original
636 // value. We may be able to do better with stack slot coloring by being more
638 assert(StackInt && "No stack slot assigned yet.");
639 LiveInterval &OrigLI = LIS.getInterval(Original);
640 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
641 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
642 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
643 << *StackInt << '\n');
645 // Already spilled everywhere.
646 if (SVI.AllDefsAreReloads) {
647 DEBUG(dbgs() << "\tno spill needed: " << SVI);
648 ++NumOmitReloadSpill;
651 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
652 // any later spills of the same value.
653 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
655 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
656 MachineBasicBlock::iterator MII;
657 if (SVI.SpillVNI->isPHIDef())
658 MII = MBB->SkipPHIsAndLabels(MBB->begin());
660 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
661 assert(DefMI && "Defining instruction disappeared");
665 // Insert spill without kill flag immediately after def.
666 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
667 MRI.getRegClass(SVI.SpillReg), &TRI);
668 --MII; // Point to store instruction.
669 LIS.InsertMachineInstrInMaps(MII);
670 VRM.addSpillSlotUse(StackSlot, MII);
671 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
673 if (MBB == CopyMI->getParent())
680 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
681 /// redundant spills of this value in SLI.reg and sibling copies.
682 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
683 assert(VNI && "Missing value");
684 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
685 WorkList.push_back(std::make_pair(&SLI, VNI));
686 assert(StackInt && "No stack slot assigned yet.");
690 tie(LI, VNI) = WorkList.pop_back_val();
691 unsigned Reg = LI->reg;
692 DEBUG(dbgs() << "Checking redundant spills for "
693 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
695 // Regs to spill are taken care of.
696 if (isRegToSpill(Reg))
699 // Add all of VNI's live range to StackInt.
700 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
701 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
703 // Find all spills and copies of VNI.
704 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
705 MachineInstr *MI = UI.skipInstruction();) {
706 if (!MI->isCopy() && !MI->getDesc().mayStore())
708 SlotIndex Idx = LIS.getInstructionIndex(MI);
709 if (LI->getVNInfoAt(Idx) != VNI)
712 // Follow sibling copies down the dominator tree.
713 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
714 if (isSibling(DstReg)) {
715 LiveInterval &DstLI = LIS.getInterval(DstReg);
716 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
717 assert(DstVNI && "Missing defined value");
718 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
719 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
726 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
727 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
728 // eliminateDeadDefs won't normally remove stores, so switch opcode.
729 MI->setDesc(TII.get(TargetOpcode::KILL));
730 DeadDefs.push_back(MI);
731 ++NumRedundantSpills;
734 } while (!WorkList.empty());
738 //===----------------------------------------------------------------------===//
740 //===----------------------------------------------------------------------===//
742 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
743 /// instruction cannot be eliminated. See through snippet copies
744 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
745 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
746 WorkList.push_back(std::make_pair(LI, VNI));
748 tie(LI, VNI) = WorkList.pop_back_val();
749 if (!UsedValues.insert(VNI))
752 if (VNI->isPHIDef()) {
753 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
754 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
755 PE = MBB->pred_end(); PI != PE; ++PI) {
756 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
758 WorkList.push_back(std::make_pair(LI, PVNI));
763 // Follow snippet copies.
764 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
765 if (!SnippetCopies.count(MI))
767 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
768 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
769 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
770 assert(SnipVNI && "Snippet undefined before copy");
771 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
772 } while (!WorkList.empty());
775 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
776 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
777 MachineBasicBlock::iterator MI) {
778 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
779 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
782 DEBUG(dbgs() << "\tadding <undef> flags: ");
783 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
784 MachineOperand &MO = MI->getOperand(i);
785 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
788 DEBUG(dbgs() << UseIdx << '\t' << *MI);
792 if (SnippetCopies.count(MI))
795 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
796 LiveRangeEdit::Remat RM(ParentVNI);
797 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
798 if (SibI != SibValues.end())
799 RM.OrigMI = SibI->second.DefMI;
800 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
801 markValueUsed(&VirtReg, ParentVNI);
802 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
806 // If the instruction also writes VirtReg.reg, it had better not require the
807 // same register for uses and defs.
809 SmallVector<unsigned, 8> Ops;
810 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
812 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
813 MachineOperand &MO = MI->getOperand(Ops[i]);
814 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
815 markValueUsed(&VirtReg, ParentVNI);
816 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
822 // Before rematerializing into a register for a single instruction, try to
823 // fold a load into the instruction. That avoids allocating a new register.
824 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
825 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
826 Edit->markRematerialized(RM.ParentVNI);
831 // Alocate a new register for the remat.
832 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
833 NewLI.markNotSpillable();
835 // Finally we can rematerialize OrigMI before MI.
836 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
838 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
839 << *LIS.getInstructionFromIndex(DefIdx));
842 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
843 MachineOperand &MO = MI->getOperand(Ops[i]);
844 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
845 MO.setReg(NewLI.reg);
849 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
851 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
852 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
853 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
858 /// reMaterializeAll - Try to rematerialize as many uses as possible,
859 /// and trim the live ranges after.
860 void InlineSpiller::reMaterializeAll() {
861 // analyzeSiblingValues has already tested all relevant defining instructions.
862 if (!Edit->anyRematerializable(LIS, TII, AA))
867 // Try to remat before all uses of snippets.
868 bool anyRemat = false;
869 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
870 unsigned Reg = RegsToSpill[i];
871 LiveInterval &LI = LIS.getInterval(Reg);
872 for (MachineRegisterInfo::use_nodbg_iterator
873 RI = MRI.use_nodbg_begin(Reg);
874 MachineInstr *MI = RI.skipInstruction();)
875 anyRemat |= reMaterializeFor(LI, MI);
880 // Remove any values that were completely rematted.
881 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
882 unsigned Reg = RegsToSpill[i];
883 LiveInterval &LI = LIS.getInterval(Reg);
884 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
887 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
889 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
890 MI->addRegisterDead(Reg, &TRI);
891 if (!MI->allDefsAreDead())
893 DEBUG(dbgs() << "All defs dead: " << *MI);
894 DeadDefs.push_back(MI);
898 // Eliminate dead code after remat. Note that some snippet copies may be
900 if (DeadDefs.empty())
902 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
903 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
905 // Get rid of deleted and empty intervals.
906 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
907 unsigned Reg = RegsToSpill[i-1];
908 if (!LIS.hasInterval(Reg)) {
909 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
912 LiveInterval &LI = LIS.getInterval(Reg);
915 Edit->eraseVirtReg(Reg, LIS);
916 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
918 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
922 //===----------------------------------------------------------------------===//
924 //===----------------------------------------------------------------------===//
926 /// If MI is a load or store of StackSlot, it can be removed.
927 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
930 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
931 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
934 // We have a stack access. Is it the right register and slot?
935 if (InstrReg != Reg || FI != StackSlot)
938 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
939 LIS.RemoveMachineInstrFromMaps(MI);
940 MI->eraseFromParent();
944 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
945 /// @param MI Instruction using or defining the current register.
946 /// @param Ops Operand indices from readsWritesVirtualRegister().
947 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
948 /// @return True on success, and MI will be erased.
949 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
950 const SmallVectorImpl<unsigned> &Ops,
951 MachineInstr *LoadMI) {
952 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
954 SmallVector<unsigned, 8> FoldOps;
955 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
956 unsigned Idx = Ops[i];
957 MachineOperand &MO = MI->getOperand(Idx);
960 // FIXME: Teach targets to deal with subregs.
963 // We cannot fold a load instruction into a def.
964 if (LoadMI && MO.isDef())
966 // Tied use operands should not be passed to foldMemoryOperand.
967 if (!MI->isRegTiedToDefOperand(Idx))
968 FoldOps.push_back(Idx);
971 MachineInstr *FoldMI =
972 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
973 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
976 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
978 VRM.addSpillSlotUse(StackSlot, FoldMI);
979 MI->eraseFromParent();
980 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
985 /// insertReload - Insert a reload of NewLI.reg before MI.
986 void InlineSpiller::insertReload(LiveInterval &NewLI,
988 MachineBasicBlock::iterator MI) {
989 MachineBasicBlock &MBB = *MI->getParent();
990 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
991 MRI.getRegClass(NewLI.reg), &TRI);
992 --MI; // Point to load instruction.
993 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
994 VRM.addSpillSlotUse(StackSlot, MI);
995 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
996 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
997 LIS.getVNInfoAllocator());
998 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
1002 /// insertSpill - Insert a spill of NewLI.reg after MI.
1003 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
1004 SlotIndex Idx, MachineBasicBlock::iterator MI) {
1005 MachineBasicBlock &MBB = *MI->getParent();
1006 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
1007 MRI.getRegClass(NewLI.reg), &TRI);
1008 --MI; // Point to store instruction.
1009 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
1010 VRM.addSpillSlotUse(StackSlot, MI);
1011 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
1012 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
1013 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
1017 /// spillAroundUses - insert spill code around each use of Reg.
1018 void InlineSpiller::spillAroundUses(unsigned Reg) {
1019 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
1020 LiveInterval &OldLI = LIS.getInterval(Reg);
1022 // Iterate over instructions using Reg.
1023 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
1024 MachineInstr *MI = RI.skipInstruction();) {
1026 // Debug values are not allowed to affect codegen.
1027 if (MI->isDebugValue()) {
1028 // Modify DBG_VALUE now that the value is in a spill slot.
1029 uint64_t Offset = MI->getOperand(1).getImm();
1030 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1031 DebugLoc DL = MI->getDebugLoc();
1032 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
1033 Offset, MDPtr, DL)) {
1034 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1035 MachineBasicBlock *MBB = MI->getParent();
1036 MBB->insert(MBB->erase(MI), NewDV);
1038 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
1039 MI->eraseFromParent();
1044 // Ignore copies to/from snippets. We'll delete them.
1045 if (SnippetCopies.count(MI))
1048 // Stack slot accesses may coalesce away.
1049 if (coalesceStackAccess(MI, Reg))
1052 // Analyze instruction.
1054 SmallVector<unsigned, 8> Ops;
1055 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
1057 // Find the slot index where this instruction reads and writes OldLI.
1058 // This is usually the def slot, except for tied early clobbers.
1059 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
1060 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getUseIndex()))
1061 if (SlotIndex::isSameInstr(Idx, VNI->def))
1064 // Check for a sibling copy.
1065 unsigned SibReg = isFullCopyOf(MI, Reg);
1066 if (SibReg && isSibling(SibReg)) {
1067 // This may actually be a copy between snippets.
1068 if (isRegToSpill(SibReg)) {
1069 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1070 SnippetCopies.insert(MI);
1074 // Hoist the spill of a sib-reg copy.
1075 if (hoistSpill(OldLI, MI)) {
1076 // This COPY is now dead, the value is already in the stack slot.
1077 MI->getOperand(0).setIsDead();
1078 DeadDefs.push_back(MI);
1082 // This is a reload for a sib-reg copy. Drop spills downstream.
1083 LiveInterval &SibLI = LIS.getInterval(SibReg);
1084 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1085 // The COPY will fold to a reload below.
1089 // Attempt to fold memory ops.
1090 if (foldMemoryOperand(MI, Ops))
1093 // Allocate interval around instruction.
1094 // FIXME: Infer regclass from instruction alone.
1095 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
1096 NewLI.markNotSpillable();
1099 insertReload(NewLI, Idx, MI);
1101 // Rewrite instruction operands.
1102 bool hasLiveDef = false;
1103 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1104 MachineOperand &MO = MI->getOperand(Ops[i]);
1105 MO.setReg(NewLI.reg);
1107 if (!MI->isRegTiedToDefOperand(Ops[i]))
1114 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
1116 // FIXME: Use a second vreg if instruction has no tied ops.
1117 if (Writes && hasLiveDef)
1118 insertSpill(NewLI, OldLI, Idx, MI);
1120 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
1124 /// spillAll - Spill all registers remaining after rematerialization.
1125 void InlineSpiller::spillAll() {
1126 // Update LiveStacks now that we are committed to spilling.
1127 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1128 StackSlot = VRM.assignVirt2StackSlot(Original);
1129 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1130 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
1132 StackInt = &LSS.getInterval(StackSlot);
1134 if (Original != Edit->getReg())
1135 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1137 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1138 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1139 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
1140 StackInt->getValNumInfo(0));
1141 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1143 // Spill around uses of all RegsToSpill.
1144 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1145 spillAroundUses(RegsToSpill[i]);
1147 // Hoisted spills may cause dead code.
1148 if (!DeadDefs.empty()) {
1149 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1150 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
1153 // Finally delete the SnippetCopies.
1154 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1155 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1156 MachineInstr *MI = RI.skipInstruction();) {
1157 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1158 // FIXME: Do this with a LiveRangeEdit callback.
1159 VRM.RemoveMachineInstrFromMaps(MI);
1160 LIS.RemoveMachineInstrFromMaps(MI);
1161 MI->eraseFromParent();
1165 // Delete all spilled registers.
1166 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1167 Edit->eraseVirtReg(RegsToSpill[i], LIS);
1170 void InlineSpiller::spill(LiveRangeEdit &edit) {
1173 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1174 && "Trying to spill a stack slot.");
1175 // Share a stack slot among all descendants of Original.
1176 Original = VRM.getOriginal(edit.getReg());
1177 StackSlot = VRM.getStackSlot(Original);
1180 DEBUG(dbgs() << "Inline spilling "
1181 << MRI.getRegClass(edit.getReg())->getName()
1182 << ':' << edit.getParent() << "\nFrom original "
1183 << LIS.getInterval(Original) << '\n');
1184 assert(edit.getParent().isSpillable() &&
1185 "Attempting to spill already spilled value.");
1186 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1188 collectRegsToSpill();
1189 analyzeSiblingValues();
1192 // Remat may handle everything.
1193 if (!RegsToSpill.empty())
1196 Edit->calculateRegClassAndHint(MF, LIS, Loops);