Repository navigation
Conversation
|
@llvm/pr-subscribers-backend-arm @llvm/pr-subscribers-backend-hexagon Author: xgxanq ChangesKeep the lane-aware stack store interface and AMDGPU partial SGPR emission. coalesceStackAccess, eliminateRedundantSpills, addToMergeableSpills and hoistAllSpills all assume whole-slot writes and reads, which keep the slot's value consistent; a partial store breaks that consistency for the whole slot. Guard them with a slot-level PartialSpillSlots record so a slot that has seen a partial spill is left alone. The flag is sticky and conservative: it never enables a transform that a partial store would invalidate, at the cost of giving up some still-safe transforms. These four transforms are slot-level by nature, so they keep the slot record. Only isSnippet is a genuine per-instruction classification, and it already uses the isStoreToStackSlot size interface to tell a whole-value store from a partial one. Still TODO: verify reload-side lane preservation for targets without partial stores. Patch is 263.49 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/243100.diff 65 Files Affected:
diff --git a/llvm/include/llvm/CodeGen/TargetInstrInfo.h b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
index 97baf780275ee3..910175d299c894 100644
--- a/llvm/include/llvm/CodeGen/TargetInstrInfo.h
+++ b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
@@ -1225,14 +1225,33 @@ class LLVM_ABI TargetInstrInfo : public MCInstrInfo {
/// can be passed elsewhere. The \p Flags is used to set appropriate machine
/// flags on the spill instruction e.g. FrameSetup flag on a callee saved
/// register spill instruction, part of prologue, during the frame lowering.
- virtual void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const {
+ ///
+ /// \p Lanes limits the spill to those lanes of \p SrcReg (RC lane numbering,
+ /// not a byte offset); the default LaneBitmask::getAll() spills the whole
+ /// register. A target opting in via canStoreRegToStackSlotWithLanes may get a
+ /// narrower mask and must store exactly those lanes, preserving the rest of
+ /// the slot. It must not widen the store, nor report the partial store as
+ /// complete via isStoreToStackSlot.
+ virtual void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const {
llvm_unreachable("Target didn't implement "
"TargetInstrInfo::storeRegToStackSlot!");
}
+ /// Whether the target can spill exactly Lanes of RC while preserving the
+ /// other lanes of the original stack slot. Lanes uses RC's lane numbering;
+ /// it is not a byte offset. In particular, a target must not round this mask
+ /// up to a wider store. A target which opts in receives the narrower mask
+ /// through storeRegToStackSlot's \p Lanes parameter.
+ virtual bool canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ return false;
+ }
+
/// Load the specified register of the given register class from the specified
/// stack frame index. The load instruction is to be added to the given
/// machine basic block before the specified machine instruction. If \p
diff --git a/llvm/lib/CodeGen/InlineSpiller.cpp b/llvm/lib/CodeGen/InlineSpiller.cpp
index 063940a6bfe4af..2370ea59c9504c 100644
--- a/llvm/lib/CodeGen/InlineSpiller.cpp
+++ b/llvm/lib/CodeGen/InlineSpiller.cpp
@@ -16,6 +16,7 @@
#include "SplitKit.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
@@ -104,6 +105,14 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
MergeableSpillsMap MergeableSpills;
+ // Stack slots that have received a partial spill in this run. The whole-slot
+ // optimizations guarded by hasPartialSpills() assume an access covers the
+ // whole value; a partial store writes only some bytes and breaks that. The
+ // flag is sticky (we add, never remove): once a slot has seen a partial spill
+ // we skip those optimizations on it for the rest of the run. This is
+ // conservative but never miscompiles.
+ DenseSet<int> PartialSpillSlots;
+
/// This is the map from original register to a set containing all its
/// siblings. To hoist a spill to another BB, we need to find out a live
/// sibling there and use it as the source of the new spill.
@@ -141,6 +150,12 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
Register Original);
bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
void hoistAllSpills();
+ void markPartialSpillSlot(int StackSlot) {
+ PartialSpillSlots.insert(StackSlot);
+ }
+ bool hasPartialSpills(int StackSlot) const {
+ return PartialSpillSlots.contains(StackSlot);
+ }
void LRE_WillShrinkVirtReg(Register) override;
bool LRE_CanEraseVirtReg(Register) override;
void LRE_DidCloneVirtReg(Register, Register) override;
@@ -226,7 +241,8 @@ class InlineSpiller : public Spiller {
bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
MachineInstr *LoadMI = nullptr);
void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
- void insertSpill(Register VReg, MachineBasicBlock::iterator MI);
+ void insertSpill(Register VReg, MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes);
void spillAroundUses(Register Reg);
void spillAll();
@@ -234,6 +250,19 @@ class InlineSpiller : public Spiller {
} // end anonymous namespace
+// Existing subranges alone do not describe the whole register: a split child
+// can have no subrange at all for lanes which remain live in its shared slot.
+static LaneBitmask getLiveSpillLanes(const LiveInterval &LI, SlotIndex Idx,
+ const MachineRegisterInfo &MRI) {
+ if (!LI.hasSubRanges())
+ return MRI.getMaxLaneMaskForVReg(LI.reg());
+ LaneBitmask Lanes;
+ for (const LiveInterval::SubRange &SR : LI.subranges())
+ if (SR.liveAt(Idx))
+ Lanes |= SR.LaneMask;
+ return Lanes;
+}
+
Spiller::~Spiller() = default;
void Spiller::anchor() {}
@@ -369,8 +398,18 @@ bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
continue;
- // Allow stack slot stores.
- if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
+ // Allow stack slot stores, but only when the store covers the whole value.
+ // A store with a known size smaller than the spill size is a partial store,
+ // so count it as a real use instead. This matches the behavior from before
+ // partial spills were recognized here. An unknown (zero) or scalable size
+ // counts as whole-value, so targets that do not implement the size overload
+ // keep their previous behavior.
+ TypeSize StoreBytes = TypeSize::getZero();
+ if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI, StoreBytes) &&
+ FI == StackSlot &&
+ (StoreBytes.isScalable() || StoreBytes.getKnownMinValue() == 0 ||
+ StoreBytes.getKnownMinValue() ==
+ TRI.getSpillSize(*MRI.getRegClass(SnipLI.reg()))))
continue;
if (StatepointOpers::isFoldableReg(&MI, SnipLI.reg()))
@@ -492,6 +531,23 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
<< *StackInt << '\n');
+ // Query the source at the actual insertion point, not at the later copy.
+ // A lane that dies before the copy can still be available here.
+ // Dead definitions are not live after the defining instruction.
+ SlotIndex InsertIdx =
+ SrcVNI->isPHIDef()
+ ? (MII == MBB->end() ? LIS.getMBBEndIdx(MBB).getPrevSlot()
+ : LIS.getInstructionIndex(*MII))
+ : SrcVNI->def.getDeadSlot();
+ LaneBitmask Lanes = getLiveSpillLanes(SrcLI, InsertIdx, MRI);
+ if (Lanes.none())
+ return false;
+ const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(SrcReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+ if (IsPartial)
+ return false;
+
// We are going to spill SrcVNI immediately after its def, so clear out
// any later spills of the same value.
eliminateRedundantSpills(SrcLI, SrcVNI);
@@ -527,6 +583,9 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
/// redundant spills of this value in SLI.reg and sibling copies.
void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
assert(VNI && "Missing value");
+ // Do not erase spills on a slot that has partial spills. See PartialSpillSlots.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return;
SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
WorkList.push_back(std::make_pair(&SLI, VNI));
assert(StackInt && "No stack slot assigned yet.");
@@ -538,6 +597,11 @@ void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
<< VNI->def << " in " << *LI << '\n');
+ // Knowing a partial sibling is in memory does not establish that the
+ // complete original value is there.
+ if (getLiveSpillLanes(*LI, VNI->def, MRI) != MRI.getMaxLaneMaskForVReg(Reg))
+ continue;
+
// Regs to spill are taken care of.
if (isRegToSpill(Reg))
continue;
@@ -942,6 +1006,16 @@ bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
if (InstrReg != Reg || FI != StackSlot)
return false;
+ // This coalescing drops a stack access because it assumes the access covers
+ // the whole slot and the surrounding spill code already owns the complete
+ // value. A slot with partial spills breaks that assumption. A partial store
+ // writes only some of the bytes, so dropping it would lose the rest. The load
+ // side normally does not reach this point, because a reload defines a fresh
+ // vreg rather than Reg and the InstrReg != Reg check above returns first; the
+ // whole-slot bail stays here to keep the guard conservative.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return false;
+
if (!IsLoad)
HSpiller.rmFromMergeableSpills(*MI, StackSlot);
@@ -1274,7 +1348,8 @@ static bool isRealSpill(const MachineInstr &Def, Register Reg) {
/// insertSpill - Insert a spill of NewVReg after MI.
void InlineSpiller::insertSpill(Register NewVReg,
- MachineBasicBlock::iterator MI) {
+ MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes) {
// Spill are not terminators, so inserting spills after terminators will
// violate invariants in MachineVerifier.
assert(!MI->isTerminator() && "Inserting a spill after a terminator");
@@ -1283,11 +1358,20 @@ void InlineSpiller::insertSpill(Register NewVReg,
MachineInstrSpan MIS(MI, &MBB);
MachineBasicBlock::iterator SpillBefore = std::next(MI);
bool IsRealSpill = isRealSpill(*MI, NewVReg);
-
- if (IsRealSpill)
- TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot,
- MRI.getRegClass(NewVReg), Register());
- else
+ const TargetRegisterClass *RC = MRI.getRegClass(NewVReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(NewVReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+
+ if (IsRealSpill && (!IsPartial || Lanes.any())) {
+ // Partial and full stores share one hook: a partial-liveness mask spills
+ // only the live lanes and preserves the rest of the shared slot, while a
+ // full mask is the ordinary full-width spill.
+ if (IsPartial)
+ HSpiller.markPartialSpillSlot(StackSlot);
+ TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot, RC,
+ Register(), MachineInstr::NoFlags,
+ IsPartial ? Lanes : LaneBitmask::getAll());
+ } else
// Don't spill undef value.
// Anything works for undef, in particular keeping the memory
// uninitialized is a viable option and it saves code size and
@@ -1306,7 +1390,7 @@ void InlineSpiller::insertSpill(Register NewVReg,
// If there is only 1 store instruction is required for spill, add it
// to mergeable list. In X86 AMX, 2 instructions are required to store.
// We disable the merge for this case.
- if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
+ if (IsRealSpill && !IsPartial && std::distance(Spill, MIS.end()) <= 1)
HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
}
@@ -1349,6 +1433,11 @@ void InlineSpiller::spillAroundUses(Register Reg) {
if (SlotIndex::isSameInstr(Idx, VNI->def))
Idx = VNI->def;
+ // Read the old interval before changing operands or constructing the
+ // short spill temporary. It may have only a subset of the original lanes.
+ // insertSpill below uses this to decide between a partial and a full store.
+ LaneBitmask Lanes = getLiveSpillLanes(OldLI, Idx, MRI);
+
// Check for a sibling copy.
Register SibReg = isCopyOfBundle(MI, Reg, TII);
if (SibReg && isSibling(SibReg)) {
@@ -1397,7 +1486,7 @@ void InlineSpiller::spillAroundUses(Register Reg) {
// FIXME: Use a second vreg if instruction has no tied ops.
if (RI.Writes)
if (hasLiveDef)
- insertSpill(NewVReg, &MI);
+ insertSpill(NewVReg, &MI, Lanes);
}
}
@@ -1485,6 +1574,10 @@ void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
/// When a spill is inserted, add the spill to MergeableSpills map.
void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
Register Original) {
+ // Do not make a slot with partial spills a hoist candidate. See
+ // PartialSpillSlots.
+ if (hasPartialSpills(StackSlot))
+ return;
BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
LiveInterval &OrigLI = LIS.getInterval(Original);
// save a copy of LiveInterval in StackSlotToOrigLI because the original
@@ -1540,9 +1633,7 @@ bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
// All of the sub-ranges should be alive at the prospective slot index.
// Otherwise, we might risk storing unrelated / compromised values from some
// sub-registers to the spill slot.
- if (all_of(LI.subranges(), [&](const LiveInterval::SubRange &SR) {
- return SR.getVNInfoAt(Idx) != nullptr;
- })) {
+ if (getLiveSpillLanes(LI, Idx, MRI) == MRI.getMaxLaneMaskForVReg(SibReg)) {
LiveReg = SibReg;
return true;
}
@@ -1817,6 +1908,9 @@ void HoistSpillHelper::hoistAllSpills() {
// Each entry in MergeableSpills contains a spill set with equal values.
for (auto &Ent : MergeableSpills) {
int Slot = Ent.first.first;
+ // Skip hoisting on a slot that has partial spills. See PartialSpillSlots.
+ if (hasPartialSpills(Slot))
+ continue;
LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
VNInfo *OrigVNI = Ent.first.second;
SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
index 40f5d0ef2383eb..bc2b800c802485 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
@@ -6453,12 +6453,10 @@ static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
.addMemOperand(MMO);
}
-void AArch64InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
- MachineBasicBlock::iterator MBBI,
- Register SrcReg, bool isKill, int FI,
- const TargetRegisterClass *RC,
- Register VReg,
- MachineInstr::MIFlag Flags) const {
+void AArch64InstrInfo::storeRegToStackSlot(
+ MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
+ bool isKill, int FI, const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = MF.getFrameInfo();
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.h b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
index 8f34c3b6f48532..195ab38360590f 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
@@ -376,10 +376,12 @@ class AArch64InstrInfo final : public AArch64GenInstrInfo {
bool KillSrc, bool RenamableDest = false,
bool RenamableSrc = false) const override;
- void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const override;
+ void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const override;
void loadRegFromStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index 63ae0f06f4c9b7..8836fcb02f1393 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -1803,11 +1803,61 @@ void SIInstrInfo::storeRegToStackSlotImpl(
void SIInstrInfo::storeRegToStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags) const {
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
+ // A narrower-than-full mask requests a partial spill that preserves the
+ // other words of the shared slot. Otherwise emit the ordinary full-width
+ // store, including when this class does not support partial spills.
+ if (Lanes != LaneBitmask::getAll() &&
+ canStoreRegToStackSlotWithLanes(RC, Lanes)) {
+ MachineFunction &MF = *MBB.getParent();
+ SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
+ MachineFrameInfo &FrameInfo = MF.getFrameInfo();
+ if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
+ MFI.setHasSpilledSGPRs();
+ const DebugLoc &DL = MBB.findDebugLoc(MI);
+
+ auto Parts = RI.getRegSplitParts(RC, 4);
+ for (unsigned Word = 0; Word != Parts.size(); ++Word) {
+ unsigned SubReg = Parts[Word];
+ LaneBitmask WordLanes = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & WordLanes).none())
+ continue;
+ Lanes &= ~WordLanes;
+ MachinePointerInfo PtrInfo =
+ MachinePointerInfo::getFixedStack(MF, FrameIndex, Word * 4);
+ auto *StoreMMO = MF.getMachineMemOperand(
+ PtrInfo, MachineMemOperand::MOStore, 4,
+ commonAlignment(FrameInfo.getObjectAlign(FrameIndex), Word * 4));
+ BuildMI(MBB, MI, DL, get(AMDGPU::SI_SPILL_S32_SAVE_PARTIAL))
+ .addReg(SrcReg, getKillRegState(isKill && Lanes.none()), SubReg)
+ .addFrameIndex(FrameIndex)
+ .addImm(Word)
+ .addMemOperand(StoreMMO)
+ .addReg(MFI.getStackPtrOffsetReg(), RegState::Implicit);
+ }
+ return;
+ }
+
storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, VReg, Flags,
false);
}
+bool SIInstrInfo::canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ if (!RI.isSGPRClass(RC) || RI.getSpillSize(*RC) <= 4)
+ return false;
+
+ // SGPR tuples split into 32-bit words. Never turn a partial-word mask into
+ // a full-word store: such masks need a different preservation mechanism.
+ for (int16_t SubReg : RI.getRegSplitParts(RC, 4)) {
+ LaneBitmask Word = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & Word).any() && (Lanes & Word) != Word)
+ return false;
+ Lanes &= ~Word;
+ }
+ return Lanes.none();
+}
+
void SIInstrInfo::storeRegToStackSlotCFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
Register SrcReg, bool isKill,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.h b/llvm/lib/Target/AMDGPU/SIInstrInfo.h
index 17a511ad13bad8..c596db328c01ee 100644
--- a/llvm/lib/Target/AMDGPU/...
[truncated]
|
|
@llvm/pr-subscribers-backend-sparc Author: xgxanq ChangesKeep the lane-aware stack store interface and AMDGPU partial SGPR emission. coalesceStackAccess, eliminateRedundantSpills, addToMergeableSpills and hoistAllSpills all assume whole-slot writes and reads, which keep the slot's value consistent; a partial store breaks that consistency for the whole slot. Guard them with a slot-level PartialSpillSlots record so a slot that has seen a partial spill is left alone. The flag is sticky and conservative: it never enables a transform that a partial store would invalidate, at the cost of giving up some still-safe transforms. These four transforms are slot-level by nature, so they keep the slot record. Only isSnippet is a genuine per-instruction classification, and it already uses the isStoreToStackSlot size interface to tell a whole-value store from a partial one. Still TODO: verify reload-side lane preservation for targets without partial stores. Patch is 263.49 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/243100.diff 65 Files Affected:
diff --git a/llvm/include/llvm/CodeGen/TargetInstrInfo.h b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
index 97baf780275ee3..910175d299c894 100644
--- a/llvm/include/llvm/CodeGen/TargetInstrInfo.h
+++ b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
@@ -1225,14 +1225,33 @@ class LLVM_ABI TargetInstrInfo : public MCInstrInfo {
/// can be passed elsewhere. The \p Flags is used to set appropriate machine
/// flags on the spill instruction e.g. FrameSetup flag on a callee saved
/// register spill instruction, part of prologue, during the frame lowering.
- virtual void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const {
+ ///
+ /// \p Lanes limits the spill to those lanes of \p SrcReg (RC lane numbering,
+ /// not a byte offset); the default LaneBitmask::getAll() spills the whole
+ /// register. A target opting in via canStoreRegToStackSlotWithLanes may get a
+ /// narrower mask and must store exactly those lanes, preserving the rest of
+ /// the slot. It must not widen the store, nor report the partial store as
+ /// complete via isStoreToStackSlot.
+ virtual void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const {
llvm_unreachable("Target didn't implement "
"TargetInstrInfo::storeRegToStackSlot!");
}
+ /// Whether the target can spill exactly Lanes of RC while preserving the
+ /// other lanes of the original stack slot. Lanes uses RC's lane numbering;
+ /// it is not a byte offset. In particular, a target must not round this mask
+ /// up to a wider store. A target which opts in receives the narrower mask
+ /// through storeRegToStackSlot's \p Lanes parameter.
+ virtual bool canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ return false;
+ }
+
/// Load the specified register of the given register class from the specified
/// stack frame index. The load instruction is to be added to the given
/// machine basic block before the specified machine instruction. If \p
diff --git a/llvm/lib/CodeGen/InlineSpiller.cpp b/llvm/lib/CodeGen/InlineSpiller.cpp
index 063940a6bfe4af..2370ea59c9504c 100644
--- a/llvm/lib/CodeGen/InlineSpiller.cpp
+++ b/llvm/lib/CodeGen/InlineSpiller.cpp
@@ -16,6 +16,7 @@
#include "SplitKit.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
@@ -104,6 +105,14 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
MergeableSpillsMap MergeableSpills;
+ // Stack slots that have received a partial spill in this run. The whole-slot
+ // optimizations guarded by hasPartialSpills() assume an access covers the
+ // whole value; a partial store writes only some bytes and breaks that. The
+ // flag is sticky (we add, never remove): once a slot has seen a partial spill
+ // we skip those optimizations on it for the rest of the run. This is
+ // conservative but never miscompiles.
+ DenseSet<int> PartialSpillSlots;
+
/// This is the map from original register to a set containing all its
/// siblings. To hoist a spill to another BB, we need to find out a live
/// sibling there and use it as the source of the new spill.
@@ -141,6 +150,12 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
Register Original);
bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
void hoistAllSpills();
+ void markPartialSpillSlot(int StackSlot) {
+ PartialSpillSlots.insert(StackSlot);
+ }
+ bool hasPartialSpills(int StackSlot) const {
+ return PartialSpillSlots.contains(StackSlot);
+ }
void LRE_WillShrinkVirtReg(Register) override;
bool LRE_CanEraseVirtReg(Register) override;
void LRE_DidCloneVirtReg(Register, Register) override;
@@ -226,7 +241,8 @@ class InlineSpiller : public Spiller {
bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
MachineInstr *LoadMI = nullptr);
void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
- void insertSpill(Register VReg, MachineBasicBlock::iterator MI);
+ void insertSpill(Register VReg, MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes);
void spillAroundUses(Register Reg);
void spillAll();
@@ -234,6 +250,19 @@ class InlineSpiller : public Spiller {
} // end anonymous namespace
+// Existing subranges alone do not describe the whole register: a split child
+// can have no subrange at all for lanes which remain live in its shared slot.
+static LaneBitmask getLiveSpillLanes(const LiveInterval &LI, SlotIndex Idx,
+ const MachineRegisterInfo &MRI) {
+ if (!LI.hasSubRanges())
+ return MRI.getMaxLaneMaskForVReg(LI.reg());
+ LaneBitmask Lanes;
+ for (const LiveInterval::SubRange &SR : LI.subranges())
+ if (SR.liveAt(Idx))
+ Lanes |= SR.LaneMask;
+ return Lanes;
+}
+
Spiller::~Spiller() = default;
void Spiller::anchor() {}
@@ -369,8 +398,18 @@ bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
continue;
- // Allow stack slot stores.
- if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
+ // Allow stack slot stores, but only when the store covers the whole value.
+ // A store with a known size smaller than the spill size is a partial store,
+ // so count it as a real use instead. This matches the behavior from before
+ // partial spills were recognized here. An unknown (zero) or scalable size
+ // counts as whole-value, so targets that do not implement the size overload
+ // keep their previous behavior.
+ TypeSize StoreBytes = TypeSize::getZero();
+ if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI, StoreBytes) &&
+ FI == StackSlot &&
+ (StoreBytes.isScalable() || StoreBytes.getKnownMinValue() == 0 ||
+ StoreBytes.getKnownMinValue() ==
+ TRI.getSpillSize(*MRI.getRegClass(SnipLI.reg()))))
continue;
if (StatepointOpers::isFoldableReg(&MI, SnipLI.reg()))
@@ -492,6 +531,23 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
<< *StackInt << '\n');
+ // Query the source at the actual insertion point, not at the later copy.
+ // A lane that dies before the copy can still be available here.
+ // Dead definitions are not live after the defining instruction.
+ SlotIndex InsertIdx =
+ SrcVNI->isPHIDef()
+ ? (MII == MBB->end() ? LIS.getMBBEndIdx(MBB).getPrevSlot()
+ : LIS.getInstructionIndex(*MII))
+ : SrcVNI->def.getDeadSlot();
+ LaneBitmask Lanes = getLiveSpillLanes(SrcLI, InsertIdx, MRI);
+ if (Lanes.none())
+ return false;
+ const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(SrcReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+ if (IsPartial)
+ return false;
+
// We are going to spill SrcVNI immediately after its def, so clear out
// any later spills of the same value.
eliminateRedundantSpills(SrcLI, SrcVNI);
@@ -527,6 +583,9 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
/// redundant spills of this value in SLI.reg and sibling copies.
void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
assert(VNI && "Missing value");
+ // Do not erase spills on a slot that has partial spills. See PartialSpillSlots.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return;
SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
WorkList.push_back(std::make_pair(&SLI, VNI));
assert(StackInt && "No stack slot assigned yet.");
@@ -538,6 +597,11 @@ void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
<< VNI->def << " in " << *LI << '\n');
+ // Knowing a partial sibling is in memory does not establish that the
+ // complete original value is there.
+ if (getLiveSpillLanes(*LI, VNI->def, MRI) != MRI.getMaxLaneMaskForVReg(Reg))
+ continue;
+
// Regs to spill are taken care of.
if (isRegToSpill(Reg))
continue;
@@ -942,6 +1006,16 @@ bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
if (InstrReg != Reg || FI != StackSlot)
return false;
+ // This coalescing drops a stack access because it assumes the access covers
+ // the whole slot and the surrounding spill code already owns the complete
+ // value. A slot with partial spills breaks that assumption. A partial store
+ // writes only some of the bytes, so dropping it would lose the rest. The load
+ // side normally does not reach this point, because a reload defines a fresh
+ // vreg rather than Reg and the InstrReg != Reg check above returns first; the
+ // whole-slot bail stays here to keep the guard conservative.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return false;
+
if (!IsLoad)
HSpiller.rmFromMergeableSpills(*MI, StackSlot);
@@ -1274,7 +1348,8 @@ static bool isRealSpill(const MachineInstr &Def, Register Reg) {
/// insertSpill - Insert a spill of NewVReg after MI.
void InlineSpiller::insertSpill(Register NewVReg,
- MachineBasicBlock::iterator MI) {
+ MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes) {
// Spill are not terminators, so inserting spills after terminators will
// violate invariants in MachineVerifier.
assert(!MI->isTerminator() && "Inserting a spill after a terminator");
@@ -1283,11 +1358,20 @@ void InlineSpiller::insertSpill(Register NewVReg,
MachineInstrSpan MIS(MI, &MBB);
MachineBasicBlock::iterator SpillBefore = std::next(MI);
bool IsRealSpill = isRealSpill(*MI, NewVReg);
-
- if (IsRealSpill)
- TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot,
- MRI.getRegClass(NewVReg), Register());
- else
+ const TargetRegisterClass *RC = MRI.getRegClass(NewVReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(NewVReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+
+ if (IsRealSpill && (!IsPartial || Lanes.any())) {
+ // Partial and full stores share one hook: a partial-liveness mask spills
+ // only the live lanes and preserves the rest of the shared slot, while a
+ // full mask is the ordinary full-width spill.
+ if (IsPartial)
+ HSpiller.markPartialSpillSlot(StackSlot);
+ TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot, RC,
+ Register(), MachineInstr::NoFlags,
+ IsPartial ? Lanes : LaneBitmask::getAll());
+ } else
// Don't spill undef value.
// Anything works for undef, in particular keeping the memory
// uninitialized is a viable option and it saves code size and
@@ -1306,7 +1390,7 @@ void InlineSpiller::insertSpill(Register NewVReg,
// If there is only 1 store instruction is required for spill, add it
// to mergeable list. In X86 AMX, 2 instructions are required to store.
// We disable the merge for this case.
- if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
+ if (IsRealSpill && !IsPartial && std::distance(Spill, MIS.end()) <= 1)
HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
}
@@ -1349,6 +1433,11 @@ void InlineSpiller::spillAroundUses(Register Reg) {
if (SlotIndex::isSameInstr(Idx, VNI->def))
Idx = VNI->def;
+ // Read the old interval before changing operands or constructing the
+ // short spill temporary. It may have only a subset of the original lanes.
+ // insertSpill below uses this to decide between a partial and a full store.
+ LaneBitmask Lanes = getLiveSpillLanes(OldLI, Idx, MRI);
+
// Check for a sibling copy.
Register SibReg = isCopyOfBundle(MI, Reg, TII);
if (SibReg && isSibling(SibReg)) {
@@ -1397,7 +1486,7 @@ void InlineSpiller::spillAroundUses(Register Reg) {
// FIXME: Use a second vreg if instruction has no tied ops.
if (RI.Writes)
if (hasLiveDef)
- insertSpill(NewVReg, &MI);
+ insertSpill(NewVReg, &MI, Lanes);
}
}
@@ -1485,6 +1574,10 @@ void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
/// When a spill is inserted, add the spill to MergeableSpills map.
void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
Register Original) {
+ // Do not make a slot with partial spills a hoist candidate. See
+ // PartialSpillSlots.
+ if (hasPartialSpills(StackSlot))
+ return;
BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
LiveInterval &OrigLI = LIS.getInterval(Original);
// save a copy of LiveInterval in StackSlotToOrigLI because the original
@@ -1540,9 +1633,7 @@ bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
// All of the sub-ranges should be alive at the prospective slot index.
// Otherwise, we might risk storing unrelated / compromised values from some
// sub-registers to the spill slot.
- if (all_of(LI.subranges(), [&](const LiveInterval::SubRange &SR) {
- return SR.getVNInfoAt(Idx) != nullptr;
- })) {
+ if (getLiveSpillLanes(LI, Idx, MRI) == MRI.getMaxLaneMaskForVReg(SibReg)) {
LiveReg = SibReg;
return true;
}
@@ -1817,6 +1908,9 @@ void HoistSpillHelper::hoistAllSpills() {
// Each entry in MergeableSpills contains a spill set with equal values.
for (auto &Ent : MergeableSpills) {
int Slot = Ent.first.first;
+ // Skip hoisting on a slot that has partial spills. See PartialSpillSlots.
+ if (hasPartialSpills(Slot))
+ continue;
LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
VNInfo *OrigVNI = Ent.first.second;
SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
index 40f5d0ef2383eb..bc2b800c802485 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
@@ -6453,12 +6453,10 @@ static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
.addMemOperand(MMO);
}
-void AArch64InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
- MachineBasicBlock::iterator MBBI,
- Register SrcReg, bool isKill, int FI,
- const TargetRegisterClass *RC,
- Register VReg,
- MachineInstr::MIFlag Flags) const {
+void AArch64InstrInfo::storeRegToStackSlot(
+ MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
+ bool isKill, int FI, const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = MF.getFrameInfo();
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.h b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
index 8f34c3b6f48532..195ab38360590f 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
@@ -376,10 +376,12 @@ class AArch64InstrInfo final : public AArch64GenInstrInfo {
bool KillSrc, bool RenamableDest = false,
bool RenamableSrc = false) const override;
- void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const override;
+ void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const override;
void loadRegFromStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index 63ae0f06f4c9b7..8836fcb02f1393 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -1803,11 +1803,61 @@ void SIInstrInfo::storeRegToStackSlotImpl(
void SIInstrInfo::storeRegToStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags) const {
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
+ // A narrower-than-full mask requests a partial spill that preserves the
+ // other words of the shared slot. Otherwise emit the ordinary full-width
+ // store, including when this class does not support partial spills.
+ if (Lanes != LaneBitmask::getAll() &&
+ canStoreRegToStackSlotWithLanes(RC, Lanes)) {
+ MachineFunction &MF = *MBB.getParent();
+ SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
+ MachineFrameInfo &FrameInfo = MF.getFrameInfo();
+ if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
+ MFI.setHasSpilledSGPRs();
+ const DebugLoc &DL = MBB.findDebugLoc(MI);
+
+ auto Parts = RI.getRegSplitParts(RC, 4);
+ for (unsigned Word = 0; Word != Parts.size(); ++Word) {
+ unsigned SubReg = Parts[Word];
+ LaneBitmask WordLanes = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & WordLanes).none())
+ continue;
+ Lanes &= ~WordLanes;
+ MachinePointerInfo PtrInfo =
+ MachinePointerInfo::getFixedStack(MF, FrameIndex, Word * 4);
+ auto *StoreMMO = MF.getMachineMemOperand(
+ PtrInfo, MachineMemOperand::MOStore, 4,
+ commonAlignment(FrameInfo.getObjectAlign(FrameIndex), Word * 4));
+ BuildMI(MBB, MI, DL, get(AMDGPU::SI_SPILL_S32_SAVE_PARTIAL))
+ .addReg(SrcReg, getKillRegState(isKill && Lanes.none()), SubReg)
+ .addFrameIndex(FrameIndex)
+ .addImm(Word)
+ .addMemOperand(StoreMMO)
+ .addReg(MFI.getStackPtrOffsetReg(), RegState::Implicit);
+ }
+ return;
+ }
+
storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, VReg, Flags,
false);
}
+bool SIInstrInfo::canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ if (!RI.isSGPRClass(RC) || RI.getSpillSize(*RC) <= 4)
+ return false;
+
+ // SGPR tuples split into 32-bit words. Never turn a partial-word mask into
+ // a full-word store: such masks need a different preservation mechanism.
+ for (int16_t SubReg : RI.getRegSplitParts(RC, 4)) {
+ LaneBitmask Word = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & Word).any() && (Lanes & Word) != Word)
+ return false;
+ Lanes &= ~Word;
+ }
+ return Lanes.none();
+}
+
void SIInstrInfo::storeRegToStackSlotCFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
Register SrcReg, bool isKill,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.h b/llvm/lib/Target/AMDGPU/SIInstrInfo.h
index 17a511ad13bad8..c596db328c01ee 100644
--- a/llvm/lib/Target/AMDGPU/...
[truncated]
|
|
@llvm/pr-subscribers-backend-risc-v Author: xgxanq ChangesKeep the lane-aware stack store interface and AMDGPU partial SGPR emission. coalesceStackAccess, eliminateRedundantSpills, addToMergeableSpills and hoistAllSpills all assume whole-slot writes and reads, which keep the slot's value consistent; a partial store breaks that consistency for the whole slot. Guard them with a slot-level PartialSpillSlots record so a slot that has seen a partial spill is left alone. The flag is sticky and conservative: it never enables a transform that a partial store would invalidate, at the cost of giving up some still-safe transforms. These four transforms are slot-level by nature, so they keep the slot record. Only isSnippet is a genuine per-instruction classification, and it already uses the isStoreToStackSlot size interface to tell a whole-value store from a partial one. Still TODO: verify reload-side lane preservation for targets without partial stores. Patch is 263.49 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/243100.diff 65 Files Affected:
diff --git a/llvm/include/llvm/CodeGen/TargetInstrInfo.h b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
index 97baf780275ee3..910175d299c894 100644
--- a/llvm/include/llvm/CodeGen/TargetInstrInfo.h
+++ b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
@@ -1225,14 +1225,33 @@ class LLVM_ABI TargetInstrInfo : public MCInstrInfo {
/// can be passed elsewhere. The \p Flags is used to set appropriate machine
/// flags on the spill instruction e.g. FrameSetup flag on a callee saved
/// register spill instruction, part of prologue, during the frame lowering.
- virtual void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const {
+ ///
+ /// \p Lanes limits the spill to those lanes of \p SrcReg (RC lane numbering,
+ /// not a byte offset); the default LaneBitmask::getAll() spills the whole
+ /// register. A target opting in via canStoreRegToStackSlotWithLanes may get a
+ /// narrower mask and must store exactly those lanes, preserving the rest of
+ /// the slot. It must not widen the store, nor report the partial store as
+ /// complete via isStoreToStackSlot.
+ virtual void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const {
llvm_unreachable("Target didn't implement "
"TargetInstrInfo::storeRegToStackSlot!");
}
+ /// Whether the target can spill exactly Lanes of RC while preserving the
+ /// other lanes of the original stack slot. Lanes uses RC's lane numbering;
+ /// it is not a byte offset. In particular, a target must not round this mask
+ /// up to a wider store. A target which opts in receives the narrower mask
+ /// through storeRegToStackSlot's \p Lanes parameter.
+ virtual bool canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ return false;
+ }
+
/// Load the specified register of the given register class from the specified
/// stack frame index. The load instruction is to be added to the given
/// machine basic block before the specified machine instruction. If \p
diff --git a/llvm/lib/CodeGen/InlineSpiller.cpp b/llvm/lib/CodeGen/InlineSpiller.cpp
index 063940a6bfe4af..2370ea59c9504c 100644
--- a/llvm/lib/CodeGen/InlineSpiller.cpp
+++ b/llvm/lib/CodeGen/InlineSpiller.cpp
@@ -16,6 +16,7 @@
#include "SplitKit.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
@@ -104,6 +105,14 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
MergeableSpillsMap MergeableSpills;
+ // Stack slots that have received a partial spill in this run. The whole-slot
+ // optimizations guarded by hasPartialSpills() assume an access covers the
+ // whole value; a partial store writes only some bytes and breaks that. The
+ // flag is sticky (we add, never remove): once a slot has seen a partial spill
+ // we skip those optimizations on it for the rest of the run. This is
+ // conservative but never miscompiles.
+ DenseSet<int> PartialSpillSlots;
+
/// This is the map from original register to a set containing all its
/// siblings. To hoist a spill to another BB, we need to find out a live
/// sibling there and use it as the source of the new spill.
@@ -141,6 +150,12 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
Register Original);
bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
void hoistAllSpills();
+ void markPartialSpillSlot(int StackSlot) {
+ PartialSpillSlots.insert(StackSlot);
+ }
+ bool hasPartialSpills(int StackSlot) const {
+ return PartialSpillSlots.contains(StackSlot);
+ }
void LRE_WillShrinkVirtReg(Register) override;
bool LRE_CanEraseVirtReg(Register) override;
void LRE_DidCloneVirtReg(Register, Register) override;
@@ -226,7 +241,8 @@ class InlineSpiller : public Spiller {
bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
MachineInstr *LoadMI = nullptr);
void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
- void insertSpill(Register VReg, MachineBasicBlock::iterator MI);
+ void insertSpill(Register VReg, MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes);
void spillAroundUses(Register Reg);
void spillAll();
@@ -234,6 +250,19 @@ class InlineSpiller : public Spiller {
} // end anonymous namespace
+// Existing subranges alone do not describe the whole register: a split child
+// can have no subrange at all for lanes which remain live in its shared slot.
+static LaneBitmask getLiveSpillLanes(const LiveInterval &LI, SlotIndex Idx,
+ const MachineRegisterInfo &MRI) {
+ if (!LI.hasSubRanges())
+ return MRI.getMaxLaneMaskForVReg(LI.reg());
+ LaneBitmask Lanes;
+ for (const LiveInterval::SubRange &SR : LI.subranges())
+ if (SR.liveAt(Idx))
+ Lanes |= SR.LaneMask;
+ return Lanes;
+}
+
Spiller::~Spiller() = default;
void Spiller::anchor() {}
@@ -369,8 +398,18 @@ bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
continue;
- // Allow stack slot stores.
- if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
+ // Allow stack slot stores, but only when the store covers the whole value.
+ // A store with a known size smaller than the spill size is a partial store,
+ // so count it as a real use instead. This matches the behavior from before
+ // partial spills were recognized here. An unknown (zero) or scalable size
+ // counts as whole-value, so targets that do not implement the size overload
+ // keep their previous behavior.
+ TypeSize StoreBytes = TypeSize::getZero();
+ if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI, StoreBytes) &&
+ FI == StackSlot &&
+ (StoreBytes.isScalable() || StoreBytes.getKnownMinValue() == 0 ||
+ StoreBytes.getKnownMinValue() ==
+ TRI.getSpillSize(*MRI.getRegClass(SnipLI.reg()))))
continue;
if (StatepointOpers::isFoldableReg(&MI, SnipLI.reg()))
@@ -492,6 +531,23 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
<< *StackInt << '\n');
+ // Query the source at the actual insertion point, not at the later copy.
+ // A lane that dies before the copy can still be available here.
+ // Dead definitions are not live after the defining instruction.
+ SlotIndex InsertIdx =
+ SrcVNI->isPHIDef()
+ ? (MII == MBB->end() ? LIS.getMBBEndIdx(MBB).getPrevSlot()
+ : LIS.getInstructionIndex(*MII))
+ : SrcVNI->def.getDeadSlot();
+ LaneBitmask Lanes = getLiveSpillLanes(SrcLI, InsertIdx, MRI);
+ if (Lanes.none())
+ return false;
+ const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(SrcReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+ if (IsPartial)
+ return false;
+
// We are going to spill SrcVNI immediately after its def, so clear out
// any later spills of the same value.
eliminateRedundantSpills(SrcLI, SrcVNI);
@@ -527,6 +583,9 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
/// redundant spills of this value in SLI.reg and sibling copies.
void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
assert(VNI && "Missing value");
+ // Do not erase spills on a slot that has partial spills. See PartialSpillSlots.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return;
SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
WorkList.push_back(std::make_pair(&SLI, VNI));
assert(StackInt && "No stack slot assigned yet.");
@@ -538,6 +597,11 @@ void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
<< VNI->def << " in " << *LI << '\n');
+ // Knowing a partial sibling is in memory does not establish that the
+ // complete original value is there.
+ if (getLiveSpillLanes(*LI, VNI->def, MRI) != MRI.getMaxLaneMaskForVReg(Reg))
+ continue;
+
// Regs to spill are taken care of.
if (isRegToSpill(Reg))
continue;
@@ -942,6 +1006,16 @@ bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
if (InstrReg != Reg || FI != StackSlot)
return false;
+ // This coalescing drops a stack access because it assumes the access covers
+ // the whole slot and the surrounding spill code already owns the complete
+ // value. A slot with partial spills breaks that assumption. A partial store
+ // writes only some of the bytes, so dropping it would lose the rest. The load
+ // side normally does not reach this point, because a reload defines a fresh
+ // vreg rather than Reg and the InstrReg != Reg check above returns first; the
+ // whole-slot bail stays here to keep the guard conservative.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return false;
+
if (!IsLoad)
HSpiller.rmFromMergeableSpills(*MI, StackSlot);
@@ -1274,7 +1348,8 @@ static bool isRealSpill(const MachineInstr &Def, Register Reg) {
/// insertSpill - Insert a spill of NewVReg after MI.
void InlineSpiller::insertSpill(Register NewVReg,
- MachineBasicBlock::iterator MI) {
+ MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes) {
// Spill are not terminators, so inserting spills after terminators will
// violate invariants in MachineVerifier.
assert(!MI->isTerminator() && "Inserting a spill after a terminator");
@@ -1283,11 +1358,20 @@ void InlineSpiller::insertSpill(Register NewVReg,
MachineInstrSpan MIS(MI, &MBB);
MachineBasicBlock::iterator SpillBefore = std::next(MI);
bool IsRealSpill = isRealSpill(*MI, NewVReg);
-
- if (IsRealSpill)
- TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot,
- MRI.getRegClass(NewVReg), Register());
- else
+ const TargetRegisterClass *RC = MRI.getRegClass(NewVReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(NewVReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+
+ if (IsRealSpill && (!IsPartial || Lanes.any())) {
+ // Partial and full stores share one hook: a partial-liveness mask spills
+ // only the live lanes and preserves the rest of the shared slot, while a
+ // full mask is the ordinary full-width spill.
+ if (IsPartial)
+ HSpiller.markPartialSpillSlot(StackSlot);
+ TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot, RC,
+ Register(), MachineInstr::NoFlags,
+ IsPartial ? Lanes : LaneBitmask::getAll());
+ } else
// Don't spill undef value.
// Anything works for undef, in particular keeping the memory
// uninitialized is a viable option and it saves code size and
@@ -1306,7 +1390,7 @@ void InlineSpiller::insertSpill(Register NewVReg,
// If there is only 1 store instruction is required for spill, add it
// to mergeable list. In X86 AMX, 2 instructions are required to store.
// We disable the merge for this case.
- if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
+ if (IsRealSpill && !IsPartial && std::distance(Spill, MIS.end()) <= 1)
HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
}
@@ -1349,6 +1433,11 @@ void InlineSpiller::spillAroundUses(Register Reg) {
if (SlotIndex::isSameInstr(Idx, VNI->def))
Idx = VNI->def;
+ // Read the old interval before changing operands or constructing the
+ // short spill temporary. It may have only a subset of the original lanes.
+ // insertSpill below uses this to decide between a partial and a full store.
+ LaneBitmask Lanes = getLiveSpillLanes(OldLI, Idx, MRI);
+
// Check for a sibling copy.
Register SibReg = isCopyOfBundle(MI, Reg, TII);
if (SibReg && isSibling(SibReg)) {
@@ -1397,7 +1486,7 @@ void InlineSpiller::spillAroundUses(Register Reg) {
// FIXME: Use a second vreg if instruction has no tied ops.
if (RI.Writes)
if (hasLiveDef)
- insertSpill(NewVReg, &MI);
+ insertSpill(NewVReg, &MI, Lanes);
}
}
@@ -1485,6 +1574,10 @@ void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
/// When a spill is inserted, add the spill to MergeableSpills map.
void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
Register Original) {
+ // Do not make a slot with partial spills a hoist candidate. See
+ // PartialSpillSlots.
+ if (hasPartialSpills(StackSlot))
+ return;
BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
LiveInterval &OrigLI = LIS.getInterval(Original);
// save a copy of LiveInterval in StackSlotToOrigLI because the original
@@ -1540,9 +1633,7 @@ bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
// All of the sub-ranges should be alive at the prospective slot index.
// Otherwise, we might risk storing unrelated / compromised values from some
// sub-registers to the spill slot.
- if (all_of(LI.subranges(), [&](const LiveInterval::SubRange &SR) {
- return SR.getVNInfoAt(Idx) != nullptr;
- })) {
+ if (getLiveSpillLanes(LI, Idx, MRI) == MRI.getMaxLaneMaskForVReg(SibReg)) {
LiveReg = SibReg;
return true;
}
@@ -1817,6 +1908,9 @@ void HoistSpillHelper::hoistAllSpills() {
// Each entry in MergeableSpills contains a spill set with equal values.
for (auto &Ent : MergeableSpills) {
int Slot = Ent.first.first;
+ // Skip hoisting on a slot that has partial spills. See PartialSpillSlots.
+ if (hasPartialSpills(Slot))
+ continue;
LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
VNInfo *OrigVNI = Ent.first.second;
SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
index 40f5d0ef2383eb..bc2b800c802485 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
@@ -6453,12 +6453,10 @@ static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
.addMemOperand(MMO);
}
-void AArch64InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
- MachineBasicBlock::iterator MBBI,
- Register SrcReg, bool isKill, int FI,
- const TargetRegisterClass *RC,
- Register VReg,
- MachineInstr::MIFlag Flags) const {
+void AArch64InstrInfo::storeRegToStackSlot(
+ MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
+ bool isKill, int FI, const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = MF.getFrameInfo();
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.h b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
index 8f34c3b6f48532..195ab38360590f 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
@@ -376,10 +376,12 @@ class AArch64InstrInfo final : public AArch64GenInstrInfo {
bool KillSrc, bool RenamableDest = false,
bool RenamableSrc = false) const override;
- void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const override;
+ void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const override;
void loadRegFromStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index 63ae0f06f4c9b7..8836fcb02f1393 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -1803,11 +1803,61 @@ void SIInstrInfo::storeRegToStackSlotImpl(
void SIInstrInfo::storeRegToStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags) const {
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
+ // A narrower-than-full mask requests a partial spill that preserves the
+ // other words of the shared slot. Otherwise emit the ordinary full-width
+ // store, including when this class does not support partial spills.
+ if (Lanes != LaneBitmask::getAll() &&
+ canStoreRegToStackSlotWithLanes(RC, Lanes)) {
+ MachineFunction &MF = *MBB.getParent();
+ SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
+ MachineFrameInfo &FrameInfo = MF.getFrameInfo();
+ if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
+ MFI.setHasSpilledSGPRs();
+ const DebugLoc &DL = MBB.findDebugLoc(MI);
+
+ auto Parts = RI.getRegSplitParts(RC, 4);
+ for (unsigned Word = 0; Word != Parts.size(); ++Word) {
+ unsigned SubReg = Parts[Word];
+ LaneBitmask WordLanes = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & WordLanes).none())
+ continue;
+ Lanes &= ~WordLanes;
+ MachinePointerInfo PtrInfo =
+ MachinePointerInfo::getFixedStack(MF, FrameIndex, Word * 4);
+ auto *StoreMMO = MF.getMachineMemOperand(
+ PtrInfo, MachineMemOperand::MOStore, 4,
+ commonAlignment(FrameInfo.getObjectAlign(FrameIndex), Word * 4));
+ BuildMI(MBB, MI, DL, get(AMDGPU::SI_SPILL_S32_SAVE_PARTIAL))
+ .addReg(SrcReg, getKillRegState(isKill && Lanes.none()), SubReg)
+ .addFrameIndex(FrameIndex)
+ .addImm(Word)
+ .addMemOperand(StoreMMO)
+ .addReg(MFI.getStackPtrOffsetReg(), RegState::Implicit);
+ }
+ return;
+ }
+
storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, VReg, Flags,
false);
}
+bool SIInstrInfo::canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ if (!RI.isSGPRClass(RC) || RI.getSpillSize(*RC) <= 4)
+ return false;
+
+ // SGPR tuples split into 32-bit words. Never turn a partial-word mask into
+ // a full-word store: such masks need a different preservation mechanism.
+ for (int16_t SubReg : RI.getRegSplitParts(RC, 4)) {
+ LaneBitmask Word = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & Word).any() && (Lanes & Word) != Word)
+ return false;
+ Lanes &= ~Word;
+ }
+ return Lanes.none();
+}
+
void SIInstrInfo::storeRegToStackSlotCFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
Register SrcReg, bool isKill,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.h b/llvm/lib/Target/AMDGPU/SIInstrInfo.h
index 17a511ad13bad8..c596db328c01ee 100644
--- a/llvm/lib/Target/AMDGPU/...
[truncated]
|
|
@llvm/pr-subscribers-backend-x86 Author: xgxanq ChangesKeep the lane-aware stack store interface and AMDGPU partial SGPR emission. coalesceStackAccess, eliminateRedundantSpills, addToMergeableSpills and hoistAllSpills all assume whole-slot writes and reads, which keep the slot's value consistent; a partial store breaks that consistency for the whole slot. Guard them with a slot-level PartialSpillSlots record so a slot that has seen a partial spill is left alone. The flag is sticky and conservative: it never enables a transform that a partial store would invalidate, at the cost of giving up some still-safe transforms. These four transforms are slot-level by nature, so they keep the slot record. Only isSnippet is a genuine per-instruction classification, and it already uses the isStoreToStackSlot size interface to tell a whole-value store from a partial one. Still TODO: verify reload-side lane preservation for targets without partial stores. Patch is 263.49 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/243100.diff 65 Files Affected:
diff --git a/llvm/include/llvm/CodeGen/TargetInstrInfo.h b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
index 97baf780275ee3..910175d299c894 100644
--- a/llvm/include/llvm/CodeGen/TargetInstrInfo.h
+++ b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
@@ -1225,14 +1225,33 @@ class LLVM_ABI TargetInstrInfo : public MCInstrInfo {
/// can be passed elsewhere. The \p Flags is used to set appropriate machine
/// flags on the spill instruction e.g. FrameSetup flag on a callee saved
/// register spill instruction, part of prologue, during the frame lowering.
- virtual void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const {
+ ///
+ /// \p Lanes limits the spill to those lanes of \p SrcReg (RC lane numbering,
+ /// not a byte offset); the default LaneBitmask::getAll() spills the whole
+ /// register. A target opting in via canStoreRegToStackSlotWithLanes may get a
+ /// narrower mask and must store exactly those lanes, preserving the rest of
+ /// the slot. It must not widen the store, nor report the partial store as
+ /// complete via isStoreToStackSlot.
+ virtual void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const {
llvm_unreachable("Target didn't implement "
"TargetInstrInfo::storeRegToStackSlot!");
}
+ /// Whether the target can spill exactly Lanes of RC while preserving the
+ /// other lanes of the original stack slot. Lanes uses RC's lane numbering;
+ /// it is not a byte offset. In particular, a target must not round this mask
+ /// up to a wider store. A target which opts in receives the narrower mask
+ /// through storeRegToStackSlot's \p Lanes parameter.
+ virtual bool canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ return false;
+ }
+
/// Load the specified register of the given register class from the specified
/// stack frame index. The load instruction is to be added to the given
/// machine basic block before the specified machine instruction. If \p
diff --git a/llvm/lib/CodeGen/InlineSpiller.cpp b/llvm/lib/CodeGen/InlineSpiller.cpp
index 063940a6bfe4af..2370ea59c9504c 100644
--- a/llvm/lib/CodeGen/InlineSpiller.cpp
+++ b/llvm/lib/CodeGen/InlineSpiller.cpp
@@ -16,6 +16,7 @@
#include "SplitKit.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
@@ -104,6 +105,14 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
MergeableSpillsMap MergeableSpills;
+ // Stack slots that have received a partial spill in this run. The whole-slot
+ // optimizations guarded by hasPartialSpills() assume an access covers the
+ // whole value; a partial store writes only some bytes and breaks that. The
+ // flag is sticky (we add, never remove): once a slot has seen a partial spill
+ // we skip those optimizations on it for the rest of the run. This is
+ // conservative but never miscompiles.
+ DenseSet<int> PartialSpillSlots;
+
/// This is the map from original register to a set containing all its
/// siblings. To hoist a spill to another BB, we need to find out a live
/// sibling there and use it as the source of the new spill.
@@ -141,6 +150,12 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
Register Original);
bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
void hoistAllSpills();
+ void markPartialSpillSlot(int StackSlot) {
+ PartialSpillSlots.insert(StackSlot);
+ }
+ bool hasPartialSpills(int StackSlot) const {
+ return PartialSpillSlots.contains(StackSlot);
+ }
void LRE_WillShrinkVirtReg(Register) override;
bool LRE_CanEraseVirtReg(Register) override;
void LRE_DidCloneVirtReg(Register, Register) override;
@@ -226,7 +241,8 @@ class InlineSpiller : public Spiller {
bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
MachineInstr *LoadMI = nullptr);
void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
- void insertSpill(Register VReg, MachineBasicBlock::iterator MI);
+ void insertSpill(Register VReg, MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes);
void spillAroundUses(Register Reg);
void spillAll();
@@ -234,6 +250,19 @@ class InlineSpiller : public Spiller {
} // end anonymous namespace
+// Existing subranges alone do not describe the whole register: a split child
+// can have no subrange at all for lanes which remain live in its shared slot.
+static LaneBitmask getLiveSpillLanes(const LiveInterval &LI, SlotIndex Idx,
+ const MachineRegisterInfo &MRI) {
+ if (!LI.hasSubRanges())
+ return MRI.getMaxLaneMaskForVReg(LI.reg());
+ LaneBitmask Lanes;
+ for (const LiveInterval::SubRange &SR : LI.subranges())
+ if (SR.liveAt(Idx))
+ Lanes |= SR.LaneMask;
+ return Lanes;
+}
+
Spiller::~Spiller() = default;
void Spiller::anchor() {}
@@ -369,8 +398,18 @@ bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
continue;
- // Allow stack slot stores.
- if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
+ // Allow stack slot stores, but only when the store covers the whole value.
+ // A store with a known size smaller than the spill size is a partial store,
+ // so count it as a real use instead. This matches the behavior from before
+ // partial spills were recognized here. An unknown (zero) or scalable size
+ // counts as whole-value, so targets that do not implement the size overload
+ // keep their previous behavior.
+ TypeSize StoreBytes = TypeSize::getZero();
+ if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI, StoreBytes) &&
+ FI == StackSlot &&
+ (StoreBytes.isScalable() || StoreBytes.getKnownMinValue() == 0 ||
+ StoreBytes.getKnownMinValue() ==
+ TRI.getSpillSize(*MRI.getRegClass(SnipLI.reg()))))
continue;
if (StatepointOpers::isFoldableReg(&MI, SnipLI.reg()))
@@ -492,6 +531,23 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
<< *StackInt << '\n');
+ // Query the source at the actual insertion point, not at the later copy.
+ // A lane that dies before the copy can still be available here.
+ // Dead definitions are not live after the defining instruction.
+ SlotIndex InsertIdx =
+ SrcVNI->isPHIDef()
+ ? (MII == MBB->end() ? LIS.getMBBEndIdx(MBB).getPrevSlot()
+ : LIS.getInstructionIndex(*MII))
+ : SrcVNI->def.getDeadSlot();
+ LaneBitmask Lanes = getLiveSpillLanes(SrcLI, InsertIdx, MRI);
+ if (Lanes.none())
+ return false;
+ const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(SrcReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+ if (IsPartial)
+ return false;
+
// We are going to spill SrcVNI immediately after its def, so clear out
// any later spills of the same value.
eliminateRedundantSpills(SrcLI, SrcVNI);
@@ -527,6 +583,9 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
/// redundant spills of this value in SLI.reg and sibling copies.
void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
assert(VNI && "Missing value");
+ // Do not erase spills on a slot that has partial spills. See PartialSpillSlots.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return;
SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
WorkList.push_back(std::make_pair(&SLI, VNI));
assert(StackInt && "No stack slot assigned yet.");
@@ -538,6 +597,11 @@ void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
<< VNI->def << " in " << *LI << '\n');
+ // Knowing a partial sibling is in memory does not establish that the
+ // complete original value is there.
+ if (getLiveSpillLanes(*LI, VNI->def, MRI) != MRI.getMaxLaneMaskForVReg(Reg))
+ continue;
+
// Regs to spill are taken care of.
if (isRegToSpill(Reg))
continue;
@@ -942,6 +1006,16 @@ bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
if (InstrReg != Reg || FI != StackSlot)
return false;
+ // This coalescing drops a stack access because it assumes the access covers
+ // the whole slot and the surrounding spill code already owns the complete
+ // value. A slot with partial spills breaks that assumption. A partial store
+ // writes only some of the bytes, so dropping it would lose the rest. The load
+ // side normally does not reach this point, because a reload defines a fresh
+ // vreg rather than Reg and the InstrReg != Reg check above returns first; the
+ // whole-slot bail stays here to keep the guard conservative.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return false;
+
if (!IsLoad)
HSpiller.rmFromMergeableSpills(*MI, StackSlot);
@@ -1274,7 +1348,8 @@ static bool isRealSpill(const MachineInstr &Def, Register Reg) {
/// insertSpill - Insert a spill of NewVReg after MI.
void InlineSpiller::insertSpill(Register NewVReg,
- MachineBasicBlock::iterator MI) {
+ MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes) {
// Spill are not terminators, so inserting spills after terminators will
// violate invariants in MachineVerifier.
assert(!MI->isTerminator() && "Inserting a spill after a terminator");
@@ -1283,11 +1358,20 @@ void InlineSpiller::insertSpill(Register NewVReg,
MachineInstrSpan MIS(MI, &MBB);
MachineBasicBlock::iterator SpillBefore = std::next(MI);
bool IsRealSpill = isRealSpill(*MI, NewVReg);
-
- if (IsRealSpill)
- TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot,
- MRI.getRegClass(NewVReg), Register());
- else
+ const TargetRegisterClass *RC = MRI.getRegClass(NewVReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(NewVReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+
+ if (IsRealSpill && (!IsPartial || Lanes.any())) {
+ // Partial and full stores share one hook: a partial-liveness mask spills
+ // only the live lanes and preserves the rest of the shared slot, while a
+ // full mask is the ordinary full-width spill.
+ if (IsPartial)
+ HSpiller.markPartialSpillSlot(StackSlot);
+ TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot, RC,
+ Register(), MachineInstr::NoFlags,
+ IsPartial ? Lanes : LaneBitmask::getAll());
+ } else
// Don't spill undef value.
// Anything works for undef, in particular keeping the memory
// uninitialized is a viable option and it saves code size and
@@ -1306,7 +1390,7 @@ void InlineSpiller::insertSpill(Register NewVReg,
// If there is only 1 store instruction is required for spill, add it
// to mergeable list. In X86 AMX, 2 instructions are required to store.
// We disable the merge for this case.
- if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
+ if (IsRealSpill && !IsPartial && std::distance(Spill, MIS.end()) <= 1)
HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
}
@@ -1349,6 +1433,11 @@ void InlineSpiller::spillAroundUses(Register Reg) {
if (SlotIndex::isSameInstr(Idx, VNI->def))
Idx = VNI->def;
+ // Read the old interval before changing operands or constructing the
+ // short spill temporary. It may have only a subset of the original lanes.
+ // insertSpill below uses this to decide between a partial and a full store.
+ LaneBitmask Lanes = getLiveSpillLanes(OldLI, Idx, MRI);
+
// Check for a sibling copy.
Register SibReg = isCopyOfBundle(MI, Reg, TII);
if (SibReg && isSibling(SibReg)) {
@@ -1397,7 +1486,7 @@ void InlineSpiller::spillAroundUses(Register Reg) {
// FIXME: Use a second vreg if instruction has no tied ops.
if (RI.Writes)
if (hasLiveDef)
- insertSpill(NewVReg, &MI);
+ insertSpill(NewVReg, &MI, Lanes);
}
}
@@ -1485,6 +1574,10 @@ void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
/// When a spill is inserted, add the spill to MergeableSpills map.
void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
Register Original) {
+ // Do not make a slot with partial spills a hoist candidate. See
+ // PartialSpillSlots.
+ if (hasPartialSpills(StackSlot))
+ return;
BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
LiveInterval &OrigLI = LIS.getInterval(Original);
// save a copy of LiveInterval in StackSlotToOrigLI because the original
@@ -1540,9 +1633,7 @@ bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
// All of the sub-ranges should be alive at the prospective slot index.
// Otherwise, we might risk storing unrelated / compromised values from some
// sub-registers to the spill slot.
- if (all_of(LI.subranges(), [&](const LiveInterval::SubRange &SR) {
- return SR.getVNInfoAt(Idx) != nullptr;
- })) {
+ if (getLiveSpillLanes(LI, Idx, MRI) == MRI.getMaxLaneMaskForVReg(SibReg)) {
LiveReg = SibReg;
return true;
}
@@ -1817,6 +1908,9 @@ void HoistSpillHelper::hoistAllSpills() {
// Each entry in MergeableSpills contains a spill set with equal values.
for (auto &Ent : MergeableSpills) {
int Slot = Ent.first.first;
+ // Skip hoisting on a slot that has partial spills. See PartialSpillSlots.
+ if (hasPartialSpills(Slot))
+ continue;
LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
VNInfo *OrigVNI = Ent.first.second;
SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
index 40f5d0ef2383eb..bc2b800c802485 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
@@ -6453,12 +6453,10 @@ static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
.addMemOperand(MMO);
}
-void AArch64InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
- MachineBasicBlock::iterator MBBI,
- Register SrcReg, bool isKill, int FI,
- const TargetRegisterClass *RC,
- Register VReg,
- MachineInstr::MIFlag Flags) const {
+void AArch64InstrInfo::storeRegToStackSlot(
+ MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
+ bool isKill, int FI, const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = MF.getFrameInfo();
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.h b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
index 8f34c3b6f48532..195ab38360590f 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
@@ -376,10 +376,12 @@ class AArch64InstrInfo final : public AArch64GenInstrInfo {
bool KillSrc, bool RenamableDest = false,
bool RenamableSrc = false) const override;
- void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const override;
+ void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const override;
void loadRegFromStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index 63ae0f06f4c9b7..8836fcb02f1393 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -1803,11 +1803,61 @@ void SIInstrInfo::storeRegToStackSlotImpl(
void SIInstrInfo::storeRegToStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags) const {
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
+ // A narrower-than-full mask requests a partial spill that preserves the
+ // other words of the shared slot. Otherwise emit the ordinary full-width
+ // store, including when this class does not support partial spills.
+ if (Lanes != LaneBitmask::getAll() &&
+ canStoreRegToStackSlotWithLanes(RC, Lanes)) {
+ MachineFunction &MF = *MBB.getParent();
+ SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
+ MachineFrameInfo &FrameInfo = MF.getFrameInfo();
+ if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
+ MFI.setHasSpilledSGPRs();
+ const DebugLoc &DL = MBB.findDebugLoc(MI);
+
+ auto Parts = RI.getRegSplitParts(RC, 4);
+ for (unsigned Word = 0; Word != Parts.size(); ++Word) {
+ unsigned SubReg = Parts[Word];
+ LaneBitmask WordLanes = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & WordLanes).none())
+ continue;
+ Lanes &= ~WordLanes;
+ MachinePointerInfo PtrInfo =
+ MachinePointerInfo::getFixedStack(MF, FrameIndex, Word * 4);
+ auto *StoreMMO = MF.getMachineMemOperand(
+ PtrInfo, MachineMemOperand::MOStore, 4,
+ commonAlignment(FrameInfo.getObjectAlign(FrameIndex), Word * 4));
+ BuildMI(MBB, MI, DL, get(AMDGPU::SI_SPILL_S32_SAVE_PARTIAL))
+ .addReg(SrcReg, getKillRegState(isKill && Lanes.none()), SubReg)
+ .addFrameIndex(FrameIndex)
+ .addImm(Word)
+ .addMemOperand(StoreMMO)
+ .addReg(MFI.getStackPtrOffsetReg(), RegState::Implicit);
+ }
+ return;
+ }
+
storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, VReg, Flags,
false);
}
+bool SIInstrInfo::canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ if (!RI.isSGPRClass(RC) || RI.getSpillSize(*RC) <= 4)
+ return false;
+
+ // SGPR tuples split into 32-bit words. Never turn a partial-word mask into
+ // a full-word store: such masks need a different preservation mechanism.
+ for (int16_t SubReg : RI.getRegSplitParts(RC, 4)) {
+ LaneBitmask Word = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & Word).any() && (Lanes & Word) != Word)
+ return false;
+ Lanes &= ~Word;
+ }
+ return Lanes.none();
+}
+
void SIInstrInfo::storeRegToStackSlotCFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
Register SrcReg, bool isKill,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.h b/llvm/lib/Target/AMDGPU/SIInstrInfo.h
index 17a511ad13bad8..c596db328c01ee 100644
--- a/llvm/lib/Target/AMDGPU/...
[truncated]
|
|
@llvm/pr-subscribers-llvm-regalloc Author: xgxanq ChangesKeep the lane-aware stack store interface and AMDGPU partial SGPR emission. coalesceStackAccess, eliminateRedundantSpills, addToMergeableSpills and hoistAllSpills all assume whole-slot writes and reads, which keep the slot's value consistent; a partial store breaks that consistency for the whole slot. Guard them with a slot-level PartialSpillSlots record so a slot that has seen a partial spill is left alone. The flag is sticky and conservative: it never enables a transform that a partial store would invalidate, at the cost of giving up some still-safe transforms. These four transforms are slot-level by nature, so they keep the slot record. Only isSnippet is a genuine per-instruction classification, and it already uses the isStoreToStackSlot size interface to tell a whole-value store from a partial one. Still TODO: verify reload-side lane preservation for targets without partial stores. Patch is 263.49 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/243100.diff 65 Files Affected:
diff --git a/llvm/include/llvm/CodeGen/TargetInstrInfo.h b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
index 97baf780275ee3..910175d299c894 100644
--- a/llvm/include/llvm/CodeGen/TargetInstrInfo.h
+++ b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
@@ -1225,14 +1225,33 @@ class LLVM_ABI TargetInstrInfo : public MCInstrInfo {
/// can be passed elsewhere. The \p Flags is used to set appropriate machine
/// flags on the spill instruction e.g. FrameSetup flag on a callee saved
/// register spill instruction, part of prologue, during the frame lowering.
- virtual void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const {
+ ///
+ /// \p Lanes limits the spill to those lanes of \p SrcReg (RC lane numbering,
+ /// not a byte offset); the default LaneBitmask::getAll() spills the whole
+ /// register. A target opting in via canStoreRegToStackSlotWithLanes may get a
+ /// narrower mask and must store exactly those lanes, preserving the rest of
+ /// the slot. It must not widen the store, nor report the partial store as
+ /// complete via isStoreToStackSlot.
+ virtual void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const {
llvm_unreachable("Target didn't implement "
"TargetInstrInfo::storeRegToStackSlot!");
}
+ /// Whether the target can spill exactly Lanes of RC while preserving the
+ /// other lanes of the original stack slot. Lanes uses RC's lane numbering;
+ /// it is not a byte offset. In particular, a target must not round this mask
+ /// up to a wider store. A target which opts in receives the narrower mask
+ /// through storeRegToStackSlot's \p Lanes parameter.
+ virtual bool canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ return false;
+ }
+
/// Load the specified register of the given register class from the specified
/// stack frame index. The load instruction is to be added to the given
/// machine basic block before the specified machine instruction. If \p
diff --git a/llvm/lib/CodeGen/InlineSpiller.cpp b/llvm/lib/CodeGen/InlineSpiller.cpp
index 063940a6bfe4af..2370ea59c9504c 100644
--- a/llvm/lib/CodeGen/InlineSpiller.cpp
+++ b/llvm/lib/CodeGen/InlineSpiller.cpp
@@ -16,6 +16,7 @@
#include "SplitKit.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
@@ -104,6 +105,14 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
MergeableSpillsMap MergeableSpills;
+ // Stack slots that have received a partial spill in this run. The whole-slot
+ // optimizations guarded by hasPartialSpills() assume an access covers the
+ // whole value; a partial store writes only some bytes and breaks that. The
+ // flag is sticky (we add, never remove): once a slot has seen a partial spill
+ // we skip those optimizations on it for the rest of the run. This is
+ // conservative but never miscompiles.
+ DenseSet<int> PartialSpillSlots;
+
/// This is the map from original register to a set containing all its
/// siblings. To hoist a spill to another BB, we need to find out a live
/// sibling there and use it as the source of the new spill.
@@ -141,6 +150,12 @@ class HoistSpillHelper : private LiveRangeEdit::Delegate {
Register Original);
bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
void hoistAllSpills();
+ void markPartialSpillSlot(int StackSlot) {
+ PartialSpillSlots.insert(StackSlot);
+ }
+ bool hasPartialSpills(int StackSlot) const {
+ return PartialSpillSlots.contains(StackSlot);
+ }
void LRE_WillShrinkVirtReg(Register) override;
bool LRE_CanEraseVirtReg(Register) override;
void LRE_DidCloneVirtReg(Register, Register) override;
@@ -226,7 +241,8 @@ class InlineSpiller : public Spiller {
bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
MachineInstr *LoadMI = nullptr);
void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
- void insertSpill(Register VReg, MachineBasicBlock::iterator MI);
+ void insertSpill(Register VReg, MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes);
void spillAroundUses(Register Reg);
void spillAll();
@@ -234,6 +250,19 @@ class InlineSpiller : public Spiller {
} // end anonymous namespace
+// Existing subranges alone do not describe the whole register: a split child
+// can have no subrange at all for lanes which remain live in its shared slot.
+static LaneBitmask getLiveSpillLanes(const LiveInterval &LI, SlotIndex Idx,
+ const MachineRegisterInfo &MRI) {
+ if (!LI.hasSubRanges())
+ return MRI.getMaxLaneMaskForVReg(LI.reg());
+ LaneBitmask Lanes;
+ for (const LiveInterval::SubRange &SR : LI.subranges())
+ if (SR.liveAt(Idx))
+ Lanes |= SR.LaneMask;
+ return Lanes;
+}
+
Spiller::~Spiller() = default;
void Spiller::anchor() {}
@@ -369,8 +398,18 @@ bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
continue;
- // Allow stack slot stores.
- if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
+ // Allow stack slot stores, but only when the store covers the whole value.
+ // A store with a known size smaller than the spill size is a partial store,
+ // so count it as a real use instead. This matches the behavior from before
+ // partial spills were recognized here. An unknown (zero) or scalable size
+ // counts as whole-value, so targets that do not implement the size overload
+ // keep their previous behavior.
+ TypeSize StoreBytes = TypeSize::getZero();
+ if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI, StoreBytes) &&
+ FI == StackSlot &&
+ (StoreBytes.isScalable() || StoreBytes.getKnownMinValue() == 0 ||
+ StoreBytes.getKnownMinValue() ==
+ TRI.getSpillSize(*MRI.getRegClass(SnipLI.reg()))))
continue;
if (StatepointOpers::isFoldableReg(&MI, SnipLI.reg()))
@@ -492,6 +531,23 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
<< *StackInt << '\n');
+ // Query the source at the actual insertion point, not at the later copy.
+ // A lane that dies before the copy can still be available here.
+ // Dead definitions are not live after the defining instruction.
+ SlotIndex InsertIdx =
+ SrcVNI->isPHIDef()
+ ? (MII == MBB->end() ? LIS.getMBBEndIdx(MBB).getPrevSlot()
+ : LIS.getInstructionIndex(*MII))
+ : SrcVNI->def.getDeadSlot();
+ LaneBitmask Lanes = getLiveSpillLanes(SrcLI, InsertIdx, MRI);
+ if (Lanes.none())
+ return false;
+ const TargetRegisterClass *RC = MRI.getRegClass(SrcReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(SrcReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+ if (IsPartial)
+ return false;
+
// We are going to spill SrcVNI immediately after its def, so clear out
// any later spills of the same value.
eliminateRedundantSpills(SrcLI, SrcVNI);
@@ -527,6 +583,9 @@ bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
/// redundant spills of this value in SLI.reg and sibling copies.
void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
assert(VNI && "Missing value");
+ // Do not erase spills on a slot that has partial spills. See PartialSpillSlots.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return;
SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
WorkList.push_back(std::make_pair(&SLI, VNI));
assert(StackInt && "No stack slot assigned yet.");
@@ -538,6 +597,11 @@ void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
<< VNI->def << " in " << *LI << '\n');
+ // Knowing a partial sibling is in memory does not establish that the
+ // complete original value is there.
+ if (getLiveSpillLanes(*LI, VNI->def, MRI) != MRI.getMaxLaneMaskForVReg(Reg))
+ continue;
+
// Regs to spill are taken care of.
if (isRegToSpill(Reg))
continue;
@@ -942,6 +1006,16 @@ bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
if (InstrReg != Reg || FI != StackSlot)
return false;
+ // This coalescing drops a stack access because it assumes the access covers
+ // the whole slot and the surrounding spill code already owns the complete
+ // value. A slot with partial spills breaks that assumption. A partial store
+ // writes only some of the bytes, so dropping it would lose the rest. The load
+ // side normally does not reach this point, because a reload defines a fresh
+ // vreg rather than Reg and the InstrReg != Reg check above returns first; the
+ // whole-slot bail stays here to keep the guard conservative.
+ if (HSpiller.hasPartialSpills(StackSlot))
+ return false;
+
if (!IsLoad)
HSpiller.rmFromMergeableSpills(*MI, StackSlot);
@@ -1274,7 +1348,8 @@ static bool isRealSpill(const MachineInstr &Def, Register Reg) {
/// insertSpill - Insert a spill of NewVReg after MI.
void InlineSpiller::insertSpill(Register NewVReg,
- MachineBasicBlock::iterator MI) {
+ MachineBasicBlock::iterator MI,
+ LaneBitmask Lanes) {
// Spill are not terminators, so inserting spills after terminators will
// violate invariants in MachineVerifier.
assert(!MI->isTerminator() && "Inserting a spill after a terminator");
@@ -1283,11 +1358,20 @@ void InlineSpiller::insertSpill(Register NewVReg,
MachineInstrSpan MIS(MI, &MBB);
MachineBasicBlock::iterator SpillBefore = std::next(MI);
bool IsRealSpill = isRealSpill(*MI, NewVReg);
-
- if (IsRealSpill)
- TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot,
- MRI.getRegClass(NewVReg), Register());
- else
+ const TargetRegisterClass *RC = MRI.getRegClass(NewVReg);
+ bool IsPartial = Lanes != MRI.getMaxLaneMaskForVReg(NewVReg) &&
+ TII.canStoreRegToStackSlotWithLanes(RC, Lanes);
+
+ if (IsRealSpill && (!IsPartial || Lanes.any())) {
+ // Partial and full stores share one hook: a partial-liveness mask spills
+ // only the live lanes and preserves the rest of the shared slot, while a
+ // full mask is the ordinary full-width spill.
+ if (IsPartial)
+ HSpiller.markPartialSpillSlot(StackSlot);
+ TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot, RC,
+ Register(), MachineInstr::NoFlags,
+ IsPartial ? Lanes : LaneBitmask::getAll());
+ } else
// Don't spill undef value.
// Anything works for undef, in particular keeping the memory
// uninitialized is a viable option and it saves code size and
@@ -1306,7 +1390,7 @@ void InlineSpiller::insertSpill(Register NewVReg,
// If there is only 1 store instruction is required for spill, add it
// to mergeable list. In X86 AMX, 2 instructions are required to store.
// We disable the merge for this case.
- if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
+ if (IsRealSpill && !IsPartial && std::distance(Spill, MIS.end()) <= 1)
HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
}
@@ -1349,6 +1433,11 @@ void InlineSpiller::spillAroundUses(Register Reg) {
if (SlotIndex::isSameInstr(Idx, VNI->def))
Idx = VNI->def;
+ // Read the old interval before changing operands or constructing the
+ // short spill temporary. It may have only a subset of the original lanes.
+ // insertSpill below uses this to decide between a partial and a full store.
+ LaneBitmask Lanes = getLiveSpillLanes(OldLI, Idx, MRI);
+
// Check for a sibling copy.
Register SibReg = isCopyOfBundle(MI, Reg, TII);
if (SibReg && isSibling(SibReg)) {
@@ -1397,7 +1486,7 @@ void InlineSpiller::spillAroundUses(Register Reg) {
// FIXME: Use a second vreg if instruction has no tied ops.
if (RI.Writes)
if (hasLiveDef)
- insertSpill(NewVReg, &MI);
+ insertSpill(NewVReg, &MI, Lanes);
}
}
@@ -1485,6 +1574,10 @@ void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
/// When a spill is inserted, add the spill to MergeableSpills map.
void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
Register Original) {
+ // Do not make a slot with partial spills a hoist candidate. See
+ // PartialSpillSlots.
+ if (hasPartialSpills(StackSlot))
+ return;
BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
LiveInterval &OrigLI = LIS.getInterval(Original);
// save a copy of LiveInterval in StackSlotToOrigLI because the original
@@ -1540,9 +1633,7 @@ bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
// All of the sub-ranges should be alive at the prospective slot index.
// Otherwise, we might risk storing unrelated / compromised values from some
// sub-registers to the spill slot.
- if (all_of(LI.subranges(), [&](const LiveInterval::SubRange &SR) {
- return SR.getVNInfoAt(Idx) != nullptr;
- })) {
+ if (getLiveSpillLanes(LI, Idx, MRI) == MRI.getMaxLaneMaskForVReg(SibReg)) {
LiveReg = SibReg;
return true;
}
@@ -1817,6 +1908,9 @@ void HoistSpillHelper::hoistAllSpills() {
// Each entry in MergeableSpills contains a spill set with equal values.
for (auto &Ent : MergeableSpills) {
int Slot = Ent.first.first;
+ // Skip hoisting on a slot that has partial spills. See PartialSpillSlots.
+ if (hasPartialSpills(Slot))
+ continue;
LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
VNInfo *OrigVNI = Ent.first.second;
SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
index 40f5d0ef2383eb..bc2b800c802485 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
@@ -6453,12 +6453,10 @@ static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
.addMemOperand(MMO);
}
-void AArch64InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
- MachineBasicBlock::iterator MBBI,
- Register SrcReg, bool isKill, int FI,
- const TargetRegisterClass *RC,
- Register VReg,
- MachineInstr::MIFlag Flags) const {
+void AArch64InstrInfo::storeRegToStackSlot(
+ MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
+ bool isKill, int FI, const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
MachineFunction &MF = *MBB.getParent();
MachineFrameInfo &MFI = MF.getFrameInfo();
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.h b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
index 8f34c3b6f48532..195ab38360590f 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
@@ -376,10 +376,12 @@ class AArch64InstrInfo final : public AArch64GenInstrInfo {
bool KillSrc, bool RenamableDest = false,
bool RenamableSrc = false) const override;
- void storeRegToStackSlot(
- MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
- bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags = MachineInstr::NoFlags) const override;
+ void
+ storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
+ Register SrcReg, bool isKill, int FrameIndex,
+ const TargetRegisterClass *RC, Register VReg,
+ MachineInstr::MIFlag Flags = MachineInstr::NoFlags,
+ LaneBitmask Lanes = LaneBitmask::getAll()) const override;
void loadRegFromStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index 63ae0f06f4c9b7..8836fcb02f1393 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -1803,11 +1803,61 @@ void SIInstrInfo::storeRegToStackSlotImpl(
void SIInstrInfo::storeRegToStackSlot(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg,
bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
- MachineInstr::MIFlag Flags) const {
+ MachineInstr::MIFlag Flags, LaneBitmask Lanes) const {
+ // A narrower-than-full mask requests a partial spill that preserves the
+ // other words of the shared slot. Otherwise emit the ordinary full-width
+ // store, including when this class does not support partial spills.
+ if (Lanes != LaneBitmask::getAll() &&
+ canStoreRegToStackSlotWithLanes(RC, Lanes)) {
+ MachineFunction &MF = *MBB.getParent();
+ SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
+ MachineFrameInfo &FrameInfo = MF.getFrameInfo();
+ if (FrameInfo.getStackID(FrameIndex) == TargetStackID::SGPRSpill)
+ MFI.setHasSpilledSGPRs();
+ const DebugLoc &DL = MBB.findDebugLoc(MI);
+
+ auto Parts = RI.getRegSplitParts(RC, 4);
+ for (unsigned Word = 0; Word != Parts.size(); ++Word) {
+ unsigned SubReg = Parts[Word];
+ LaneBitmask WordLanes = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & WordLanes).none())
+ continue;
+ Lanes &= ~WordLanes;
+ MachinePointerInfo PtrInfo =
+ MachinePointerInfo::getFixedStack(MF, FrameIndex, Word * 4);
+ auto *StoreMMO = MF.getMachineMemOperand(
+ PtrInfo, MachineMemOperand::MOStore, 4,
+ commonAlignment(FrameInfo.getObjectAlign(FrameIndex), Word * 4));
+ BuildMI(MBB, MI, DL, get(AMDGPU::SI_SPILL_S32_SAVE_PARTIAL))
+ .addReg(SrcReg, getKillRegState(isKill && Lanes.none()), SubReg)
+ .addFrameIndex(FrameIndex)
+ .addImm(Word)
+ .addMemOperand(StoreMMO)
+ .addReg(MFI.getStackPtrOffsetReg(), RegState::Implicit);
+ }
+ return;
+ }
+
storeRegToStackSlotImpl(MBB, MI, SrcReg, isKill, FrameIndex, RC, VReg, Flags,
false);
}
+bool SIInstrInfo::canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC,
+ LaneBitmask Lanes) const {
+ if (!RI.isSGPRClass(RC) || RI.getSpillSize(*RC) <= 4)
+ return false;
+
+ // SGPR tuples split into 32-bit words. Never turn a partial-word mask into
+ // a full-word store: such masks need a different preservation mechanism.
+ for (int16_t SubReg : RI.getRegSplitParts(RC, 4)) {
+ LaneBitmask Word = RI.getSubRegIndexLaneMask(SubReg);
+ if ((Lanes & Word).any() && (Lanes & Word) != Word)
+ return false;
+ Lanes &= ~Word;
+ }
+ return Lanes.none();
+}
+
void SIInstrInfo::storeRegToStackSlotCFI(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
Register SrcReg, bool isKill,
diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.h b/llvm/lib/Target/AMDGPU/SIInstrInfo.h
index 17a511ad13bad8..c596db328c01ee 100644
--- a/llvm/lib/Target/AMDGPU/...
[truncated]
|
|
✅ With the latest revision this PR passed the C/C++ code formatter. |
ab771a3 to
92edaf7
Compare
92edaf7 to
3744672
Compare
🐧 Linux x64 Test Results
✅ The build succeeded and all tests passed. |
🪟 Windows x64 Test Results
✅ The build succeeded and all tests passed. |
38487b2 to
d9770d2
Compare
8174070 to
29c4cb2
Compare
…tive guards Keep the lane-aware stack store interface and AMDGPU partial SGPR emission. coalesceStackAccess, eliminateRedundantSpills, addToMergeableSpills and hoistAllSpills all assume whole-slot writes and reads, which keep the slot's value consistent; a partial store breaks that consistency for the whole slot. Guard them with a slot-level PartialSpillSlots record so a slot that has seen a partial spill is left alone. The flag is sticky and conservative: it never enables a transform that a partial store would invalidate, at the cost of giving up some still-safe transforms. These four transforms are slot-level by nature, so they keep the slot record. Only isSnippet is a genuine per-instruction classification, and it already uses the isStoreToStackSlot size interface to tell a whole-value store from a partial one. Still TODO: verify reload-side lane preservation for targets without partial stores. Tests ----- New partial SGPR store coverage: - inline-spiller-partial-sgpr-spill-gfx1151.ll: only the defined words are stored, via per-word SI_SPILL_S32_SAVE_PARTIAL. - spill-partial-sgpr-lanes.mir: each store touches only its source lanes. - lower-partial-sgpr-spills.mir: si-lower-sgpr-spills / PEI lowering. Existing tests regenerated; the spiller now emits per-word SAVE_PARTIAL for partial SGPR tuples: - CHECK now shows SAVE_PARTIAL, spill count unchanged: greedy-alloc-fail-sgpr1024-spill.mir, infloop-subrange-spill-inspect-subrange.mir, ra-inserted-scalar-instructions.mir, ran-out-of-sgprs-allocation-failure.mir, splitkit.mir, splitkit-copy-bundle.mir, splitkit-nolivesubranges.mir. - Improvement, only the live word stored: load-constant-i1.ll. - Known regression, left for follow-up coalescing: identical-subrange-spill-infloop.ll, spill-scavenge-offset.ll. - Spill-sequence churn from the partial SGPR spill, functionally equivalent (SI and VI runs): amdgcn.bitcast.1024bit.ll.
…partial-store fixes Add a preservation fallback for targets without a native lane-masked store. When a write-only partial def lands in a slot that still holds other live lanes, reload them before the def and store the whole register back, so the full-width store keeps them instead of clobbering them. hoistSpillInsideBB uses this path when SrcReg does not cover the lanes to keep. A new VGPR preservation test covers it. Also revert two getLiveSpillLanes checks the previous commit added to make the whole-slot transforms lane-aware; the slot-level hasPartialSpills guard already covers partial slots. Regenerate amdgcn.bitcast.1024bit.ll: the only change from upstream is the SI run of bitcast_v64bf16_to_v128i8_scalar, the one function using the native partial store; every other run returns to the upstream sequence. Update regalloc-remat-early-clobber-partial-def.mir: the partial def now spills only its defined words. Marking the slot partial also disables coalesceStackAccess on it, so a redundant whole-register store to the slot is no longer dropped and one reload/store pair is left in place; the result is verifier-clean.
29c4cb2 to
dbb04bf
Compare
Reorganize spillAroundUses's partial-def spill around a single signal, LiveUncovered: the unwritten lanes of a partial def that the original is still live in. A non-empty LiveUncovered would be clobbered by a full-width store into the shared slot, so it must be preserved -- with a native lane-masked store (write only the defined lanes, mark the slot partially spilled) or, absent one, a reload + full-width store. An empty LiveUncovered (e.g. an undef partial def whose other lanes are dead) needs neither and takes a plain full-width store. Drop the whole-slot partial-spill guard in coalesceStackAccess: an access that names Reg and targets Reg's own stack slot just copies the slot onto itself and is redundant lane-for-lane even under partial spills, so no guard is needed. Restricting partial stores to the genuine-patchwork case returns several AMDGPU spill tests to their upstream codegen (undef partial defs now spill full-width as before). The remaining ones are regenerated and keep spill traffic flat or slightly lower, except identical-subrange-spill-infloop.ll (+8 writelane, +16 readlane), where per-word partial stores add lane copies on that subrange-dense function.
dbb04bf to
99126a8
Compare
| // Scratch lowering may read the other words to preserve them when no SGPR is | ||
| // available to save EXEC. The data operand only reads this one source word. | ||
| let UseNamedOperandTable = 1, Spill = 1, SALU = 1, Uses = [EXEC], | ||
| mayStore = 1, mayLoad = 0 in |
There was a problem hiding this comment.
The comment above says scratch lowering may read the other words, but the pseudo has mayLoad = 0 and a store-only MMO?
There was a problem hiding this comment.
The comment above says scratch lowering may read the other words, but the pseudo has
mayLoad = 0and a store-only MMO?
This part originally came from an AI-generated patch quetin handed me; the AI wasn't fully correct, so it still needs human eyes on it. I changed this mayLoad myself after thinking it through, but the comment is indeed out of date.
Good catch — you're right that the lowering can emit a real read, but only on one fallback path: when the partial save is expanded at PEI and there's no free SGPR to save EXEC (SB.IsPartial && !SB.SavedExecReg), readWriteTmpVGPR(IsLoad=true) reloads the slot's other words so they can be written back unchanged.
That's an internal read-preserve-write of the slot's own other words, not a real load of any value, so the pseudo's net memory effect is still just a partial store. Modeling it as mayLoad = 0 with a store-only MMO is deliberate and, I'd argue, the more correct choice:
-
Whether that read even happens is only known at PEI expansion time, so it shouldn't leak into the high-level pseudo's semantics.
-
The only thing the hidden read could alias with is another store to the same slot, and store↔store ordering on the same frame index already serializes the whole pseudo after those —so mayLoad = 0 doesn't open any reordering hole.
-
Keeping it store-only is also what lets isStoreToStackSlot recognize it with the correct MemBytes, which several consumers rely on.
So this is just a stale comment, not a bug — I'll reword the comment to make clear the read is an internal preservation step in the PEI fallback and that the pseudo is intentionally store-only.
e05c0ad to
3d5992b
Compare
| // partial store on a target that has no native one. | ||
| bool NeedsLanePreservation = LiveUncovered.any() && | ||
| !NeedsNativePartialStore && !RI.Reads && | ||
| StackInt->liveAt(Idx.getBaseIndex()); |
There was a problem hiding this comment.
Is there any danger that StackInt is not yet live when we come through here, but becomes live later due to another sibling being spilled?
There was a problem hiding this comment.
vreg-live ≠ slot-live
It's dangers just as following:
undef %reg.subX = ...
There was a problem hiding this comment.
To clarify: I understand why the gate is there. My question is about ordering. StackInt only contains the siblings spilled so far. Suppose that at this partial def, the LiveUncovered lanes are still held in a register by sibling S, so the gate is false and we emit a plain full-width store. If S is spilled later, its store lands before this def and its reloads after it, and this full-width store overwrites the lanes in between. What guarantees that S is always spilled before this point?
There was a problem hiding this comment.
You described this situtation as follows:
mir
bb.0:
%s:sreg_64 = COPY %init ; S.def — before (). %s holds lane B
...
undef %r.sub0 = COPY %x.sub0 ; () R.def: defines only lane A (sub0)
; Original.sub1 is still live here (value is in reg %s)
; → LiveUncovered = sub1
...
S_NOP implicit %r.sub0 ; R.use — after () (lane A)
...
S_NOP implicit %s ; S.use — after () (lane B) ← S is live across (*)
Key: %s.def < () < %s.use, so S is live across () on lane B; at (*), R writes only lane A and never touches sub1.
Snapshot 1 — Round 1 spills R (gate = false → full-width store)
In this round RegsToSpill = {%r} (%s is a different sibling, not in this round). StackInt has only %r merged. At (*)'s getBaseIndex() (the slot just before the def), the slot is not live:
NeedsPartialStore = sub1.any() ✔ && canStoreWithLanes(sub0) ✔
&& StackInt->liveAt(().base) ✘ ← only %r this round, %r starts live at ()
= false → full-width
mir
bb.0:
%s:sreg_64 = COPY %init
...
undef %r2.sub0 = COPY %x.sub0 ; (*) rewritten R.def
SI_SPILL_S64_SAVE %r2, %stack.0 ; (S_R) full-width store: slot.sub0 = A (real), slot.sub1 = GARBAGE
; (%r2.sub1 is undef → garbage is written)
...
%r3 = SI_SPILL_S64_RESTORE %stack.0 ; R.reload
S_NOP implicit %r3.sub0 ; R.use reads slot.sub0 → A correct ✔ (R only cares about lane A)
...
S_NOP implicit %s ; %s is still a register, untouched this round
At this point the garbage in lane B is not read by anyone yet (%s's value is safely still in a register) — this is exactly the "when gate is false, nobody cares about the uncovered lanes" case. Correct — in this round nobody cares.
Snapshot 2 — Round 2 spills S (store lands before (), reload after ())
Spilling %s: the store is pinned right after %s.def (→ before ()); the reload is pinned right before the %s.sub1 use (→ after ()). Same stack.0 is reused.
mir
bb.0:
%s2:sreg_64 = COPY %init
SI_SPILL_S64_SAVE %s2, %stack.0 ; (S_S) S store: slot.sub1 = B (real) ← before ()!
...
undef %r2.sub0 = COPY %x.sub0 ; ()
SI_SPILL_S64_SAVE %r2, %stack.0 ; (S_R) R full-width store: slot.sub1 overwritten with GARBAGE ← sandwiched!
...
%r3 = SI_SPILL_S64_RESTORE %stack.0
S_NOP implicit %r3
...
%s3 = SI_SPILL_S64_RESTORE %stack.0 ; (L_S) S reload: reads slot.sub1 ← after (*)
S_NOP implicit %s3 ; reads GARBAGE ✗✗✗ MISCOMPILE
Memory timeline for lane B (slot.sub1)
program order instruction slot.sub1
(S_S) before () S store → B (real) ✔ ← S's store is pinned after S.def, naturally before ()
(S_R) at () R full store → garbage ✗ ← sandwiched in between, clobbers it
(L_S) after () S reload → reads garbage ✗ → %s3.sub1 is wrong
This maybe possible.
There was a problem hiding this comment.
This requires structural changes: either enforce an ordering constraint so that S is spilled to the slot before R, or avoid slot sharing entirely for these per-lane mutually-live sibling registers. However, I do not recommend this local approach that breaks the one-slot-one-value invariant.
NeedsLanePreservation serves targets without native partial spill support (non-AMDGPU). I intend to drop this path for the time being and concentrate on refining the AMDGPU-specific logic. If we want to enable this support later, we will need to address the issue we have been discussing.
| !NeedsNativePartialStore && !RI.Reads && | ||
| StackInt->liveAt(Idx.getBaseIndex()); | ||
| if (NeedsNativePartialStore) | ||
| HSpiller.markPartialSpillSlot(StackSlot); |
There was a problem hiding this comment.
Should we be marking this so early here or wait until hoisting is done?
There was a problem hiding this comment.
Yes, that is correct. This condition indicates that insertSpill will create a partial spill.
There was a problem hiding this comment.
I don't think that holds: if hoistSpillInsideBB succeeds (the case where KeepLanes is a subset of Lanes), it emits a full-width store of the source and we continue, so insertSpill never runs. The slot is still marked, which also makes that hoist's own eliminateRedundantSpills return early. Could we mark the slot in insertSpill when StoreMask != LaneBitmask::getAll() instead?
There was a problem hiding this comment.
I don't think that holds: if
hoistSpillInsideBBsucceeds (the case whereKeepLanesis a subset ofLanes), it emits a full-width store of the source and we continue, soinsertSpillnever runs. The slot is still marked, which also makes that hoist's owneliminateRedundantSpillsreturn early. Could we mark the slot ininsertSpillwhenStoreMask != LaneBitmask::getAll()instead?
Yes.
|
|
||
| // Attempt to fold memory ops. | ||
| if (foldMemoryOperand(Ops)) | ||
| if (!NeedsLanePreservation && foldMemoryOperand(Ops)) |
There was a problem hiding this comment.
Do we need to check LiveUncovered here as well?
There was a problem hiding this comment.
if (!NeedsLanePreservation && LiveUncovered.none()&&foldMemoryOperand(Ops)) is better
There was a problem hiding this comment.
Thanks, that works. One small simplification: NeedsLanePreservation already implies LiveUncovered.any(), so the first check is redundant and this should be enough:
if (LiveUncovered.none() && foldMemoryOperand(Ops))
continue;| if (Lanes != LaneBitmask::getAll() && | ||
| canStoreRegToStackSlotWithLanes(RC, Lanes)) { |
There was a problem hiding this comment.
Nit: Should the canStoreRegToStackSlotWithLanes be an assertion instead, to avoid silently widening?
| //===- PartialSpillTest.cpp - Partial SGPR spill tests | ||
| //---------------------===// |
There was a problem hiding this comment.
Nit: Broken formatting.
| /// it is not a byte offset. In particular, a target must not round this mask | ||
| /// up to a wider store. A target which opts in receives the narrower mask | ||
| /// through storeRegToStackSlot's \p Lanes parameter. | ||
| virtual bool canStoreRegToStackSlotWithLanes(const TargetRegisterClass *RC, |
There was a problem hiding this comment.
Shouldn't need this. The existing spill hooks should simply be provided a LaneBitmask for them to deal with. We shouldn't need 2 parallel interfaces
Keep the lane-aware stack store interface and AMDGPU partial SGPR emission. eliminateRedundantSpills, addToMergeableSpills and hoistAllSpills all assume whole-slot writes and reads, which keep the slot's value consistent; a partial store breaks that consistency for the whole slot. Guard them with a slot-level PartialSpillSlots record so a slot that has seen a partial spill is left alone. The flag is sticky and conservative: it never enables a transform that a partial store would invalidate, at the cost of giving up some still-safe transforms.
These four transforms are slot-level by nature, so they keep the slot record. Only isSnippet is a genuine per-instruction classification, and it already uses the isStoreToStackSlot size interface to tell a whole-value store from a partial one.
Targets without a native lane-masked store keep their shared-slot lanes through a reload plus full-width store at the partial def, so a partial store is not needed there.
The Orignial issue #225054