1 //===--- LiveRangeEdit.cpp - Basic tools for editing a register live range --===//
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 LiveRangeEdit class represents changes done to a virtual register when it
11 // is spilled or split.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "LiveRangeEdit.h"
16 #include "VirtRegMap.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
28 STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
29 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
30 STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
32 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg,
35 MachineRegisterInfo &MRI = VRM.getRegInfo();
36 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
38 VRM.setIsSplitFromReg(VReg, VRM.getOriginal(OldReg));
39 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
40 newRegs_.push_back(&LI);
44 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
45 const MachineInstr *DefMI,
46 const TargetInstrInfo &tii,
48 assert(DefMI && "Missing instruction");
49 scannedRemattable_ = true;
50 if (!tii.isTriviallyReMaterializable(DefMI, aa))
52 remattable_.insert(VNI);
56 void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
57 const TargetInstrInfo &tii,
59 for (LiveInterval::vni_iterator I = parent_.vni_begin(),
60 E = parent_.vni_end(); I != E; ++I) {
64 MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
67 checkRematerializable(VNI, DefMI, tii, aa);
69 scannedRemattable_ = true;
72 bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
73 const TargetInstrInfo &tii,
75 if (!scannedRemattable_)
76 scanRemattable(lis, tii, aa);
77 return !remattable_.empty();
80 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
81 /// OrigIdx are also available with the same value at UseIdx.
82 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
86 OrigIdx = OrigIdx.getRegSlot(true);
87 UseIdx = UseIdx.getRegSlot(true);
88 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
89 const MachineOperand &MO = OrigMI->getOperand(i);
90 if (!MO.isReg() || !MO.getReg() || MO.isDef())
92 // Reserved registers are OK.
93 if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
95 // We cannot depend on virtual registers in uselessRegs_.
97 for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
98 if ((*uselessRegs_)[ui]->reg == MO.getReg())
101 LiveInterval &li = lis.getInterval(MO.getReg());
102 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
105 if (OVNI != li.getVNInfoAt(UseIdx))
111 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
114 LiveIntervals &lis) {
115 assert(scannedRemattable_ && "Call anyRematerializable first");
117 // Use scanRemattable info.
118 if (!remattable_.count(RM.ParentVNI))
121 // No defining instruction provided.
124 DefIdx = lis.getInstructionIndex(RM.OrigMI);
126 DefIdx = RM.ParentVNI->def;
127 RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
128 assert(RM.OrigMI && "No defining instruction for remattable value");
131 // If only cheap remats were requested, bail out early.
132 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
135 // Verify that all used registers are available with the same values.
136 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
142 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
143 MachineBasicBlock::iterator MI,
147 const TargetInstrInfo &tii,
148 const TargetRegisterInfo &tri,
150 assert(RM.OrigMI && "Invalid remat");
151 tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
152 rematted_.insert(RM.ParentVNI);
153 return lis.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
157 void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
158 if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
159 LIS.removeInterval(Reg);
162 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
163 SmallVectorImpl<MachineInstr*> &Dead,
164 MachineRegisterInfo &MRI,
166 const TargetInstrInfo &TII) {
167 MachineInstr *DefMI = 0, *UseMI = 0;
169 // Check that there is a single def and a single use.
170 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
171 E = MRI.reg_nodbg_end(); I != E; ++I) {
172 MachineOperand &MO = I.getOperand();
173 MachineInstr *MI = MO.getParent();
175 if (DefMI && DefMI != MI)
177 if (!MI->canFoldAsLoad())
180 } else if (!MO.isUndef()) {
181 if (UseMI && UseMI != MI)
183 // FIXME: Targets don't know how to fold subreg uses.
189 if (!DefMI || !UseMI)
192 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
193 << " into single use: " << *UseMI);
195 SmallVector<unsigned, 8> Ops;
196 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
199 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
202 DEBUG(dbgs() << " folded: " << *FoldMI);
203 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
204 UseMI->eraseFromParent();
205 DefMI->addRegisterDead(LI->reg, 0);
206 Dead.push_back(DefMI);
211 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
212 LiveIntervals &LIS, VirtRegMap &VRM,
213 const TargetInstrInfo &TII,
214 ArrayRef<unsigned> RegsBeingSpilled) {
215 SetVector<LiveInterval*,
216 SmallVector<LiveInterval*, 8>,
217 SmallPtrSet<LiveInterval*, 8> > ToShrink;
218 MachineRegisterInfo &MRI = VRM.getRegInfo();
221 // Erase all dead defs.
222 while (!Dead.empty()) {
223 MachineInstr *MI = Dead.pop_back_val();
224 assert(MI->allDefsAreDead() && "Def isn't really dead");
225 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
227 // Never delete inline asm.
228 if (MI->isInlineAsm()) {
229 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
233 // Use the same criteria as DeadMachineInstructionElim.
234 bool SawStore = false;
235 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
236 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
240 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
242 // Check for live intervals that may shrink
243 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
244 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
247 unsigned Reg = MOI->getReg();
248 if (!TargetRegisterInfo::isVirtualRegister(Reg))
250 LiveInterval &LI = LIS.getInterval(Reg);
252 // Shrink read registers, unless it is likely to be expensive and
253 // unlikely to change anything. We typically don't want to shrink the
254 // PIC base register that has lots of uses everywhere.
255 // Always shrink COPY uses that probably come from live range splitting.
256 if (MI->readsVirtualRegister(Reg) &&
257 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
259 ToShrink.insert(&LI);
261 // Remove defined value.
263 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
265 delegate_->LRE_WillShrinkVirtReg(LI.reg);
268 ToShrink.remove(&LI);
269 eraseVirtReg(Reg, LIS);
276 delegate_->LRE_WillEraseInstruction(MI);
277 LIS.RemoveMachineInstrFromMaps(MI);
278 MI->eraseFromParent();
282 if (ToShrink.empty())
285 // Shrink just one live interval. Then delete new dead defs.
286 LiveInterval *LI = ToShrink.back();
288 if (foldAsLoad(LI, Dead, MRI, LIS, TII))
291 delegate_->LRE_WillShrinkVirtReg(LI->reg);
292 if (!LIS.shrinkToUses(LI, &Dead))
295 // Don't create new intervals for a register being spilled.
296 // The new intervals would have to be spilled anyway so its not worth it.
297 // Also they currently aren't spilled so creating them and not spilling
298 // them results in incorrect code.
299 bool BeingSpilled = false;
300 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
301 if (LI->reg == RegsBeingSpilled[i]) {
307 if (BeingSpilled) continue;
310 // LI may have been separated, create new intervals.
311 LI->RenumberValues(LIS);
312 ConnectedVNInfoEqClasses ConEQ(LIS);
313 unsigned NumComp = ConEQ.Classify(LI);
317 bool IsOriginal = VRM.getOriginal(LI->reg) == LI->reg;
318 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
319 SmallVector<LiveInterval*, 8> Dups(1, LI);
320 for (unsigned i = 1; i != NumComp; ++i) {
321 Dups.push_back(&createFrom(LI->reg, LIS, VRM));
322 // If LI is an original interval that hasn't been split yet, make the new
323 // intervals their own originals instead of referring to LI. The original
324 // interval must contain all the split products, and LI doesn't.
326 VRM.setIsSplitFromReg(Dups.back()->reg, 0);
328 delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
330 ConEQ.Distribute(&Dups[0], MRI);
334 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
336 const MachineLoopInfo &Loops) {
337 VirtRegAuxInfo VRAI(MF, LIS, Loops);
338 MachineRegisterInfo &MRI = MF.getRegInfo();
339 for (iterator I = begin(), E = end(); I != E; ++I) {
340 LiveInterval &LI = **I;
341 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
342 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
343 << MRI.getRegClass(LI.reg)->getName() << '\n');
344 VRAI.CalculateWeightAndHint(LI);