1//===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The LiveRangeEdit class represents changes done to a virtual register when it
10// is spilled or split.
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/LiveRangeEdit.h"
14#include "llvm/ADT/Statistic.h"
15#include "llvm/CodeGen/CalcSpillWeights.h"
16#include "llvm/CodeGen/LiveIntervals.h"
17#include "llvm/CodeGen/MachineRegisterInfo.h"
18#include "llvm/CodeGen/TargetInstrInfo.h"
19#include "llvm/CodeGen/VirtRegMap.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/raw_ostream.h"
22
23using namespace llvm;
24
25#define DEBUG_TYPE "regalloc"
26
27STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
28STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
29STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
30STATISTIC(NumReMaterialization, "Number of instructions rematerialized");
31
32void LiveRangeEdit::Delegate::anchor() { }
33
34LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(Register OldReg,
35 bool createSubRanges) {
36 Register VReg = MRI.cloneVirtualRegister(VReg: OldReg);
37 if (VRM)
38 VRM->setIsSplitFromReg(virtReg: VReg, SReg: VRM->getOriginal(VirtReg: OldReg));
39
40 LiveInterval &LI = LIS.createEmptyInterval(Reg: VReg);
41 if (Parent && !Parent->isSpillable())
42 LI.markNotSpillable();
43 if (createSubRanges) {
44 // Create empty subranges if the OldReg's interval has them. Do not create
45 // the main range here---it will be constructed later after the subranges
46 // have been finalized.
47 LiveInterval &OldLI = LIS.getInterval(Reg: OldReg);
48 VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
49 for (LiveInterval::SubRange &S : OldLI.subranges())
50 LI.createSubRange(Allocator&: Alloc, LaneMask: S.LaneMask);
51 }
52 return LI;
53}
54
55Register LiveRangeEdit::createFrom(Register OldReg) {
56 Register VReg = MRI.cloneVirtualRegister(VReg: OldReg);
57 if (VRM) {
58 VRM->setIsSplitFromReg(virtReg: VReg, SReg: VRM->getOriginal(VirtReg: OldReg));
59 }
60 // FIXME: Getting the interval here actually computes it.
61 // In theory, this may not be what we want, but in practice
62 // the createEmptyIntervalFrom API is used when this is not
63 // the case. Generally speaking we just want to annotate the
64 // LiveInterval when it gets created but we cannot do that at
65 // the moment.
66 if (Parent && !Parent->isSpillable())
67 LIS.getInterval(Reg: VReg).markNotSpillable();
68 return VReg;
69}
70
71bool LiveRangeEdit::canRematerializeAt(Remat &RM, SlotIndex UseIdx) {
72 assert(RM.OrigMI && "No defining instruction for remattable value");
73
74 if (!TII.isReMaterializable(MI: *RM.OrigMI))
75 return false;
76
77 // Verify that all used registers are available with the same values.
78 if (!VirtRegAuxInfo::allUsesAvailableAt(MI: RM.OrigMI, UseIdx, LIS, MRI, TII))
79 return false;
80
81 return true;
82}
83
84SlotIndex LiveRangeEdit::rematerializeAt(
85 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg,
86 const Remat &RM, const TargetRegisterInfo &tri, bool Late, unsigned SubIdx,
87 MachineInstr *ReplaceIndexMI, LaneBitmask UsedLanes) {
88 assert(RM.OrigMI && "Invalid remat");
89 TII.reMaterialize(MBB, MI, DestReg, SubIdx, Orig: *RM.OrigMI, UsedLanes);
90 // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
91 // to false anyway in case the isDead flag of RM.OrigMI's dest register
92 // is true.
93 (*--MI).clearRegisterDeads(Reg: DestReg);
94 Rematted.insert(Ptr: RM.ParentVNI);
95 ++NumReMaterialization;
96
97 bool EarlyClobber = MI->getOperand(i: 0).isEarlyClobber();
98 if (ReplaceIndexMI)
99 return LIS.ReplaceMachineInstrInMaps(MI&: *ReplaceIndexMI, NewMI&: *MI)
100 .getRegSlot(EC: EarlyClobber);
101 return LIS.getSlotIndexes()->insertMachineInstrInMaps(MI&: *MI, Late).getRegSlot(
102 EC: EarlyClobber);
103}
104
105void LiveRangeEdit::eraseVirtReg(Register Reg) {
106 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
107 LIS.removeInterval(Reg);
108}
109
110bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
111 SmallVectorImpl<MachineInstr*> &Dead) {
112 MachineInstr *DefMI = nullptr, *UseMI = nullptr;
113
114 // Check that there is a single def and a single use.
115 for (MachineOperand &MO : MRI.reg_nodbg_operands(Reg: LI->reg())) {
116 MachineInstr *MI = MO.getParent();
117 if (MO.isDef()) {
118 if (DefMI && DefMI != MI)
119 return false;
120 if (!MI->canFoldAsLoad())
121 return false;
122 DefMI = MI;
123 } else if (!MO.isUndef()) {
124 if (UseMI && UseMI != MI)
125 return false;
126 // FIXME: Targets don't know how to fold subreg uses.
127 if (MO.getSubReg())
128 return false;
129 UseMI = MI;
130 }
131 }
132 if (!DefMI || !UseMI)
133 return false;
134
135 // Since we're moving the DefMI load, make sure we're not extending any live
136 // ranges.
137 if (!VirtRegAuxInfo::allUsesAvailableAt(
138 MI: DefMI, UseIdx: LIS.getInstructionIndex(Instr: *UseMI), LIS, MRI, TII))
139 return false;
140
141 // We also need to make sure it is safe to move the load.
142 // Assume there are stores between DefMI and UseMI.
143 bool SawStore = true;
144 if (!DefMI->isSafeToMove(SawStore))
145 return false;
146
147 LLVM_DEBUG(dbgs() << "Try to fold single def: " << *DefMI
148 << " into single use: " << *UseMI);
149
150 SmallVector<unsigned, 8> Ops;
151 if (UseMI->readsWritesVirtualRegister(Reg: LI->reg(), Ops: &Ops).second)
152 return false;
153
154 MachineInstr *FoldMI = TII.foldMemoryOperand(MI&: *UseMI, Ops, LoadMI&: *DefMI, LIS: &LIS);
155 if (!FoldMI)
156 return false;
157 LLVM_DEBUG(dbgs() << " folded: " << *FoldMI);
158 LIS.ReplaceMachineInstrInMaps(MI&: *UseMI, NewMI&: *FoldMI);
159 // Update the call info.
160 if (UseMI->shouldUpdateAdditionalCallInfo())
161 UseMI->getMF()->moveAdditionalCallInfo(Old: UseMI, New: FoldMI);
162 UseMI->eraseFromParent();
163 DefMI->addRegisterDead(Reg: LI->reg(), RegInfo: nullptr);
164 Dead.push_back(Elt: DefMI);
165 ++NumDCEFoldedLoads;
166 return true;
167}
168
169bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
170 const MachineOperand &MO) const {
171 const MachineInstr &MI = *MO.getParent();
172 SlotIndex Idx = LIS.getInstructionIndex(Instr: MI).getRegSlot();
173 if (LI.Query(Idx).isKill())
174 return true;
175 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
176 unsigned SubReg = MO.getSubReg();
177 LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubIdx: SubReg);
178 for (const LiveInterval::SubRange &S : LI.subranges()) {
179 if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill())
180 return true;
181 }
182 return false;
183}
184
185/// Find all live intervals that need to shrink, then remove the instruction.
186void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
187 assert(MI->allDefsAreDead() && "Def isn't really dead");
188 SlotIndex Idx = LIS.getInstructionIndex(Instr: *MI).getRegSlot();
189
190 // Never delete a bundled instruction.
191 if (MI->isBundled()) {
192 // TODO: Handle deleting copy bundles
193 LLVM_DEBUG(dbgs() << "Won't delete dead bundled inst: " << Idx << '\t'
194 << *MI);
195 return;
196 }
197
198 // Never delete inline asm.
199 if (MI->isInlineAsm()) {
200 LLVM_DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
201 return;
202 }
203
204 // Use the same criteria as DeadMachineInstructionElim.
205 bool SawStore = false;
206 if (!MI->isSafeToMove(SawStore)) {
207 LLVM_DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
208 return;
209 }
210
211 LLVM_DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
212
213 // Collect virtual registers to be erased after MI is gone.
214 SmallVector<Register, 8> RegsToErase;
215 bool ReadsPhysRegs = false;
216 bool isOrigDef = false;
217 Register Dest;
218 unsigned DestSubReg;
219 // Only optimize rematerialize case when the instruction has one def, since
220 // otherwise we could leave some dead defs in the code. This case is
221 // extremely rare.
222 if (VRM && MI->getOperand(i: 0).isReg() && MI->getOperand(i: 0).isDef() &&
223 MI->getDesc().getNumDefs() == 1) {
224 Dest = MI->getOperand(i: 0).getReg();
225 DestSubReg = MI->getOperand(i: 0).getSubReg();
226 Register Original = VRM->getOriginal(VirtReg: Dest);
227 LiveInterval &OrigLI = LIS.getInterval(Reg: Original);
228 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
229 // The original live-range may have been shrunk to
230 // an empty live-range. It happens when it is dead, but
231 // we still keep it around to be able to rematerialize
232 // other values that depend on it.
233 if (OrigVNI)
234 isOrigDef = SlotIndex::isSameInstr(A: OrigVNI->def, B: Idx);
235 }
236
237 bool HasLiveVRegUses = false;
238
239 // Check for live intervals that may shrink
240 for (const MachineOperand &MO : MI->operands()) {
241 if (!MO.isReg())
242 continue;
243 Register Reg = MO.getReg();
244 if (!Reg.isVirtual()) {
245 // Check if MI reads any unreserved physregs.
246 if (Reg && MO.readsReg() && !MRI.isReserved(PhysReg: Reg))
247 ReadsPhysRegs = true;
248 else if (MO.isDef())
249 LIS.removePhysRegDefAt(Reg: Reg.asMCReg(), Pos: Idx);
250 continue;
251 }
252 LiveInterval &LI = LIS.getInterval(Reg);
253
254 // Shrink read registers, unless it is likely to be expensive and
255 // unlikely to change anything. We typically don't want to shrink the
256 // PIC base register that has lots of uses everywhere.
257 // Always shrink COPY uses that probably come from live range splitting.
258 if ((MI->readsVirtualRegister(Reg) &&
259 (MO.isDef() || TII.isCopyInstr(MI: *MI))) ||
260 (MO.readsReg() && (MRI.hasOneNonDBGUse(RegNo: Reg) || useIsKill(LI, MO))))
261 ToShrink.insert(X: &LI);
262 else if (MO.readsReg())
263 HasLiveVRegUses = true;
264
265 // Remove defined value.
266 if (MO.isDef()) {
267 if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
268 TheDelegate->LRE_WillShrinkVirtReg(LI.reg());
269 LIS.removeVRegDefAt(LI, Pos: Idx);
270 if (LI.empty())
271 RegsToErase.push_back(Elt: Reg);
272 }
273 }
274
275 // If the dest of MI is an original reg and MI is reMaterializable,
276 // don't delete the inst. Replace the dest with a new reg, and keep
277 // the inst for remat of other siblings. The inst is saved in
278 // LiveRangeEdit::DeadRemats and will be deleted after all the
279 // allocations of the func are done. Note that if we keep the
280 // instruction with the original operands, that handles the physreg
281 // operand case (described just below) as well.
282 // However, immediately delete instructions which have unshrunk virtual
283 // register uses. That may provoke RA to split an interval at the KILL
284 // and later result in an invalid live segment end.
285 if (isOrigDef && DeadRemats && !HasLiveVRegUses &&
286 TII.isReMaterializable(MI: *MI)) {
287 LiveInterval &NewLI = createEmptyIntervalFrom(OldReg: Dest, createSubRanges: false);
288 VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
289 VNInfo *VNI = NewLI.getNextValue(Def: Idx, VNInfoAllocator&: Alloc);
290 NewLI.addSegment(S: LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
291
292 if (DestSubReg) {
293 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
294 auto *SR =
295 NewLI.createSubRange(Allocator&: Alloc, LaneMask: TRI->getSubRegIndexLaneMask(SubIdx: DestSubReg));
296 SR->addSegment(S: LiveInterval::Segment(Idx, Idx.getDeadSlot(),
297 SR->getNextValue(Def: Idx, VNInfoAllocator&: Alloc)));
298 }
299
300 pop_back();
301 DeadRemats->insert(Ptr: MI);
302 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
303 MI->substituteRegister(FromReg: Dest, ToReg: NewLI.reg(), SubIdx: 0, RegInfo: TRI);
304 assert(MI->registerDefIsDead(NewLI.reg(), &TRI));
305 }
306 // Currently, we don't support DCE of physreg live ranges. If MI reads
307 // any unreserved physregs, don't erase the instruction, but turn it into
308 // a KILL instead. This way, the physreg live ranges don't end up
309 // dangling.
310 // FIXME: It would be better to have something like shrinkToUses() for
311 // physregs. That could potentially enable more DCE and it would free up
312 // the physreg. It would not happen often, though.
313 else if (ReadsPhysRegs) {
314 MI->setDesc(TII.get(Opcode: TargetOpcode::KILL));
315 // Remove all operands that aren't physregs.
316 for (unsigned i = MI->getNumOperands(); i; --i) {
317 const MachineOperand &MO = MI->getOperand(i: i-1);
318 if (MO.isReg() && MO.getReg().isPhysical())
319 continue;
320 MI->removeOperand(OpNo: i-1);
321 }
322 MI->dropMemRefs(MF&: *MI->getMF());
323 LLVM_DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
324 } else {
325 if (TheDelegate)
326 TheDelegate->LRE_WillEraseInstruction(MI);
327 LIS.RemoveMachineInstrFromMaps(MI&: *MI);
328 MI->eraseFromParent();
329 ++NumDCEDeleted;
330 }
331
332 // Erase any virtregs that are now empty and unused. There may be <undef>
333 // uses around. Keep the empty live range in that case.
334 for (Register Reg : RegsToErase) {
335 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(RegNo: Reg)) {
336 ToShrink.remove(X: &LIS.getInterval(Reg));
337 eraseVirtReg(Reg);
338 }
339 }
340}
341
342void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
343 ArrayRef<Register> RegsBeingSpilled) {
344 ToShrinkSet ToShrink;
345
346 for (;;) {
347 // Erase all dead defs.
348 while (!Dead.empty())
349 eliminateDeadDef(MI: Dead.pop_back_val(), ToShrink);
350
351 if (ToShrink.empty())
352 break;
353
354 // Shrink just one live interval. Then delete new dead defs.
355 LiveInterval *LI = ToShrink.pop_back_val();
356 if (foldAsLoad(LI, Dead))
357 continue;
358 Register VReg = LI->reg();
359 if (TheDelegate)
360 TheDelegate->LRE_WillShrinkVirtReg(VReg);
361 if (!LIS.shrinkToUses(li: LI, dead: &Dead))
362 continue;
363
364 // Don't create new intervals for a register being spilled.
365 // The new intervals would have to be spilled anyway so its not worth it.
366 // Also they currently aren't spilled so creating them and not spilling
367 // them results in incorrect code.
368 if (llvm::is_contained(Range&: RegsBeingSpilled, Element: VReg))
369 continue;
370
371 // LI may have been separated, create new intervals.
372 LI->RenumberValues();
373 SmallVector<LiveInterval*, 8> SplitLIs;
374 LIS.splitSeparateComponents(LI&: *LI, SplitLIs);
375 if (!SplitLIs.empty())
376 ++NumFracRanges;
377
378 Register Original = VRM ? VRM->getOriginal(VirtReg: VReg) : Register();
379 for (const LiveInterval *SplitLI : SplitLIs) {
380 // If LI is an original interval that hasn't been split yet, make the new
381 // intervals their own originals instead of referring to LI. The original
382 // interval must contain all the split products, and LI doesn't.
383 if (Original != VReg && Original != 0)
384 VRM->setIsSplitFromReg(virtReg: SplitLI->reg(), SReg: Original);
385 if (TheDelegate)
386 TheDelegate->LRE_DidCloneVirtReg(New: SplitLI->reg(), Old: VReg);
387 }
388 }
389}
390
391// Keep track of new virtual registers created via
392// MachineRegisterInfo::createVirtualRegister.
393void
394LiveRangeEdit::MRI_NoteNewVirtualRegister(Register VReg) {
395 if (VRM)
396 VRM->grow();
397
398 NewRegs.push_back(Elt: VReg);
399}
400
401void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
402 VirtRegAuxInfo &VRAI) {
403 for (unsigned I = 0, Size = size(); I < Size; ++I) {
404 LiveInterval &LI = LIS.getInterval(Reg: get(idx: I));
405 if (MRI.recomputeRegClass(Reg: LI.reg()))
406 LLVM_DEBUG({
407 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
408 dbgs() << "Inflated " << printReg(LI.reg()) << " to "
409 << TRI->getRegClassName(MRI.getRegClass(LI.reg())) << '\n';
410 });
411 VRAI.calculateSpillWeightAndHint(LI);
412 }
413}
414