1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
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
7 //===----------------------------------------------------------------------===//
9 // The LiveRangeEdit class represents changes done to a virtual register when it
10 // is spilled or split.
11 //===----------------------------------------------------------------------===//
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"
25 #define DEBUG_TYPE "regalloc"
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 bool createSubRanges
) {
35 Register VReg
= MRI
.createVirtualRegister(MRI
.getRegClass(OldReg
));
37 VRM
->setIsSplitFromReg(VReg
, VRM
->getOriginal(OldReg
));
39 LiveInterval
&LI
= LIS
.createEmptyInterval(VReg
);
40 if (Parent
&& !Parent
->isSpillable())
41 LI
.markNotSpillable();
42 if (createSubRanges
) {
43 // Create empty subranges if the OldReg's interval has them. Do not create
44 // the main range here---it will be constructed later after the subranges
45 // have been finalized.
46 LiveInterval
&OldLI
= LIS
.getInterval(OldReg
);
47 VNInfo::Allocator
&Alloc
= LIS
.getVNInfoAllocator();
48 for (LiveInterval::SubRange
&S
: OldLI
.subranges())
49 LI
.createSubRange(Alloc
, S
.LaneMask
);
54 unsigned LiveRangeEdit::createFrom(unsigned OldReg
) {
55 Register VReg
= MRI
.createVirtualRegister(MRI
.getRegClass(OldReg
));
57 VRM
->setIsSplitFromReg(VReg
, VRM
->getOriginal(OldReg
));
59 // FIXME: Getting the interval here actually computes it.
60 // In theory, this may not be what we want, but in practice
61 // the createEmptyIntervalFrom API is used when this is not
62 // the case. Generally speaking we just want to annotate the
63 // LiveInterval when it gets created but we cannot do that at
65 if (Parent
&& !Parent
->isSpillable())
66 LIS
.getInterval(VReg
).markNotSpillable();
70 bool LiveRangeEdit::checkRematerializable(VNInfo
*VNI
,
71 const MachineInstr
*DefMI
,
73 assert(DefMI
&& "Missing instruction");
74 ScannedRemattable
= true;
75 if (!TII
.isTriviallyReMaterializable(*DefMI
, aa
))
77 Remattable
.insert(VNI
);
81 void LiveRangeEdit::scanRemattable(AliasAnalysis
*aa
) {
82 for (VNInfo
*VNI
: getParent().valnos
) {
85 unsigned Original
= VRM
->getOriginal(getReg());
86 LiveInterval
&OrigLI
= LIS
.getInterval(Original
);
87 VNInfo
*OrigVNI
= OrigLI
.getVNInfoAt(VNI
->def
);
90 MachineInstr
*DefMI
= LIS
.getInstructionFromIndex(OrigVNI
->def
);
93 checkRematerializable(OrigVNI
, DefMI
, aa
);
95 ScannedRemattable
= true;
98 bool LiveRangeEdit::anyRematerializable(AliasAnalysis
*aa
) {
99 if (!ScannedRemattable
)
101 return !Remattable
.empty();
104 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
105 /// OrigIdx are also available with the same value at UseIdx.
106 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr
*OrigMI
,
108 SlotIndex UseIdx
) const {
109 OrigIdx
= OrigIdx
.getRegSlot(true);
110 UseIdx
= UseIdx
.getRegSlot(true);
111 for (unsigned i
= 0, e
= OrigMI
->getNumOperands(); i
!= e
; ++i
) {
112 const MachineOperand
&MO
= OrigMI
->getOperand(i
);
113 if (!MO
.isReg() || !MO
.getReg() || !MO
.readsReg())
116 // We can't remat physreg uses, unless it is a constant.
117 if (Register::isPhysicalRegister(MO
.getReg())) {
118 if (MRI
.isConstantPhysReg(MO
.getReg()))
123 LiveInterval
&li
= LIS
.getInterval(MO
.getReg());
124 const VNInfo
*OVNI
= li
.getVNInfoAt(OrigIdx
);
128 // Don't allow rematerialization immediately after the original def.
129 // It would be incorrect if OrigMI redefines the register.
131 if (SlotIndex::isSameInstr(OrigIdx
, UseIdx
))
134 if (OVNI
!= li
.getVNInfoAt(UseIdx
))
140 bool LiveRangeEdit::canRematerializeAt(Remat
&RM
, VNInfo
*OrigVNI
,
141 SlotIndex UseIdx
, bool cheapAsAMove
) {
142 assert(ScannedRemattable
&& "Call anyRematerializable first");
144 // Use scanRemattable info.
145 if (!Remattable
.count(OrigVNI
))
148 // No defining instruction provided.
150 assert(RM
.OrigMI
&& "No defining instruction for remattable value");
151 DefIdx
= LIS
.getInstructionIndex(*RM
.OrigMI
);
153 // If only cheap remats were requested, bail out early.
154 if (cheapAsAMove
&& !TII
.isAsCheapAsAMove(*RM
.OrigMI
))
157 // Verify that all used registers are available with the same values.
158 if (!allUsesAvailableAt(RM
.OrigMI
, DefIdx
, UseIdx
))
164 SlotIndex
LiveRangeEdit::rematerializeAt(MachineBasicBlock
&MBB
,
165 MachineBasicBlock::iterator MI
,
168 const TargetRegisterInfo
&tri
,
170 assert(RM
.OrigMI
&& "Invalid remat");
171 TII
.reMaterialize(MBB
, MI
, DestReg
, 0, *RM
.OrigMI
, tri
);
172 // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
173 // to false anyway in case the isDead flag of RM.OrigMI's dest register
175 (*--MI
).getOperand(0).setIsDead(false);
176 Rematted
.insert(RM
.ParentVNI
);
177 return LIS
.getSlotIndexes()->insertMachineInstrInMaps(*MI
, Late
).getRegSlot();
180 void LiveRangeEdit::eraseVirtReg(unsigned Reg
) {
181 if (TheDelegate
&& TheDelegate
->LRE_CanEraseVirtReg(Reg
))
182 LIS
.removeInterval(Reg
);
185 bool LiveRangeEdit::foldAsLoad(LiveInterval
*LI
,
186 SmallVectorImpl
<MachineInstr
*> &Dead
) {
187 MachineInstr
*DefMI
= nullptr, *UseMI
= nullptr;
189 // Check that there is a single def and a single use.
190 for (MachineOperand
&MO
: MRI
.reg_nodbg_operands(LI
->reg
)) {
191 MachineInstr
*MI
= MO
.getParent();
193 if (DefMI
&& DefMI
!= MI
)
195 if (!MI
->canFoldAsLoad())
198 } else if (!MO
.isUndef()) {
199 if (UseMI
&& UseMI
!= MI
)
201 // FIXME: Targets don't know how to fold subreg uses.
207 if (!DefMI
|| !UseMI
)
210 // Since we're moving the DefMI load, make sure we're not extending any live
212 if (!allUsesAvailableAt(DefMI
, LIS
.getInstructionIndex(*DefMI
),
213 LIS
.getInstructionIndex(*UseMI
)))
216 // We also need to make sure it is safe to move the load.
217 // Assume there are stores between DefMI and UseMI.
218 bool SawStore
= true;
219 if (!DefMI
->isSafeToMove(nullptr, SawStore
))
222 LLVM_DEBUG(dbgs() << "Try to fold single def: " << *DefMI
223 << " into single use: " << *UseMI
);
225 SmallVector
<unsigned, 8> Ops
;
226 if (UseMI
->readsWritesVirtualRegister(LI
->reg
, &Ops
).second
)
229 MachineInstr
*FoldMI
= TII
.foldMemoryOperand(*UseMI
, Ops
, *DefMI
, &LIS
);
232 LLVM_DEBUG(dbgs() << " folded: " << *FoldMI
);
233 LIS
.ReplaceMachineInstrInMaps(*UseMI
, *FoldMI
);
235 UseMI
->getMF()->moveCallSiteInfo(UseMI
, FoldMI
);
236 UseMI
->eraseFromParent();
237 DefMI
->addRegisterDead(LI
->reg
, nullptr);
238 Dead
.push_back(DefMI
);
243 bool LiveRangeEdit::useIsKill(const LiveInterval
&LI
,
244 const MachineOperand
&MO
) const {
245 const MachineInstr
&MI
= *MO
.getParent();
246 SlotIndex Idx
= LIS
.getInstructionIndex(MI
).getRegSlot();
247 if (LI
.Query(Idx
).isKill())
249 const TargetRegisterInfo
&TRI
= *MRI
.getTargetRegisterInfo();
250 unsigned SubReg
= MO
.getSubReg();
251 LaneBitmask LaneMask
= TRI
.getSubRegIndexLaneMask(SubReg
);
252 for (const LiveInterval::SubRange
&S
: LI
.subranges()) {
253 if ((S
.LaneMask
& LaneMask
).any() && S
.Query(Idx
).isKill())
259 /// Find all live intervals that need to shrink, then remove the instruction.
260 void LiveRangeEdit::eliminateDeadDef(MachineInstr
*MI
, ToShrinkSet
&ToShrink
,
262 assert(MI
->allDefsAreDead() && "Def isn't really dead");
263 SlotIndex Idx
= LIS
.getInstructionIndex(*MI
).getRegSlot();
265 // Never delete a bundled instruction.
266 if (MI
->isBundled()) {
269 // Never delete inline asm.
270 if (MI
->isInlineAsm()) {
271 LLVM_DEBUG(dbgs() << "Won't delete: " << Idx
<< '\t' << *MI
);
275 // Use the same criteria as DeadMachineInstructionElim.
276 bool SawStore
= false;
277 if (!MI
->isSafeToMove(nullptr, SawStore
)) {
278 LLVM_DEBUG(dbgs() << "Can't delete: " << Idx
<< '\t' << *MI
);
282 LLVM_DEBUG(dbgs() << "Deleting dead def " << Idx
<< '\t' << *MI
);
284 // Collect virtual registers to be erased after MI is gone.
285 SmallVector
<unsigned, 8> RegsToErase
;
286 bool ReadsPhysRegs
= false;
287 bool isOrigDef
= false;
289 // Only optimize rematerialize case when the instruction has one def, since
290 // otherwise we could leave some dead defs in the code. This case is
292 if (VRM
&& MI
->getOperand(0).isReg() && MI
->getOperand(0).isDef() &&
293 MI
->getDesc().getNumDefs() == 1) {
294 Dest
= MI
->getOperand(0).getReg();
295 unsigned Original
= VRM
->getOriginal(Dest
);
296 LiveInterval
&OrigLI
= LIS
.getInterval(Original
);
297 VNInfo
*OrigVNI
= OrigLI
.getVNInfoAt(Idx
);
298 // The original live-range may have been shrunk to
299 // an empty live-range. It happens when it is dead, but
300 // we still keep it around to be able to rematerialize
301 // other values that depend on it.
303 isOrigDef
= SlotIndex::isSameInstr(OrigVNI
->def
, Idx
);
306 // Check for live intervals that may shrink
307 for (MachineInstr::mop_iterator MOI
= MI
->operands_begin(),
308 MOE
= MI
->operands_end(); MOI
!= MOE
; ++MOI
) {
311 Register Reg
= MOI
->getReg();
312 if (!Register::isVirtualRegister(Reg
)) {
313 // Check if MI reads any unreserved physregs.
314 if (Reg
&& MOI
->readsReg() && !MRI
.isReserved(Reg
))
315 ReadsPhysRegs
= true;
316 else if (MOI
->isDef())
317 LIS
.removePhysRegDefAt(Reg
, Idx
);
320 LiveInterval
&LI
= LIS
.getInterval(Reg
);
322 // Shrink read registers, unless it is likely to be expensive and
323 // unlikely to change anything. We typically don't want to shrink the
324 // PIC base register that has lots of uses everywhere.
325 // Always shrink COPY uses that probably come from live range splitting.
326 if ((MI
->readsVirtualRegister(Reg
) && (MI
->isCopy() || MOI
->isDef())) ||
327 (MOI
->readsReg() && (MRI
.hasOneNonDBGUse(Reg
) || useIsKill(LI
, *MOI
))))
328 ToShrink
.insert(&LI
);
330 // Remove defined value.
332 if (TheDelegate
&& LI
.getVNInfoAt(Idx
) != nullptr)
333 TheDelegate
->LRE_WillShrinkVirtReg(LI
.reg
);
334 LIS
.removeVRegDefAt(LI
, Idx
);
336 RegsToErase
.push_back(Reg
);
340 // Currently, we don't support DCE of physreg live ranges. If MI reads
341 // any unreserved physregs, don't erase the instruction, but turn it into
342 // a KILL instead. This way, the physreg live ranges don't end up
344 // FIXME: It would be better to have something like shrinkToUses() for
345 // physregs. That could potentially enable more DCE and it would free up
346 // the physreg. It would not happen often, though.
348 MI
->setDesc(TII
.get(TargetOpcode::KILL
));
349 // Remove all operands that aren't physregs.
350 for (unsigned i
= MI
->getNumOperands(); i
; --i
) {
351 const MachineOperand
&MO
= MI
->getOperand(i
-1);
352 if (MO
.isReg() && Register::isPhysicalRegister(MO
.getReg()))
354 MI
->RemoveOperand(i
-1);
356 LLVM_DEBUG(dbgs() << "Converted physregs to:\t" << *MI
);
358 // If the dest of MI is an original reg and MI is reMaterializable,
359 // don't delete the inst. Replace the dest with a new reg, and keep
360 // the inst for remat of other siblings. The inst is saved in
361 // LiveRangeEdit::DeadRemats and will be deleted after all the
362 // allocations of the func are done.
363 if (isOrigDef
&& DeadRemats
&& TII
.isTriviallyReMaterializable(*MI
, AA
)) {
364 LiveInterval
&NewLI
= createEmptyIntervalFrom(Dest
, false);
365 VNInfo
*VNI
= NewLI
.getNextValue(Idx
, LIS
.getVNInfoAllocator());
366 NewLI
.addSegment(LiveInterval::Segment(Idx
, Idx
.getDeadSlot(), VNI
));
368 DeadRemats
->insert(MI
);
369 const TargetRegisterInfo
&TRI
= *MRI
.getTargetRegisterInfo();
370 MI
->substituteRegister(Dest
, NewLI
.reg
, 0, TRI
);
371 MI
->getOperand(0).setIsDead(true);
374 TheDelegate
->LRE_WillEraseInstruction(MI
);
375 LIS
.RemoveMachineInstrFromMaps(*MI
);
376 MI
->eraseFromParent();
381 // Erase any virtregs that are now empty and unused. There may be <undef>
382 // uses around. Keep the empty live range in that case.
383 for (unsigned i
= 0, e
= RegsToErase
.size(); i
!= e
; ++i
) {
384 unsigned Reg
= RegsToErase
[i
];
385 if (LIS
.hasInterval(Reg
) && MRI
.reg_nodbg_empty(Reg
)) {
386 ToShrink
.remove(&LIS
.getInterval(Reg
));
392 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl
<MachineInstr
*> &Dead
,
393 ArrayRef
<unsigned> RegsBeingSpilled
,
395 ToShrinkSet ToShrink
;
398 // Erase all dead defs.
399 while (!Dead
.empty())
400 eliminateDeadDef(Dead
.pop_back_val(), ToShrink
, AA
);
402 if (ToShrink
.empty())
405 // Shrink just one live interval. Then delete new dead defs.
406 LiveInterval
*LI
= ToShrink
.back();
408 if (foldAsLoad(LI
, Dead
))
410 unsigned VReg
= LI
->reg
;
412 TheDelegate
->LRE_WillShrinkVirtReg(VReg
);
413 if (!LIS
.shrinkToUses(LI
, &Dead
))
416 // Don't create new intervals for a register being spilled.
417 // The new intervals would have to be spilled anyway so its not worth it.
418 // Also they currently aren't spilled so creating them and not spilling
419 // them results in incorrect code.
420 bool BeingSpilled
= false;
421 for (unsigned i
= 0, e
= RegsBeingSpilled
.size(); i
!= e
; ++i
) {
422 if (VReg
== RegsBeingSpilled
[i
]) {
428 if (BeingSpilled
) continue;
430 // LI may have been separated, create new intervals.
431 LI
->RenumberValues();
432 SmallVector
<LiveInterval
*, 8> SplitLIs
;
433 LIS
.splitSeparateComponents(*LI
, SplitLIs
);
434 if (!SplitLIs
.empty())
437 unsigned Original
= VRM
? VRM
->getOriginal(VReg
) : 0;
438 for (const LiveInterval
*SplitLI
: SplitLIs
) {
439 // If LI is an original interval that hasn't been split yet, make the new
440 // intervals their own originals instead of referring to LI. The original
441 // interval must contain all the split products, and LI doesn't.
442 if (Original
!= VReg
&& Original
!= 0)
443 VRM
->setIsSplitFromReg(SplitLI
->reg
, Original
);
445 TheDelegate
->LRE_DidCloneVirtReg(SplitLI
->reg
, VReg
);
450 // Keep track of new virtual registers created via
451 // MachineRegisterInfo::createVirtualRegister.
453 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg
)
458 NewRegs
.push_back(VReg
);
462 LiveRangeEdit::calculateRegClassAndHint(MachineFunction
&MF
,
463 const MachineLoopInfo
&Loops
,
464 const MachineBlockFrequencyInfo
&MBFI
) {
465 VirtRegAuxInfo
VRAI(MF
, LIS
, VRM
, Loops
, MBFI
);
466 for (unsigned I
= 0, Size
= size(); I
< Size
; ++I
) {
467 LiveInterval
&LI
= LIS
.getInterval(get(I
));
468 if (MRI
.recomputeRegClass(LI
.reg
))
470 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
471 dbgs() << "Inflated " << printReg(LI
.reg
) << " to "
472 << TRI
->getRegClassName(MRI
.getRegClass(LI
.reg
)) << '\n';
474 VRAI
.calculateSpillWeightAndHint(LI
);