Repository navigation
Conversation
753a90e to
0a6053c
Compare
|
Hello @xgxanq 👋 Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.
Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description. Frequently asked questionsHow do I add reviewers? This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically. You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using What if there are no comments? If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers. Are any special GitHub settings required to contribute to LLVM? We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details. If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse. Thank you, |
|
@llvm/pr-subscribers-backend-amdgpu Author: xgxanq ChangesRewriteMFMAFormStage recolors an MFMA rewrite candidate's dst/src2 vreg to AGPR, but previously only checked its uses. If the vreg is also redefined by a non-MFMA VALU or feeds a VGPR-only use, the blind recolor creates an illegal AGPR access and the machine verifier aborts. Add isRecolorSafe(), which checks both the vreg's defs and their reaching uses before recoloring. When the vreg is not safe to recolor, keep it in VGPR and bridge it to AGPR with a copy for the MFMA operand instead. Patch is 62.82 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/217396.diff 6 Files Affected:
diff --git a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
index 5816559fcc899..9dccfc3b6275a 100644
--- a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
+++ b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
@@ -2316,40 +2316,69 @@ void GCNSchedStage::modifyRegionSchedule(unsigned RegionIdx,
DAG.Regions[RegionIdx].first = MIOrder.front();
}
-/// Returns true if reaching def \p RD will be in AGPR form after the rewrite
-/// and so needs no bridge copy: a candidate MFMA in \p RewriteSet, an
-/// AV_MOV_*_IMM_PSEUDO, or a copy from a candidate src2 reg in \p CandSrc2Regs.
-/// A non-candidate MFMA stays in VGPR form and still needs a bridge.
-static bool isReachingDefAGPRForm(
- MachineInstr *RD, const SmallPtrSetImpl<MachineInstr *> &RewriteSet,
- const DenseSet<Register> &CandSrc2Regs, const SIInstrInfo &TII) {
- if (TII.isMAI(*RD))
- return RewriteSet.contains(RD);
- if (RD->getOpcode() == AMDGPU::AV_MOV_B32_IMM_PSEUDO ||
- RD->getOpcode() == AMDGPU::AV_MOV_B64_IMM_PSEUDO)
+static bool
+isRewriteCandidateMAI(const MachineInstr *MI, const SIInstrInfo *TII,
+ const SmallPtrSetImpl<MachineInstr *> &RewriteCandsSet) {
+ return TII->isMAI(*MI) && RewriteCandsSet.contains(MI);
+}
+
+static bool canWriteAGPR(const MachineInstr *MI, const SIInstrInfo *TII,
+ const SIRegisterInfo *SRI) {
+ // A writer can write its result into an AGPR lane iff its def operand's
+ // register-class constraint admits AGPRs (AV/agnostic classes do, plain VGPR
+ // classes don't). COPY is a generic opcode with no operand constraint, so
+ // special-case it.
+ if (MI->isCopy())
return true;
- if (RD->isCopy() && CandSrc2Regs.contains(RD->getOperand(1).getReg()))
- return true;
- return false;
+ const MCInstrDesc &Desc = MI->getDesc();
+ if (Desc.getNumDefs() == 0)
+ return false;
+ const TargetRegisterClass *DefRC = TII->getRegClass(Desc, 0);
+ return DefRC && SRI->hasAGPRs(DefRC);
}
-bool RewriteMFMAFormStage::hasUseRequiringVGPR(
- ArrayRef<SlotIndex> Src2ReachingDefs,
- const SmallPtrSetImpl<MachineInstr *> &RewriteSet) {
- for (SlotIndex RDIdx : Src2ReachingDefs) {
- const MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
- SmallVector<MachineOperand *, 8> ReachingUses;
- findReachingUses(RD, DAG.LIS, ReachingUses);
- for (const MachineOperand *UseMO : ReachingUses) {
- const MachineInstr *UseMI = UseMO->getParent();
- if (UseMI->isCopy())
- continue;
- if (TII->isMAI(*UseMI) && RewriteSet.contains(UseMI))
+static bool useAcceptsAGPR(const MachineOperand *Use, const SIInstrInfo *TII,
+ const SIRegisterInfo *SRI) {
+ const MachineInstr *UseMI = Use->getParent();
+ // COPY is a generic opcode with no operand constraint; it can read an AGPR.
+ if (UseMI->isCopy())
+ return true;
+ // The use's static register-class constraint must admit AGPRs.
+ const TargetRegisterClass *UseRC =
+ UseMI->getRegClassConstraint(Use->getOperandNo(), TII, SRI);
+ return UseRC && SRI->hasAGPRs(UseRC);
+}
+
+bool RewriteMFMAFormStage::isRecolorSafe(
+ Register Reg, ArrayRef<MachineOperand *> DstReachingUses,
+ const SmallPtrSetImpl<MachineInstr *> &RewriteCandsSet, bool IsDst) {
+ for (MachineOperand &DefMO : DAG.MRI.def_operands(Reg)) {
+ MachineInstr *DefMI = DefMO.getParent();
+ // A candidate MFMA def is rewritten to AGPR form (it produces the AGPR
+ // result directly), so it does not constrain the recolor.
+ if (isRewriteCandidateMAI(DefMI, TII, RewriteCandsSet))
+ continue;
+ bool CanWriteAGPR = canWriteAGPR(DefMI, TII, SRI);
+ if (!CanWriteAGPR)
+ return false;
+ SmallVector<MachineOperand *, 8> DefReachingUses;
+ findReachingUses(DefMI, DAG.LIS, DefReachingUses);
+ for (MachineOperand *UseMO : DefReachingUses) {
+ // Exempt uses that do not constrain the recolor: for a dst, its own
+ // reaching uses (bridged to VGPR by case2); for a src2, uses that are
+ // candidate MFMAs (they read the AGPR result directly after rewrite).
+ if (IsDst) {
+ if (is_contained(DstReachingUses, UseMO))
+ continue;
+ } else if (isRewriteCandidateMAI(UseMO->getParent(), TII,
+ RewriteCandsSet)) {
continue;
- return true;
+ }
+ if (!useAcceptsAGPR(UseMO, TII, SRI))
+ return false;
}
}
- return false;
+ return true;
}
void RewriteMFMAFormStage::resetRewriteCandsToVGPR(
@@ -2380,12 +2409,6 @@ bool RewriteMFMAFormStage::isRewriteCandidate(MachineInstr *MI) const {
return false;
if (AMDGPU::getAGPRFormOp(MI->getOpcode()) == -1)
return false;
- // Reject candidates whose users force an unavoidable bridge copy.
- Register DstReg = MI->getOperand(0).getReg();
- for (const MachineOperand &Use : DAG.MRI.use_nodbg_operands(DstReg)) {
- if (!TII->isMAI(*Use.getParent()) && !Use.getParent()->isCopy())
- return false;
- }
return true;
}
@@ -2398,15 +2421,11 @@ bool RewriteMFMAFormStage::initHeuristics(
// Collect the candidate group, its members share AGPR-form operands
// post-rewrite, so reaching defs feeding any member don't need bridge copy.
SmallPtrSet<MachineInstr *, 16> RewriteSet;
- DenseSet<Register> CandSrc2Regs;
for (MachineBasicBlock &MBB : MF) {
for (MachineInstr &MI : MBB) {
if (!isRewriteCandidate(&MI))
continue;
RewriteSet.insert(&MI);
- MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
- if (Src2 && Src2->isReg())
- CandSrc2Regs.insert(Src2->getReg());
}
}
@@ -2427,17 +2446,13 @@ bool RewriteMFMAFormStage::initHeuristics(
SmallVector<SlotIndex, 8> Src2ReachingDefs;
findReachingDefs(*Src2, DAG.LIS, Src2ReachingDefs);
- // If src2 has a use that must remain VGPR, it cannot be reclassified to
- // AGPR.
- bool Src2NeedsVGPR = hasUseRequiringVGPR(Src2ReachingDefs, RewriteSet);
- Src2NeedsVGPRCache[&MI] = Src2NeedsVGPR;
-
- for (SlotIndex RDIdx : Src2ReachingDefs) {
- MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
- if (!Src2NeedsVGPR &&
- isReachingDefAGPRForm(RD, RewriteSet, CandSrc2Regs, *TII))
- continue;
- CopyForDef.insert(RD);
+ bool Src2RecolorSafe =
+ isRecolorSafe(Src2->getReg(), {}, RewriteSet, /*IsDst=*/false);
+ if (!Src2RecolorSafe) {
+ for (SlotIndex RDIdx : Src2ReachingDefs) {
+ MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
+ CopyForDef.insert(RD);
+ }
}
}
@@ -2445,33 +2460,39 @@ bool RewriteMFMAFormStage::initHeuristics(
SmallVector<MachineOperand *, 8> DstReachingUses;
findReachingUses(&MI, DAG.LIS, DstReachingUses);
+ bool DstRecolorSafe =
+ isRecolorSafe(Dst.getReg(), DstReachingUses, RewriteSet,
+ /*IsDst=*/true);
for (MachineOperand *RUOp : DstReachingUses) {
MachineInstr *UserMI = RUOp->getParent();
+ bool NeedsAGPRToVGPRCopy = true;
// Group members read the AGPR result directly.
if (TII->isMAI(*UserMI) && RewriteSet.contains(UserMI))
- continue;
+ NeedsAGPRToVGPRCopy = false;
// For any user of the result of the MFMA which is not an MFMA, we
- // insert a copy. For a given register, we will only insert one copy
- // per user block.
- CopyForUse[UserMI->getParent()].insert(RUOp->getReg());
-
- if (TII->isMAI(*UserMI))
+ // record a copy location. For a given register, we only record one
+ // copy per user block.
+ if (NeedsAGPRToVGPRCopy)
+ CopyForUse[UserMI->getParent()].insert(RUOp->getReg());
+
+ // If the dst can be wholly recolored to AGPR, its reaching defs are
+ // reclassified along with it, so no per-def bridge copy is needed.
+ if (DstRecolorSafe)
continue;
-
SmallVector<SlotIndex, 8> DstUsesReachingDefs;
findReachingDefs(*RUOp, DAG.LIS, DstUsesReachingDefs);
for (SlotIndex RDIndex : DstUsesReachingDefs) {
MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
- if (TII->isMAI(*RD))
+ if (TII->isMAI(*RD) && RewriteSet.contains(RD))
continue;
- // For any definition of the user of the MFMA which is not an MFMA,
- // we insert a copy. We do this to transform all the reaching defs
- // of this use to AGPR. By doing this, we can insert a copy from
- // AGPR to VGPR at the user rather than after the MFMA.
+ // Dst cannot be recolored: for any non-MFMA reaching def of this
+ // use, record a copy location. This transforms all the reaching
+ // defs of this use to AGPR so the AGPR-to-VGPR copy lands at the
+ // user rather than after the MFMA.
CopyForDef.insert(RD);
}
}
@@ -2693,17 +2714,21 @@ bool RewriteMFMAFormStage::rewrite(
findReachingDefs(*Src2, DAG.LIS, Src2ReachingDefs);
SmallSetVector<MachineInstr *, 8> Src2DefsReplace;
- // If src2 has a use that must remain VGPR, it cannot be reclassified to
- // AGPR.
- bool Src2NeedsVGPR = Src2NeedsVGPRCache.lookup(MI);
-
- for (SlotIndex RDIndex : Src2ReachingDefs) {
- MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
- if (!Src2NeedsVGPR &&
- isReachingDefAGPRForm(RD, RewriteCandsSet, RewriteSrc2Regs, *TII))
- continue;
-
- Src2DefsReplace.insert(RD);
+ // An already-redefined src2 reuses its mapped reg below, so treat it as
+ // unsafe to recolor and collect the reaching defs that need a bridge.
+ bool Src2AlreadyRedef = RedefMap.contains(Src2Reg);
+ bool Src2RecolorSafe =
+ !Src2AlreadyRedef &&
+ isRecolorSafe(Src2Reg, {}, RewriteCandsSet, /*IsDst=*/false);
+ // src2 cannot be recolored to AGPR: collect its non-candidate reaching
+ // defs to bridge below (candidate MFMAs already produce AGPR directly).
+ if (!Src2RecolorSafe) {
+ for (SlotIndex RDIndex : Src2ReachingDefs) {
+ MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
+ if (isRewriteCandidateMAI(RD, TII, RewriteCandsSet))
+ continue;
+ Src2DefsReplace.insert(RD);
+ }
}
if (!Src2DefsReplace.empty()) {
@@ -2768,34 +2793,47 @@ bool RewriteMFMAFormStage::rewrite(
findReachingUses(MI, DAG.LIS, DstReachingUses);
+ // An already-redefined dst reuses its mapped reg, so treat it as unsafe to
+ // recolor and bridge its reaching defs instead.
+ bool DstAlreadyRedef = RedefMap.contains(DstReg);
+ bool DstRecolorSafe =
+ !DstAlreadyRedef &&
+ isRecolorSafe(DstReg, DstReachingUses, RewriteCandsSet, /*IsDst=*/true);
for (MachineOperand *RUOp : DstReachingUses) {
MachineInstr *UserMI = RUOp->getParent();
- // Group members read the AGPR result directly.
- if (TII->isMAI(*UserMI) && RewriteCandsSet.contains(UserMI))
- continue;
-
- // If there is a non mai reaching use, then we need a copy.
- if (find(DstReachingUseCopies, RUOp) == DstReachingUseCopies.end())
+ // A group-member MFMA reads the AGPR result directly; any other user can
+ // only avoid a bridge if it accepts an AGPR operand.
+ bool CanReadAGPR = TII->isMAI(*UserMI) ? RewriteCandsSet.contains(UserMI)
+ : useAcceptsAGPR(RUOp, TII, SRI);
+ if (!CanReadAGPR &&
+ find(DstReachingUseCopies, RUOp) == DstReachingUseCopies.end())
DstReachingUseCopies.push_back(RUOp);
-
- // Non-rewritten MAI: its defs aren't being reclassified.
- if (TII->isMAI(*UserMI))
+ // If the dst is wholly recolored to AGPR, its reaching defs are
+ // reclassified along with it, so none of them need a bridge copy.
+ if (DstRecolorSafe)
continue;
-
SmallVector<SlotIndex, 8> DstUsesReachingDefs;
findReachingDefs(*RUOp, DAG.LIS, DstUsesReachingDefs);
for (SlotIndex RDIndex : DstUsesReachingDefs) {
MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex);
- if (TII->isMAI(*RD))
+ if (isRewriteCandidateMAI(RD, TII, RewriteCandsSet))
continue;
-
- // If there is a non mai reaching def of this reaching use, then we will
- // need a copy.
+ // A non-candidate reaching def must be bridged to VGPR; record it once
+ // (dedup against DstUseDefsReplace).
if (find(DstUseDefsReplace, RD) == DstUseDefsReplace.end())
DstUseDefsReplace.push_back(RD);
}
}
+ // The dst has no reaching uses and cannot be recolored: create a fresh
+ // reg to carry the AGPR-form value and record the mapping, leaving the
+ // original dst reg in VGPR form.
+ if (DstReachingUses.empty() && !DstRecolorSafe) {
+ const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(DstReg);
+ const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC);
+ MappedReg = DAG.MRI.createVirtualRegister(VGPRRC);
+ RedefMap[DstReg] = MappedReg;
+ }
if (!DstUseDefsReplace.empty()) {
auto RI = RedefMap.find(DstReg);
diff --git a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h
index 2059f4e6479ff..f922b694dd6c2 100644
--- a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h
+++ b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.h
@@ -443,10 +443,6 @@ class RewriteMFMAFormStage : public GCNSchedStage {
const SIInstrInfo *TII;
const SIRegisterInfo *SRI;
- /// Per-candidate cache of the src2 "needs VGPR" decision, computed once
- /// and reused on-demand.
- DenseMap<const MachineInstr *, bool> Src2NeedsVGPRCache;
-
/// Do a speculative rewrite and collect copy locations. The speculative
/// rewrite allows us to calculate the RP of the code after the rewrite, and
/// the copy locations allow us to calculate the total cost of copies required
@@ -486,11 +482,12 @@ class RewriteMFMAFormStage : public GCNSchedStage {
void findReachingUses(const MachineInstr *DefMI, LiveIntervals *LIS,
SmallVectorImpl<MachineOperand *> &ReachingUses);
- /// Returns true if the src2 register with reaching defs \p Src2ReachingDefs
- /// has a use other than a group MFMA (in \p RewriteSet) or a copy, which
- /// would keep it in VGPR form rather than let it be reclassified to AGPR.
- bool hasUseRequiringVGPR(ArrayRef<SlotIndex> Src2ReachingDefs,
- const SmallPtrSetImpl<MachineInstr *> &RewriteSet);
+ /// Returns true if \p Reg (a rewrite candidate's dst or src2, selected by
+ /// \p IsDst) can be wholly reclassified to AGPR without creating an illegal
+ /// VALU AGPR access.
+ bool isRecolorSafe(Register Reg, ArrayRef<MachineOperand *> DstReachingUses,
+ const SmallPtrSetImpl<MachineInstr *> &RewriteCandsSet,
+ bool IsDst);
public:
bool initGCNSchedStage() override;
diff --git a/llvm/test/CodeGen/AMDGPU/mfma-no-multiple-copies.mir b/llvm/test/CodeGen/AMDGPU/mfma-no-multiple-copies.mir
index c7ae0a2c2ef93..de9c11753db37 100644
--- a/llvm/test/CodeGen/AMDGPU/mfma-no-multiple-copies.mir
+++ b/llvm/test/CodeGen/AMDGPU/mfma-no-multiple-copies.mir
@@ -42,10 +42,11 @@ body: |
; CHECK-NEXT: bb.2:
; CHECK-NEXT: KILL %p0, %p1, %p2, %p3, %p4, %p5, %p6, %p7
; CHECK-NEXT: %m4:areg_128_align2 = V_MFMA_F32_16X16X32_F16_e64 undef %s0:vreg_128_align2, undef %s1:vreg_128_align2, %m2, 0, 0, 0, implicit $mode, implicit $exec
- ; CHECK-NEXT: [[COPY1:%[0-9]+]]:vreg_128_align2 = COPY %m4
- ; CHECK-NEXT: %out1:vreg_128_align2 = V_MFMA_F32_16X16X32_F16_vgprcd_e64 undef %s0:vreg_128_align2, undef %s1:vreg_128_align2, [[COPY1]], 0, 0, 0, implicit $mode, implicit $exec
- ; CHECK-NEXT: %out2:vreg_128_align2 = V_MFMA_F32_16X16X32_F16_vgprcd_e64 undef %s1:vreg_128_align2, undef %s0:vreg_128_align2, [[COPY1]], 0, 0, 0, implicit $mode, implicit $exec
- ; CHECK-NEXT: S_ENDPGM 0, implicit %out1, implicit %out2
+ ; CHECK-NEXT: %out1:areg_128_align2 = V_MFMA_F32_16X16X32_F16_e64 undef %s0:vreg_128_align2, undef %s1:vreg_128_align2, %m4, 0, 0, 0, implicit $mode, implicit $exec
+ ; CHECK-NEXT: %out2:areg_128_align2 = V_MFMA_F32_16X16X32_F16_e64 undef %s1:vreg_128_align2, undef %s0:vreg_128_align2, %m4, 0, 0, 0, implicit $mode, implicit $exec
+ ; CHECK-NEXT: [[COPY1:%[0-9]+]]:vreg_128_align2 = COPY %out1
+ ; CHECK-NEXT: [[COPY2:%[0-9]+]]:vreg_128_align2 = COPY %out2
+ ; CHECK-NEXT: S_ENDPGM 0, implicit [[COPY1]], implicit [[COPY2]]
bb.0:
successors: %bb.1(0x80000000)
%p0:vreg_1024 = IMPLICIT_DEF
diff --git a/llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-fix-recolor.mir b/llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-fix-recolor.mir
new file mode 100644
index 0000000000000..cc53c87fd6299
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-fix-recolor.mir
@@ -0,0 +1,87 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py UTC_ARGS: --version 6
+# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -run-pass=machine-scheduler \
+# RUN: -amdgpu-disable-rewrite-mfma-form-sched-stage=false \
+# RUN: -verify-machineinstrs -o - %s | FileCheck %s
+
+# Correctness test for the RewriteMFMAFormStage def-side recolor guard. The loop
+# MFMA's src2 %acc is partially redefined in the epilogue (%acc.sub0) and read by
+# a VGPR-only DS_READ_B32. isRecolorSafe scans the reaching uses of %acc's defs,
+# sees that read, and keeps %acc in VGPR -- bridging it to AGPR with a copy for
+# src2 instead of recoloring the whole vreg (which would abort with
+# "AReg_64_Align2.sub0 cannot be used for VGPR_32 operands").
+
+--- |
+ define amdgpu_kernel void @mfma_fix_recolor() #0 {
+ ret void
+ }
+
+ attributes #0 = { "amdgpu-flat-work-group-size"="1,256" }
+...
+---
+name: mfma_fix_recolor
+tracksRegLiveness: true
+body: |
+ ; CHECK-LABEL: name: mfma_fix_recolor
+ ; CHECK: bb.0:
+ ; CHECK-NEXT: successors: %bb.1(0x80000000)
+ ; CHECK-NEXT: liveins: $vgpr0_vgpr1, $vgpr2_vgpr3, $sgpr0
+ ; CHECK-NEXT: {{ $}}
+ ; CHECK-NEXT: %s0:vreg_64_align2 = COPY $vgpr0_vgpr1
+ ; CHECK-NEXT: %s1:vreg_64_align2 = COPY $vgpr2_vgpr3
+ ; CHECK-NEXT: %cnt:sgpr_32 = COPY $sgpr0
+ ; CHECK-NEXT: %acc:vreg_64_align2 = AV_MOV_B64_IMM_PSEUDO 0, implicit $exec
+ ; CHECK-NEXT: [[COPY:%[0-9]+]]:areg_64_align2 = COPY %acc
+ ; CHECK-NEXT: {{ $}}
+ ; CHECK-NEXT: bb.1:
+ ; CHECK-NEXT: successors: %bb.1(0x40000000), %bb.2(0x40000000)
+ ; CHECK-NEXT: {{ $}}
+ ; CHECK-NEXT: dead %mdst:areg_64_align2 = V_MFMA_F64_4X4X4F64_e64 %s0, %s1, [[COPY]], 0, 0, 0, implicit $mode, implicit $exec
+ ; CHECK-NEXT: %cnt:sgpr_32 = S_SUB_I32 %cnt, 1, implicit-def $scc
+ ; CHECK-NEXT: S_CBRANCH_SCC1 %bb.1, implicit $scc
+ ; CHECK-NEXT: S_BRANCH %bb.2
+ ; CHECK-NEXT: {{ $}}
+ ; CHECK-NEXT: bb.2:
+ ; CHECK-NEXT: %acc.sub0:vreg_64_align2 = AV_MOV_B32_IMM_PSEUDO 7, implicit $exec
+ ; CHECK-NEXT: dead %conn:vreg_64_align2 = COPY %acc
+ ; CHECK-NEXT: %ld:vgpr_32 = DS_READ_B32_gfx9 %acc.sub0, 0, 0, implicit $exec :: (load (s32), addrspace 3)
+ ; CHECK-NEXT: [[DEF:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF1:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF2:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF3:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF4:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF5:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF6:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF7:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: [[DEF8:%[0-9]+]]:vreg_1024 = IMPLICIT_DEF
+ ; CHECK-NEXT: S_ENDPGM 0, implicit %ld, implicit [[DEF]], implicit [[DEF1]], implicit [[DEF2]], implicit [[DEF3]], implicit [[DEF4]], implicit [[DEF5]], implicit [[DEF6]], implicit [[DEF7]], implicit [[DEF8]]
+ bb.0:
+ successors: %bb.1
+ liveins: $vgpr0_vgpr1, $vgpr2_vgpr3, $sgpr0
+
+ %s0:vreg_64_align2 = COPY $vgpr0_vgpr1
+ %s1:vreg_64_align2 = COPY $vgpr2_vgpr3
+ %cnt:sgpr_32 = COPY $sgpr0
+ %p0:vreg_1024 = IMPLICIT_DEF
+ %p1:vreg_1024 = IMPLICIT_...
[truncated]
|
|
✅ With the latest revision this PR passed the C/C++ code formatter. |
| // register-class constraint admits AGPRs (AV/agnostic classes do, plain VGPR | ||
| // classes don't). COPY is a generic opcode with no operand constraint, so | ||
| // special-case it. | ||
| if (MI->isCopy()) |
There was a problem hiding this comment.
Maybe should generalize this to the unknown register class, which would cover all the pseudos. Though there is some risk there. In particular I'm concerned about future SSAification where REG_SEQUENCE may appear here
There was a problem hiding this comment.
REG_SEQUENCE, INSERT_SUBREG and this class of instructions have a DefRC of nullptr; nullptr falls into DefRC && hasAGPRs → false (conservative — treated as "cannot write AGPR", which prevents recoloring this whole reg to AGPR). This is reasonable.
btw, besides this obvious code‑design flaw we just hit, there are also other bugs: Multiple connected components in live interval and Virtual register defs don't dominate all uses. So I will first fix this major standalone design hole and continue addressing the other two categories of bugs afterwards. Of course, I will also follow‑up and refine this area further if additional improvements are needed.
| if (UseMI->isCopy()) | ||
| continue; | ||
| if (TII->isMAI(*UseMI) && RewriteSet.contains(UseMI)) | ||
| static bool useAcceptsAGPR(const MachineOperand *Use, const SIInstrInfo *TII, |
There was a problem hiding this comment.
This is unnecessarily special casing. You should check if the operand class is compatible with the class you want, not that it's specifically AGPR
There was a problem hiding this comment.
In the prior code logic, the VGPR for the dst and src2 operands of an mfma instruction could be directly converted to AGPR via DAG.MRI.setRegClass. However, setRegClass does not only affect the reaching‑def and reaching‑use chains associated with the mfma instruction. This is not merely a flow‑sensitive problem.
For a destination register, to determine whether it can be recolored from the VGPR register‑class to AGPR directly without creating a mapped register, the most direct criterion is: every definition obtained via DAG.MRI.def_operands for this dst must accept the AGPR form, and each ReachingUse of such definitions must either natively accept the AGPR form(useAcceptsAGPR ), or be eligible for the copy‑insertion handling under case2.
There was a problem hiding this comment.
but this should be expressed as check compatibility with the class of the instruction you want to emit, not hardcoding AGPR checks
There was a problem hiding this comment.
but this should be expressed as check compatibility with the class of the instruction you want to emit, not hardcoding AGPR checks
ok
| for (MachineOperand &DefMO : DAG.MRI.def_operands(Reg)) { | ||
| MachineInstr *DefMI = DefMO.getParent(); |
There was a problem hiding this comment.
def_instructions? Try to avoid getParent on MachineOperands
| MachineInstr *UserMI = RUOp->getParent(); | ||
| bool NeedsAGPRToVGPRCopy = true; | ||
| // Group members read the AGPR result directly. | ||
| if (TII->isMAI(*UserMI) && RewriteSet.contains(UserMI)) |
There was a problem hiding this comment.
Use isRewriteCandidateMAI
| for (SlotIndex RDIndex : DstUsesReachingDefs) { | ||
| MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIndex); | ||
| if (TII->isMAI(*RD)) | ||
| if (TII->isMAI(*RD) && RewriteSet.contains(RD)) |
| return UseRC && SRI->hasAGPRs(UseRC); | ||
| } | ||
|
|
||
| bool RewriteMFMAFormStage::isRecolorSafe( |
There was a problem hiding this comment.
nit: for the sake of API clarity, can you make one version of this function for each operand type (isSrc2RecolorSafe/isDstRecolorSafe), both of which can call this "operand-generic" function.
The src2 version also never uses DstReachingUses and AFAIU there will always be at least one reaching use for dst so you don't really need IsDst: just check DstReachingUses.empty() in its place in the generic implementation.
There was a problem hiding this comment.
I don’t think we can remove the IsDst flag. DstReachingUses.empty() may still hold true even when IsDst is true, for instance for a dead destination definition with no reaching‑uses at all. So we cannot rely solely on DstReachingUses.empty() to distinguish between source‑operand and destination‑operand paths.
|
Hi! This comment was generated using fuzz-fill, a new tool we're building to help improve LLVM test coverage by spotting lines introduced in a PR that don't yet appear to be exercised by the full test suite, including any tests added in this PR. Looking at PR head It looks like the body of that |
I have added a test |
RewriteMFMAFormStage recolors an MFMA rewrite candidate's dst/src2 vreg to AGPR, but previously only checked its uses. If the vreg is also redefined by a non-MFMA VALU or feeds a VGPR-only use, the blind recolor creates an illegal AGPR access and the machine verifier aborts. Add isRecolorSafe(), which checks both the vreg's defs and their reaching uses before recoloring. When the vreg is not safe to recolor, keep it in VGPR and bridge it to AGPR with a copy for the MFMA operand instead.
Walk def_instructions instead of def_operands so a def is visited once per instruction (dropping the getParent hop and avoiding duplicate findReachingUses work when one instr partially defs multiple subregs), and fold the two remaining raw isMAI() && RewriteSet.contains() checks into the existing isRewriteCandidateMAI helper. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Factor the duplicated "does this operand's RC admit the AGPR form we emit" test out of canWriteAGPR and useAcceptsAGPR into a shared operandAcceptsAGPRForm helper. While here, fix a verifier error in RewriteMFMAFormStage::rewrite(): an unsafe, non-recolorable MFMA dst with no reaching use was left without a full-lane def after its MFMA def moved to a mapped AGPR reg. Bridge the AGPR-form result back into the original VGPR dst with a COPY. Co-Authored-By: Claude Opus 4.7 <[email protected]>
A recolor-unsafe candidate MFMA dst that has reaching uses but no non-candidate reaching def to bridge (DstUseDefsReplace empty) was never recorded in the redef map, so the final reclassification recolored the original VGPR dst to AGPR instead of a fresh carrier. Record the mapping for this case so the original dst stays VGPR and only the mapped AGPR carrier is reclassified. Adds a dedicated test and updates sched_mfma_rewrite_copies.mir to store the correct value. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Switch the RUN lines to the -mtriple=amdgpuX.Y-amd-amdhsa form (mcpu folded into the triple) to match the sibling rewrite-mfma-form tests. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Reform canWriteAGPR/useAcceptsAGPR to test AGPR legality via MachineInstr::getRegClassConstraintEffect against the target AGPR class, mirroring the def/use handling in AMDGPURewriteAGPRCopyMFMA. This folds in each operand's subregister index and correctly treats unconstrained defs (e.g. IMPLICIT_DEF) as AGPR-placeable, replacing the over-conservative operandAcceptsAGPRForm helper (now removed). Regenerate the affected flag-test CHECKs. Co-Authored-By: Claude Opus 4.7 <[email protected]>
99c7e74 to
b655979
Compare
| DefOpIdx, RegAGPRClass, TII, SRI) != nullptr; | ||
| } | ||
|
|
||
| static bool useAcceptsAGPR(const MachineOperand *Use, |
There was a problem hiding this comment.
This should be in terms of User, not use
There was a problem hiding this comment.
useAcceptsAGPR → userAcceptsAGPR?
There was a problem hiding this comment.
Yes, and pass in the instruction not the operand, and only use instruction iterators
| static bool canWriteAGPR(const MachineInstr *MI, Register Reg, | ||
| const TargetRegisterClass *RegAGPRClass, | ||
| const SIInstrInfo *TII, const SIRegisterInfo *SRI) { | ||
| if (MI->getDesc().getNumDefs() == 0 || !RegAGPRClass) |
There was a problem hiding this comment.
Weird null check, I'd expect any class argument to be non-null
| if (MI->getDesc().getNumDefs() == 0 || !RegAGPRClass) | ||
| return false; | ||
| int DefOpIdx = | ||
| MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr, false, false); |
| return false; | ||
| int DefOpIdx = | ||
| MI->findRegisterDefOperandIdx(Reg, /*TRI=*/nullptr, false, false); | ||
| return DefOpIdx >= 0 && MI->getRegClassConstraintEffect( |
There was a problem hiding this comment.
Don't understand the special case of DefOpIdx
There was a problem hiding this comment.
The def-operand special case via findRegisterDefOperandIdx is actually wrong: for a tied operand, both the def and the use need to be checked. I previously considered the tied-operand case of a sub-register overwrite. However, in the current design that case needs to be handled by other code, not written this way here.
This bug fix is fully ready. I prefer landing this PR first and handling follow-up work in separate PRs. |
…-mfma tests The recolor-legality rework let the MFMA users (%out1/%out2) in mfma-no-multiple-copies themselves be recolored to AGPR form, so they read the accumulator's AGPR result directly and no AGPR->VGPR copy was emitted -- the test passed but no longer exercised the single-shared-copy dedup path it was written for. Feed %m4 into the users through a VGPR-only src0 of the non-candidate _e64 form (which has no AGPR form and so is not a rewrite candidate). The %m4 chain still recolors to AGPR, but both same-block users now require a bridge and share a single AGPR->VGPR copy, restoring the coverage. Also document, in fix-recolor.mir, why the dead full-register COPY of %acc is needed: bb.2 only redefines sub0, so without the full-register use the verifier reports "Multiple connected components in live interval". Co-Authored-By: Claude Opus 4.7 <[email protected]>
I think the ask about expressing the safety check in terms of users is a reasonable one. It isn't just cosmetic either. The queries the check makes are users-related, not uses, so we'll have a semantic gap and potentially some unnecessary overhead. It also sidesteps the hardcoded argument position in the implementation which is technically incorrect (although doesn't materialize in any real problem atm, as far as I can tell at least). That's my read anyway, maybe @arsenm has more arguments. |
Most of Matt's review comments are reasonable and logically sound, and I've made the corresponding corrections. I can understand what Matt is saying. @kurapov-peter Matt also encountered and resolved the recolor issue when designing |
Thanks for trying it out. I don't think the single-argument isRecolorSafe(Reg, RewriteCandsSet) can be made equivalent, though, at least not the way the exemptions are currently defined. IsDst isn't a property of Reg — it encodes the role Reg plays at the call site: whether we're recoloring it as a candidate's dst or as its src2. The same accumulator vreg can be both (the dst of one candidate MFMA and the src2 of the next in an accumulation chain), and the two roles exempt genuinely different reaching-uses:
A function that only sees Reg can't tell the roles apart, so it can only give one answer for a shared accumulator — whereas the two paths legitimately need different ones. That's why the IsDst flag is load-bearing rather than incidental. |
|
I think this needs to address the uses vs users question and a ready-for-merge patch to subregisters problem for this to go in. The former will help this be maintainable, the latter - resolve the regression this introduces (I understand this is just uncovered behavior by this patch, but it creates the problem nonetheless). The rest is nice-to-have and isn't blocking IMO. |
Thanks very much. |
|
Hi @xgxanq,
For #2, I think it depends whether the PR is useful in its current state. I don't have a personal opinion here. Cheers, |
I believe something like this should address 1.: And for 2. I suggest a temporary workaround which could be committed with this patch and removed when a proper fix for sub-reg issues is merged: Note. This rejects mfma convertion in ~4 LIT tests, but I believe we can live with that some time. UPD. Updated sub-regs workaround to handle src2 as well. @kurapov-peter @xgxanq WDYT ? |
| const TargetRegisterClass *DstRC = DAG.MRI.getRegClass(DstReg); | ||
| const TargetRegisterClass *VGPRRC = SRI->getEquivalentVGPRClass(DstRC); | ||
| MappedReg = DAG.MRI.createVirtualRegister(VGPRRC); | ||
| RedefMap[DstReg] = MappedReg; |
There was a problem hiding this comment.
can replace the assert above with insert + llvm_unreachable
|
|
||
| // Track the mapping of the original register to the new register. | ||
| MappedReg = DAG.MRI.createVirtualRegister(VGPRRC); | ||
| RedefMap[DstReg] = MappedReg; |
| const SmallPtrSetImpl<MachineInstr *> &RewriteCandsSet, bool IsDst) { | ||
| const TargetRegisterClass *RegAGPRClass = | ||
| SRI->getEquivalentAGPRClass(DAG.MRI.getRegClass(Reg)); | ||
| for (MachineInstr &DefMI : DAG.MRI.def_instructions(Reg)) { |
There was a problem hiding this comment.
I don't understand why this is only looking at defs, you also need to account for the direct uses? I'd expect this to be reg_instructions, look at the uses and defs on each referencing instruction
There was a problem hiding this comment.
The uses are checked, just not where it looks — the def loop calls findReachingUses per def (2389) and runs userAcceptsAGPR on each reaching use (2390-2403), so it's really "defs,plus the reaching uses of each def" rather than defs only. Agreed it's an awkward structure though. I'll restructure it the way romanovvlad suggested: a plain def loop for canWriteAGPR, then a separate use_nodbg_instructions(Reg) loop for userAcceptsAGPR — which also drops the O(defs×uses) nesting. One thing I'll keep: the exemptions are deliberate,not accidental — a dst's own reaching uses are bridged to VGPR by case2, and a use fed only by candidate MFMAs reads the AGPR result directly, so neither constrains the recolor.
| @@ -2803,35 +2816,92 @@ bool RewriteMFMAFormStage::rewrite( | |||
|
|
|||
| findReachingUses(MI, DAG.LIS, DstReachingUses); | |||
There was a problem hiding this comment.
There's another bug in findReachingUses where it assumes operand 0 is the def, which won't hold for the ds_write2* cases
There was a problem hiding this comment.
You're right that the getOperand(0) assumption is unsound. Today it happens to be safe: findReachingUses is only ever called with a rewrite-candidate MFMA (2485, 2817) or with an instruction from def_instructions(Reg) (2389), where operand 0 is the def. A ds_write2* has an empty def list ((outs) / NORET), so def_instructions(Reg) never yields one and it isn't reachable here yet — but it absolutely becomes reachable once isRecolorSafe switches to walking reg_instructions (which includes non-def users like ds_write2*). I'll fix findReachingUses to take the def register/operand explicitly rather than assuming index 0, as a prerequisite for that refactor.
| SRI) != nullptr; | ||
| } | ||
|
|
||
| bool RewriteMFMAFormStage::isRecolorSafe( |
There was a problem hiding this comment.
This is pretty algorithmically expensive and is now called more times without any caching.
O(defs x uses x CFG-walk), is now called for both src2 and dst of every candidate in both initHeuristics and rewrite()
| ? RewriteCandsSet.contains(UserMI) | ||
| : DstRecolorSafe && | ||
| userAcceptsAGPR(UserMI, DstReg, DstAGPRClass, TII, SRI); | ||
| if (!CanReadAGPR && |
There was a problem hiding this comment.
Do these skipped cases leave orphaned RedefMap[DstReg] entries?
There was a problem hiding this comment.
No literally-orphaned entries. RewriteRegs.insert(DstReg) (line 2985) and ReplaceMap[DstReg].insert(Dst) (line 2990) both run unconditionally at the end of the dst block — there's no continue/return between the RedefMap[DstReg] insertions (2873 / 2902 / 2916) and those two lines. So whenever a RedefMap[DstReg] entry is created, DstReg is guaranteed to be in both RewriteRegs and ReplaceMap[DstReg], and the entry is consumed by both the operand-redirect loop (3043) and the reclassify loop (3057). Nothing is left dangling.
| if (RI != RedefMap.end()) { | ||
| MappedReg = RI->second; | ||
| } else { | ||
| assert(!ReachingDefCopyMap.contains(DstReg)); |
There was a problem hiding this comment.
This same sequence is repeated below in the if (!DstUseDefsReplace.empty()) block
Thanks for the detailed review and especially for the reference code — both were very helpful. I've applied #1 and have a data point + a narrower proposal for #2.
Adopted your reference isRecolorSafe (two loops: def-side canWriteAGPR, then use_nodbg_instructions with the candidate-user / DstReachingUses / all-reaching-defs-are-candidates One note for the record: dropping IsDst is not strictly NFC. On the dst path the old code did not exempt candidate-MFMA users that aren't in DstReachingUses; it ran them through
|
Rewrite isRecolorSafe into two independent passes: a def-side check that every non-candidate def of the register can write the AGPR form, and a user-side check over use_nodbg_instructions(). This removes the previous O(defs x uses x CFG-walk) nested walk (now O(defs + uses x CFG-walk)) and drops the IsDst parameter by unifying the exemptions (candidate-MFMA users, the dst's own reaching uses bridged by case2, and uses whose reaching defs are all candidate MFMAs). Dropping IsDst is not strictly NFC: on the dst path the old code ran a candidate MFMA user that is not among DstReachingUses through userAcceptsAGPR on its still VGPR (vgprcd) form, reporting the dst unsafe. That is a false negative -- the sibling candidate is rewritten to AGPR form and reads AGPR natively -- so the unified version correctly treats it as safe, avoiding an unnecessary mapped-reg path. Also pass the defining register explicitly to findReachingUses instead of assuming operand 0 is the def, so it is correct for instructions that define a register other than their operand 0. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…alue
The whole-register reaching-def/recolor logic in RewriteMFMAFormStage does not
yet handle a candidate MFMA whose src2 (accumulator) reads a value produced by a
non-undef subreg def that overwrote a previously full register value (a
mid-chain read-modify-write). Recoloring such a register produces invalid live
intervals ("Multiple connected components in live interval").
As a temporary workaround until subreg-aware reaching-def handling lands, exclude
these MFMAs from rewriting. The check is tied to the specific value src2 reads
(via its reaching defs, so it is correct across basic blocks and PHIs): benign
accumulators that are merely built up lane-by-lane before the MFMA, and subreg
overwrites that happen only after the MFMA reads the register, are not excluded,
so the common AGPR-form conversion is unaffected.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Resolve CHECK conflict in rewrite-mfma-single-exit-copy.ll by regenerating golden output with update_llc_test_checks.py against merged llc (upstream 'Compute LiveIntervals before TwoAddressInstructions' + our recolor guard both affect register allocation). GCNSchedStrategy.cpp/.h auto-merged clean. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
🪟 Windows x64 Test Results
✅ The build succeeded and all tests passed. |
…MFMAs The narrow Src2ReadsSplicedValue check (only src2 reads whose reaching value came from a full-register overwrite) does not cover an MFMA whose src2 is an earlier MFMA's mapped dst built lane-by-lane. Such chains still hit 'empty-use dst unexpectedly already mapped' in rewrite() -- e.g. the coexec persistent-mfma kernel and coexec-rewrite-mfma.ll. Temporarily widen the workaround to romanovvlad's WrittenPiecewise form: reject any candidate whose dst or src2 has a non-undef subreg def anywhere. This is the only splice-family predicate that covers the src2<-earlier-dst chain, at the cost of reverting benign lane-by-lane accumulators (coexec kernel: 0/30 MFMAs migrate to AGPR). Tracked test CHECKs regenerated/updated to the widened behavior; the AGPR-form assertions in coexec-rewrite-mfma.ll are flipped with a FIXME to restore once the subreg-aware / forward-exclusion fix lands. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extract the repeated 'find RedefMap entry, else create a VGPR-class mapped reg' sequence (three sites: src2 bridge, unsafe dst without/with a def to bridge) into a getOrCreateMappedReg lambda using try_emplace (arsenm nit llvm#5). Also harden the empty-use dst path (arsenm nit llvm#6): the invariant that such a dst is never already mapped was only an assert, so in release builds a stale mapping would be silently overwritten and miscompile. Enforce it with try_emplace().second + llvm_unreachable so it traps in release too. findReachingDefs memoization (nit llvm#7) is deferred: its calls span the initHeuristics and rewrite phases and rewrite() mutates LIS mid-pass, so a cross-call cache would go stale; the broad subreg WA also no longer calls it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
RewriteMFMAFormStage recolors an MFMA rewrite candidate's dst/src2 vreg to AGPR, but previously only checked its uses. If the vreg is also redefined by a non-MFMA VALU or feeds a VGPR-only use, the blind recolor creates an illegal AGPR access and the machine verifier aborts.
Add isRecolorSafe(), which checks both the vreg's defs and their reaching uses before recoloring. When the vreg is not safe to recolor, keep it in VGPR and bridge it to AGPR with a copy for the MFMA operand instead.
Fixes #214124.