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 "llvm/CodeGen/LiveRangeEdit.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/CodeGen/CalcSpillWeights.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/VirtRegMap.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetInstrInfo.h"
27 STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
28 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
29 STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
31 void LiveRangeEdit::Delegate::anchor() { }
33 LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(unsigned OldReg) {
34 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
36 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
38 LiveInterval &LI = LIS.createEmptyInterval(VReg);
42 unsigned LiveRangeEdit::createFrom(unsigned OldReg) {
43 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
45 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
50 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
51 const MachineInstr *DefMI,
53 assert(DefMI && "Missing instruction");
54 ScannedRemattable = true;
55 if (!TII.isTriviallyReMaterializable(DefMI, aa))
57 Remattable.insert(VNI);
61 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
62 for (LiveInterval::vni_iterator I = getParent().vni_begin(),
63 E = getParent().vni_end(); I != E; ++I) {
67 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
70 checkRematerializable(VNI, DefMI, aa);
72 ScannedRemattable = true;
75 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
76 if (!ScannedRemattable)
78 return !Remattable.empty();
81 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
82 /// OrigIdx are also available with the same value at UseIdx.
83 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
85 SlotIndex UseIdx) const {
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.readsReg())
93 // We can't remat physreg uses, unless it is a constant.
94 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
95 if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent()))
100 LiveInterval &li = LIS.getInterval(MO.getReg());
101 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
105 // Don't allow rematerialization immediately after the original def.
106 // It would be incorrect if OrigMI redefines the register.
108 if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
111 if (OVNI != li.getVNInfoAt(UseIdx))
117 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
120 assert(ScannedRemattable && "Call anyRematerializable first");
122 // Use scanRemattable info.
123 if (!Remattable.count(RM.ParentVNI))
126 // No defining instruction provided.
129 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
131 DefIdx = RM.ParentVNI->def;
132 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
133 assert(RM.OrigMI && "No defining instruction for remattable value");
136 // If only cheap remats were requested, bail out early.
137 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
140 // Verify that all used registers are available with the same values.
141 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
147 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
148 MachineBasicBlock::iterator MI,
151 const TargetRegisterInfo &tri,
153 assert(RM.OrigMI && "Invalid remat");
154 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
155 Rematted.insert(RM.ParentVNI);
156 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
160 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
161 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
162 LIS.removeInterval(Reg);
165 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
166 SmallVectorImpl<MachineInstr*> &Dead) {
167 MachineInstr *DefMI = 0, *UseMI = 0;
169 // Check that there is a single def and a single use.
170 for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) {
171 MachineInstr *MI = MO.getParent();
173 if (DefMI && DefMI != MI)
175 if (!MI->canFoldAsLoad())
178 } else if (!MO.isUndef()) {
179 if (UseMI && UseMI != MI)
181 // FIXME: Targets don't know how to fold subreg uses.
187 if (!DefMI || !UseMI)
190 // Since we're moving the DefMI load, make sure we're not extending any live
192 if (!allUsesAvailableAt(DefMI,
193 LIS.getInstructionIndex(DefMI),
194 LIS.getInstructionIndex(UseMI)))
197 // We also need to make sure it is safe to move the load.
198 // Assume there are stores between DefMI and UseMI.
199 bool SawStore = true;
200 if (!DefMI->isSafeToMove(&TII, 0, SawStore))
203 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
204 << " into single use: " << *UseMI);
206 SmallVector<unsigned, 8> Ops;
207 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
210 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
213 DEBUG(dbgs() << " folded: " << *FoldMI);
214 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
215 UseMI->eraseFromParent();
216 DefMI->addRegisterDead(LI->reg, 0);
217 Dead.push_back(DefMI);
222 /// Find all live intervals that need to shrink, then remove the instruction.
223 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
224 assert(MI->allDefsAreDead() && "Def isn't really dead");
225 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
227 // Never delete a bundled instruction.
228 if (MI->isBundled()) {
231 // Never delete inline asm.
232 if (MI->isInlineAsm()) {
233 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
237 // Use the same criteria as DeadMachineInstructionElim.
238 bool SawStore = false;
239 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
240 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
244 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
246 // Collect virtual registers to be erased after MI is gone.
247 SmallVector<unsigned, 8> RegsToErase;
248 bool ReadsPhysRegs = false;
250 // Check for live intervals that may shrink
251 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
252 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
255 unsigned Reg = MOI->getReg();
256 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
257 // Check if MI reads any unreserved physregs.
258 if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
259 ReadsPhysRegs = true;
260 else if (MOI->isDef()) {
261 for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo());
262 Units.isValid(); ++Units) {
263 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
264 if (VNInfo *VNI = LR->getVNInfoAt(Idx))
265 LR->removeValNo(VNI);
271 LiveInterval &LI = LIS.getInterval(Reg);
273 // Shrink read registers, unless it is likely to be expensive and
274 // unlikely to change anything. We typically don't want to shrink the
275 // PIC base register that has lots of uses everywhere.
276 // Always shrink COPY uses that probably come from live range splitting.
277 if (MI->readsVirtualRegister(Reg) &&
278 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
279 LI.Query(Idx).isKill()))
280 ToShrink.insert(&LI);
282 // Remove defined value.
284 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
286 TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
289 RegsToErase.push_back(Reg);
294 // Currently, we don't support DCE of physreg live ranges. If MI reads
295 // any unreserved physregs, don't erase the instruction, but turn it into
296 // a KILL instead. This way, the physreg live ranges don't end up
298 // FIXME: It would be better to have something like shrinkToUses() for
299 // physregs. That could potentially enable more DCE and it would free up
300 // the physreg. It would not happen often, though.
302 MI->setDesc(TII.get(TargetOpcode::KILL));
303 // Remove all operands that aren't physregs.
304 for (unsigned i = MI->getNumOperands(); i; --i) {
305 const MachineOperand &MO = MI->getOperand(i-1);
306 if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
308 MI->RemoveOperand(i-1);
310 DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
313 TheDelegate->LRE_WillEraseInstruction(MI);
314 LIS.RemoveMachineInstrFromMaps(MI);
315 MI->eraseFromParent();
319 // Erase any virtregs that are now empty and unused. There may be <undef>
320 // uses around. Keep the empty live range in that case.
321 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
322 unsigned Reg = RegsToErase[i];
323 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
324 ToShrink.remove(&LIS.getInterval(Reg));
330 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
331 ArrayRef<unsigned> RegsBeingSpilled) {
332 ToShrinkSet ToShrink;
335 // Erase all dead defs.
336 while (!Dead.empty())
337 eliminateDeadDef(Dead.pop_back_val(), ToShrink);
339 if (ToShrink.empty())
342 // Shrink just one live interval. Then delete new dead defs.
343 LiveInterval *LI = ToShrink.back();
345 if (foldAsLoad(LI, Dead))
348 TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
349 if (!LIS.shrinkToUses(LI, &Dead))
352 // Don't create new intervals for a register being spilled.
353 // The new intervals would have to be spilled anyway so its not worth it.
354 // Also they currently aren't spilled so creating them and not spilling
355 // them results in incorrect code.
356 bool BeingSpilled = false;
357 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
358 if (LI->reg == RegsBeingSpilled[i]) {
364 if (BeingSpilled) continue;
366 // LI may have been separated, create new intervals.
367 LI->RenumberValues();
368 ConnectedVNInfoEqClasses ConEQ(LIS);
369 unsigned NumComp = ConEQ.Classify(LI);
373 bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
374 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
375 SmallVector<LiveInterval*, 8> Dups(1, LI);
376 for (unsigned i = 1; i != NumComp; ++i) {
377 Dups.push_back(&createEmptyIntervalFrom(LI->reg));
378 // If LI is an original interval that hasn't been split yet, make the new
379 // intervals their own originals instead of referring to LI. The original
380 // interval must contain all the split products, and LI doesn't.
382 VRM->setIsSplitFromReg(Dups.back()->reg, 0);
384 TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
386 ConEQ.Distribute(&Dups[0], MRI);
388 for (unsigned i = 0; i != NumComp; ++i)
389 dbgs() << '\t' << *Dups[i] << '\n';
394 // Keep track of new virtual registers created via
395 // MachineRegisterInfo::createVirtualRegister.
397 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
402 NewRegs.push_back(VReg);
406 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
407 const MachineLoopInfo &Loops,
408 const MachineBlockFrequencyInfo &MBFI) {
409 VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI);
410 for (unsigned I = 0, Size = size(); I < Size; ++I) {
411 LiveInterval &LI = LIS.getInterval(get(I));
412 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
413 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
414 << MRI.getRegClass(LI.reg)->getName() << '\n');
415 VRAI.calculateSpillWeightAndHint(LI);