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 "VirtRegMap.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveRangeEdit.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 void LiveRangeEdit::Delegate::anchor() { }
34 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) {
35 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
38 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
40 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
41 newRegs_.push_back(&LI);
45 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
46 const MachineInstr *DefMI,
48 assert(DefMI && "Missing instruction");
49 scannedRemattable_ = true;
50 if (!TII.isTriviallyReMaterializable(DefMI, aa))
52 remattable_.insert(VNI);
56 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
57 for (LiveInterval::vni_iterator I = parent_.vni_begin(),
58 E = parent_.vni_end(); I != E; ++I) {
62 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
65 checkRematerializable(VNI, DefMI, aa);
67 scannedRemattable_ = true;
70 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
71 if (!scannedRemattable_)
73 return !remattable_.empty();
76 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
77 /// OrigIdx are also available with the same value at UseIdx.
78 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
81 OrigIdx = OrigIdx.getRegSlot(true);
82 UseIdx = UseIdx.getRegSlot(true);
83 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
84 const MachineOperand &MO = OrigMI->getOperand(i);
85 if (!MO.isReg() || !MO.getReg() || MO.isDef())
87 // Reserved registers are OK.
88 if (MO.isUndef() || !LIS.hasInterval(MO.getReg()))
91 LiveInterval &li = LIS.getInterval(MO.getReg());
92 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
95 if (OVNI != li.getVNInfoAt(UseIdx))
101 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
104 assert(scannedRemattable_ && "Call anyRematerializable first");
106 // Use scanRemattable info.
107 if (!remattable_.count(RM.ParentVNI))
110 // No defining instruction provided.
113 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
115 DefIdx = RM.ParentVNI->def;
116 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
117 assert(RM.OrigMI && "No defining instruction for remattable value");
120 // If only cheap remats were requested, bail out early.
121 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
124 // Verify that all used registers are available with the same values.
125 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
131 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
132 MachineBasicBlock::iterator MI,
135 const TargetRegisterInfo &tri,
137 assert(RM.OrigMI && "Invalid remat");
138 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
139 rematted_.insert(RM.ParentVNI);
140 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
144 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
145 if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
146 LIS.removeInterval(Reg);
149 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
150 SmallVectorImpl<MachineInstr*> &Dead) {
151 MachineInstr *DefMI = 0, *UseMI = 0;
153 // Check that there is a single def and a single use.
154 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
155 E = MRI.reg_nodbg_end(); I != E; ++I) {
156 MachineOperand &MO = I.getOperand();
157 MachineInstr *MI = MO.getParent();
159 if (DefMI && DefMI != MI)
161 if (!MI->canFoldAsLoad())
164 } else if (!MO.isUndef()) {
165 if (UseMI && UseMI != MI)
167 // FIXME: Targets don't know how to fold subreg uses.
173 if (!DefMI || !UseMI)
176 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
177 << " into single use: " << *UseMI);
179 SmallVector<unsigned, 8> Ops;
180 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
183 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
186 DEBUG(dbgs() << " folded: " << *FoldMI);
187 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
188 UseMI->eraseFromParent();
189 DefMI->addRegisterDead(LI->reg, 0);
190 Dead.push_back(DefMI);
195 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
196 ArrayRef<unsigned> RegsBeingSpilled) {
197 SetVector<LiveInterval*,
198 SmallVector<LiveInterval*, 8>,
199 SmallPtrSet<LiveInterval*, 8> > ToShrink;
202 // Erase all dead defs.
203 while (!Dead.empty()) {
204 MachineInstr *MI = Dead.pop_back_val();
205 assert(MI->allDefsAreDead() && "Def isn't really dead");
206 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
208 // Never delete inline asm.
209 if (MI->isInlineAsm()) {
210 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
214 // Use the same criteria as DeadMachineInstructionElim.
215 bool SawStore = false;
216 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
217 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
221 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
223 // Check for live intervals that may shrink
224 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
225 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
228 unsigned Reg = MOI->getReg();
229 if (!TargetRegisterInfo::isVirtualRegister(Reg))
231 LiveInterval &LI = LIS.getInterval(Reg);
233 // Shrink read registers, unless it is likely to be expensive and
234 // unlikely to change anything. We typically don't want to shrink the
235 // PIC base register that has lots of uses everywhere.
236 // Always shrink COPY uses that probably come from live range splitting.
237 if (MI->readsVirtualRegister(Reg) &&
238 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
240 ToShrink.insert(&LI);
242 // Remove defined value.
244 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
246 delegate_->LRE_WillShrinkVirtReg(LI.reg);
249 ToShrink.remove(&LI);
257 delegate_->LRE_WillEraseInstruction(MI);
258 LIS.RemoveMachineInstrFromMaps(MI);
259 MI->eraseFromParent();
263 if (ToShrink.empty())
266 // Shrink just one live interval. Then delete new dead defs.
267 LiveInterval *LI = ToShrink.back();
269 if (foldAsLoad(LI, Dead))
272 delegate_->LRE_WillShrinkVirtReg(LI->reg);
273 if (!LIS.shrinkToUses(LI, &Dead))
276 // Don't create new intervals for a register being spilled.
277 // The new intervals would have to be spilled anyway so its not worth it.
278 // Also they currently aren't spilled so creating them and not spilling
279 // them results in incorrect code.
280 bool BeingSpilled = false;
281 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
282 if (LI->reg == RegsBeingSpilled[i]) {
288 if (BeingSpilled) continue;
290 // LI may have been separated, create new intervals.
291 LI->RenumberValues(LIS);
292 ConnectedVNInfoEqClasses ConEQ(LIS);
293 unsigned NumComp = ConEQ.Classify(LI);
297 bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
298 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
299 SmallVector<LiveInterval*, 8> Dups(1, LI);
300 for (unsigned i = 1; i != NumComp; ++i) {
301 Dups.push_back(&createFrom(LI->reg));
302 // If LI is an original interval that hasn't been split yet, make the new
303 // intervals their own originals instead of referring to LI. The original
304 // interval must contain all the split products, and LI doesn't.
306 VRM->setIsSplitFromReg(Dups.back()->reg, 0);
308 delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
310 ConEQ.Distribute(&Dups[0], MRI);
314 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
315 const MachineLoopInfo &Loops) {
316 VirtRegAuxInfo VRAI(MF, LIS, Loops);
317 for (iterator I = begin(), E = end(); I != E; ++I) {
318 LiveInterval &LI = **I;
319 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
320 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
321 << MRI.getRegClass(LI.reg)->getName() << '\n');
322 VRAI.CalculateWeightAndHint(LI);