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 #include "llvm/CodeGen/LiveRangeEdit.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/CodeGen/CalcSpillWeights.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/VirtRegMap.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
26 #define DEBUG_TYPE "regalloc"
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::createEmptyIntervalFrom(unsigned OldReg) {
35 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
37 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
39 LiveInterval &LI = LIS.createEmptyInterval(VReg);
43 unsigned LiveRangeEdit::createFrom(unsigned OldReg) {
44 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
46 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
51 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
52 const MachineInstr *DefMI,
54 assert(DefMI && "Missing instruction");
55 ScannedRemattable = true;
56 if (!TII.isTriviallyReMaterializable(DefMI, aa))
58 Remattable.insert(VNI);
62 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
63 for (LiveInterval::vni_iterator I = getParent().vni_begin(),
64 E = getParent().vni_end(); I != E; ++I) {
68 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
71 checkRematerializable(VNI, DefMI, aa);
73 ScannedRemattable = true;
76 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
77 if (!ScannedRemattable)
79 return !Remattable.empty();
82 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
83 /// OrigIdx are also available with the same value at UseIdx.
84 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
86 SlotIndex UseIdx) const {
87 OrigIdx = OrigIdx.getRegSlot(true);
88 UseIdx = UseIdx.getRegSlot(true);
89 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
90 const MachineOperand &MO = OrigMI->getOperand(i);
91 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
94 // We can't remat physreg uses, unless it is a constant.
95 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
96 if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent()))
101 LiveInterval &li = LIS.getInterval(MO.getReg());
102 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
106 // Don't allow rematerialization immediately after the original def.
107 // It would be incorrect if OrigMI redefines the register.
109 if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
112 if (OVNI != li.getVNInfoAt(UseIdx))
118 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
121 assert(ScannedRemattable && "Call anyRematerializable first");
123 // Use scanRemattable info.
124 if (!Remattable.count(RM.ParentVNI))
127 // No defining instruction provided.
130 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
132 DefIdx = RM.ParentVNI->def;
133 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
134 assert(RM.OrigMI && "No defining instruction for remattable value");
137 // If only cheap remats were requested, bail out early.
138 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
141 // Verify that all used registers are available with the same values.
142 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
148 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
149 MachineBasicBlock::iterator MI,
152 const TargetRegisterInfo &tri,
154 assert(RM.OrigMI && "Invalid remat");
155 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
156 Rematted.insert(RM.ParentVNI);
157 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
161 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
162 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
163 LIS.removeInterval(Reg);
166 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
167 SmallVectorImpl<MachineInstr*> &Dead) {
168 MachineInstr *DefMI = nullptr, *UseMI = nullptr;
170 // Check that there is a single def and a single use.
171 for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) {
172 MachineInstr *MI = MO.getParent();
174 if (DefMI && DefMI != MI)
176 if (!MI->canFoldAsLoad())
179 } else if (!MO.isUndef()) {
180 if (UseMI && UseMI != MI)
182 // FIXME: Targets don't know how to fold subreg uses.
188 if (!DefMI || !UseMI)
191 // Since we're moving the DefMI load, make sure we're not extending any live
193 if (!allUsesAvailableAt(DefMI,
194 LIS.getInstructionIndex(DefMI),
195 LIS.getInstructionIndex(UseMI)))
198 // We also need to make sure it is safe to move the load.
199 // Assume there are stores between DefMI and UseMI.
200 bool SawStore = true;
201 if (!DefMI->isSafeToMove(&TII, nullptr, SawStore))
204 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
205 << " into single use: " << *UseMI);
207 SmallVector<unsigned, 8> Ops;
208 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
211 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
214 DEBUG(dbgs() << " folded: " << *FoldMI);
215 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
216 UseMI->eraseFromParent();
217 DefMI->addRegisterDead(LI->reg, nullptr);
218 Dead.push_back(DefMI);
223 /// Find all live intervals that need to shrink, then remove the instruction.
224 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
225 assert(MI->allDefsAreDead() && "Def isn't really dead");
226 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
228 // Never delete a bundled instruction.
229 if (MI->isBundled()) {
232 // Never delete inline asm.
233 if (MI->isInlineAsm()) {
234 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
238 // Use the same criteria as DeadMachineInstructionElim.
239 bool SawStore = false;
240 if (!MI->isSafeToMove(&TII, nullptr, SawStore)) {
241 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
245 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
247 // Collect virtual registers to be erased after MI is gone.
248 SmallVector<unsigned, 8> RegsToErase;
249 bool ReadsPhysRegs = false;
251 // Check for live intervals that may shrink
252 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
253 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
256 unsigned Reg = MOI->getReg();
257 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
258 // Check if MI reads any unreserved physregs.
259 if (Reg && MOI->readsReg() && !MRI.isReserved(Reg))
260 ReadsPhysRegs = true;
261 else if (MOI->isDef()) {
262 for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo());
263 Units.isValid(); ++Units) {
264 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
265 if (VNInfo *VNI = LR->getVNInfoAt(Idx))
266 LR->removeValNo(VNI);
272 LiveInterval &LI = LIS.getInterval(Reg);
274 // Shrink read registers, unless it is likely to be expensive and
275 // unlikely to change anything. We typically don't want to shrink the
276 // PIC base register that has lots of uses everywhere.
277 // Always shrink COPY uses that probably come from live range splitting.
278 if (MI->readsVirtualRegister(Reg) &&
279 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
280 LI.Query(Idx).isKill()))
281 ToShrink.insert(&LI);
283 // Remove defined value.
285 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
287 TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
290 RegsToErase.push_back(Reg);
295 // Currently, we don't support DCE of physreg live ranges. If MI reads
296 // any unreserved physregs, don't erase the instruction, but turn it into
297 // a KILL instead. This way, the physreg live ranges don't end up
299 // FIXME: It would be better to have something like shrinkToUses() for
300 // physregs. That could potentially enable more DCE and it would free up
301 // the physreg. It would not happen often, though.
303 MI->setDesc(TII.get(TargetOpcode::KILL));
304 // Remove all operands that aren't physregs.
305 for (unsigned i = MI->getNumOperands(); i; --i) {
306 const MachineOperand &MO = MI->getOperand(i-1);
307 if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
309 MI->RemoveOperand(i-1);
311 DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
314 TheDelegate->LRE_WillEraseInstruction(MI);
315 LIS.RemoveMachineInstrFromMaps(MI);
316 MI->eraseFromParent();
320 // Erase any virtregs that are now empty and unused. There may be <undef>
321 // uses around. Keep the empty live range in that case.
322 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
323 unsigned Reg = RegsToErase[i];
324 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
325 ToShrink.remove(&LIS.getInterval(Reg));
331 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
332 ArrayRef<unsigned> RegsBeingSpilled) {
333 ToShrinkSet ToShrink;
336 // Erase all dead defs.
337 while (!Dead.empty())
338 eliminateDeadDef(Dead.pop_back_val(), ToShrink);
340 if (ToShrink.empty())
343 // Shrink just one live interval. Then delete new dead defs.
344 LiveInterval *LI = ToShrink.back();
346 if (foldAsLoad(LI, Dead))
349 TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
350 if (!LIS.shrinkToUses(LI, &Dead))
353 // Don't create new intervals for a register being spilled.
354 // The new intervals would have to be spilled anyway so its not worth it.
355 // Also they currently aren't spilled so creating them and not spilling
356 // them results in incorrect code.
357 bool BeingSpilled = false;
358 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
359 if (LI->reg == RegsBeingSpilled[i]) {
365 if (BeingSpilled) continue;
367 // LI may have been separated, create new intervals.
368 LI->RenumberValues();
369 ConnectedVNInfoEqClasses ConEQ(LIS);
370 unsigned NumComp = ConEQ.Classify(LI);
374 bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
375 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
376 SmallVector<LiveInterval*, 8> Dups(1, LI);
377 for (unsigned i = 1; i != NumComp; ++i) {
378 Dups.push_back(&createEmptyIntervalFrom(LI->reg));
379 // If LI is an original interval that hasn't been split yet, make the new
380 // intervals their own originals instead of referring to LI. The original
381 // interval must contain all the split products, and LI doesn't.
383 VRM->setIsSplitFromReg(Dups.back()->reg, 0);
385 TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
387 ConEQ.Distribute(&Dups[0], MRI);
389 for (unsigned i = 0; i != NumComp; ++i)
390 dbgs() << '\t' << *Dups[i] << '\n';
395 // Keep track of new virtual registers created via
396 // MachineRegisterInfo::createVirtualRegister.
398 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg)
403 NewRegs.push_back(VReg);
407 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
408 const MachineLoopInfo &Loops,
409 const MachineBlockFrequencyInfo &MBFI) {
410 VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI);
411 for (unsigned I = 0, Size = size(); I < Size; ++I) {
412 LiveInterval &LI = LIS.getInterval(get(I));
413 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
414 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
415 << MRI.getRegClass(LI.reg)->getName() << '\n');
416 VRAI.calculateSpillWeightAndHint(LI);