[llvm] [AMDGPU] Port MFMA-form rewrite refinements onto shared copy-plan analysis (PR #210703)

via llvm-commits llvm-commits at lists.llvm.org
Mon Jul 20 05:37:28 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-amdgpu

Author: xgxanq

<details>
<summary>Changes</summary>

 Extend the RewriteMFMAFormStage safe-guard and bridge-copy logic on top of
    the analyzeCopyPoints copy-plan refactor:

     - Safe-guard: add a post-dominator tree and isSrc2MergePoint(), and extend
       hasSrc2BridgeConflict with a joint-lane coverage check plus a fast path
       for parallel MAI/non-MAI def pairs, so more unsafe src2 rewrites are
       excluded (still propagating forward and backward, no IR mutated).

     - src2 bridge: factor def classification into computeSrc2BridgePlan /
       classifySrc2Bridge, and split emission into a merged full-width COPY
       before the MFMA vs one COPY per def-BB (narrowed to a sub-reg COPY when
       the defs jointly cover the range).

     - dst bridge: add getCopyGroups() to group Case 2/3 dst uses by subreg and
       emit the narrowest legal VGPR COPY per group.

     - Occupancy: override shouldRevertScheduling to revert when archVGPR/AGPR
       pressure stays over the shared physical limit and worse than before, and
       refresh live-ins/pressure for all regions after LIS reanalyze().

---

Patch is 193.14 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/210703.diff


11 Files Affected:

- (modified) llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp (+954-279) 
- (modified) llvm/lib/Target/AMDGPU/GCNSchedStrategy.h (+171-5) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-pressure-refresh.mir (+101) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-safe-guard.mir (+1053) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-src2-merge-point-both-rewritten.mir (+171) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-src2-mfma-plus-subreg-rewrite.mir (+134) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-src2-mixed-agpr-covered-perbb.mir (+144) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-src2-parallel-fulldef-liveinterval-split.mir (+128) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-src2-parallel-fullwidth-merged.mir (+126) 
- (added) llvm/test/CodeGen/AMDGPU/rewrite-mfma-form-src2-seq-bypass-dominance-gap.mir (+115) 
- (modified) llvm/test/CodeGen/AMDGPU/sched_mfma_rewrite_copies.mir (+110-63) 


``````````diff
diff --git a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
index a4f854beaeebe..e3a302501aca8 100644
--- a/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
+++ b/llvm/lib/Target/AMDGPU/GCNSchedStrategy.cpp
@@ -35,6 +35,7 @@
 #include "llvm/CodeGen/MachineBasicBlock.h"
 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
+#include "llvm/CodeGen/MachineDominators.h"
 #include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/CodeGen/RegisterClassInfo.h"
 #include "llvm/CodeGen/Rematerializer.h"
@@ -1315,48 +1316,108 @@ bool GCNSchedStage::initGCNSchedStage() {
   return true;
 }
 
-void RewriteMFMAFormStage::findReachingDefs(
-    MachineOperand &UseMO, LiveIntervals *LIS,
-    SmallVectorImpl<SlotIndex> &DefIdxs) {
-  MachineInstr *UseMI = UseMO.getParent();
-  LiveInterval &UseLI = LIS->getInterval(UseMO.getReg());
-  VNInfo *VNI = UseLI.getVNInfoAt(LIS->getInstructionIndex(*UseMI));
+static void collectReachingDefsInRange(const LiveRange &QR,
+                                       MachineBasicBlock *UseMBB,
+                                       SlotIndex UseIdx,
+                                       const LiveIntervals *LIS,
+                                       SmallSet<SlotIndex, 8> &ResultSet) {
+  const VNInfo *VNI = QR.getVNInfoAt(UseIdx);
+  if (!VNI)
+    return;
 
-  // If the def is not a PHI, then it must be the only reaching def.
   if (!VNI->isPHIDef()) {
-    DefIdxs.push_back(VNI->def);
+    ResultSet.insert(VNI->def);
     return;
   }
 
-  SmallPtrSet<MachineBasicBlock *, 8> Visited = {UseMI->getParent()};
+  SmallPtrSet<MachineBasicBlock *, 8> Visited;
   SmallVector<MachineBasicBlock *, 8> Worklist;
-
-  // Mark the predecessor blocks for traversal
-  for (MachineBasicBlock *PredMBB : UseMI->getParent()->predecessors()) {
-    Worklist.push_back(PredMBB);
-    Visited.insert(PredMBB);
-  }
+  for (MachineBasicBlock *PredMBB : UseMBB->predecessors())
+    if (Visited.insert(PredMBB).second)
+      Worklist.push_back(PredMBB);
 
   while (!Worklist.empty()) {
     MachineBasicBlock *CurrMBB = Worklist.pop_back_val();
+    SlotIndex CurrMBBEnd = LIS->getMBBEndIdx(CurrMBB).getPrevSlot();
+    const VNInfo *PredVNI = QR.getVNInfoAt(CurrMBBEnd);
+    if (!PredVNI)
+      continue;
 
-    SlotIndex CurrMBBEnd = LIS->getMBBEndIdx(CurrMBB);
-    VNInfo *VNI = UseLI.getVNInfoAt(CurrMBBEnd.getPrevSlot());
-
-    MachineBasicBlock *DefMBB = LIS->getMBBFromIndex(VNI->def);
-
-    // If there is a def in this block, then add it to the list. This is the
-    // reaching def of this path.
-    if (!VNI->isPHIDef()) {
-      DefIdxs.push_back(VNI->def);
+    if (!PredVNI->isPHIDef()) {
+      // Skip self-referential defs (src2 == dst): the MFMA's own result must
+      // not appear as a reaching def of its own src2 operand.
+      if (SlotIndex::isSameInstr(PredVNI->def, UseIdx))
+        continue;
+      ResultSet.insert(PredVNI->def);
       continue;
     }
 
-    for (MachineBasicBlock *PredMBB : DefMBB->predecessors()) {
+    MachineBasicBlock *DefMBB = LIS->getMBBFromIndex(PredVNI->def);
+    for (MachineBasicBlock *PredMBB : DefMBB->predecessors())
       if (Visited.insert(PredMBB).second)
         Worklist.push_back(PredMBB);
+  }
+}
+
+void RewriteMFMAFormStage::findReachingDefs(
+    MachineOperand &UseMO, LiveIntervals *LIS,
+    SmallVectorImpl<SlotIndex> &DefIdxs) {
+  MachineInstr *UseMI = UseMO.getParent();
+  Register UseReg = UseMO.getReg();
+  unsigned UseSubReg = UseMO.getSubReg();
+
+  if (!UseReg.isVirtual() || !LIS->hasInterval(UseReg))
+    return;
+
+  LiveInterval &UseLI = LIS->getInterval(UseReg);
+  SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
+
+  // Use a set to deduplicate: a full-reg def appears in every SubRange but
+  // must be inserted into DefIdxs only once.
+  SmallSet<SlotIndex, 8> ResultSet;
+
+  if (UseLI.hasSubRanges()) {
+    const TargetRegisterInfo *TRI = DAG.MRI.getTargetRegisterInfo();
+
+    if (UseSubReg) {
+      // Find the SubRange whose LaneMask fully covers the operand's lanes.
+      // If none does (e.g. register initialised via per-lane subreg writes),
+      // fall back to all overlapping SubRanges to capture every reaching def.
+      LaneBitmask UseLanes = TRI->getSubRegIndexLaneMask(UseSubReg);
+      bool FoundFullCoverage = false;
+      for (LiveInterval::SubRange &SR : UseLI.subranges()) {
+        if ((SR.LaneMask & UseLanes) == UseLanes) {
+          collectReachingDefsInRange(SR, UseMI->getParent(), UseIdx, LIS,
+                                     ResultSet);
+          FoundFullCoverage = true;
+          break;
+        }
+      }
+      if (!FoundFullCoverage) {
+        for (LiveInterval::SubRange &SR : UseLI.subranges())
+          if ((SR.LaneMask & UseLanes).any())
+            collectReachingDefsInRange(SR, UseMI->getParent(), UseIdx, LIS,
+                                       ResultSet);
+      }
+    } else {
+      // Full-reg use: query every subrange so that partial (subreg) defs on
+      // different lanes are all captured.
+      for (LiveInterval::SubRange &SR : UseLI.subranges())
+        collectReachingDefsInRange(SR, UseMI->getParent(), UseIdx, LIS,
+                                   ResultSet);
+      // If the register has SubRanges but none covers the use point,
+      // LiveIntervals is malformed: a full-width def must appear in at least
+      // one SubRange.
+      assert(!ResultSet.empty() &&
+             "hasSubRanges() but no SubRange live at full-reg use: "
+             "LiveInterval construction is inconsistent");
     }
+  } else {
+    collectReachingDefsInRange(UseLI, UseMI->getParent(), UseIdx, LIS,
+                               ResultSet);
   }
+
+  DefIdxs.append(ResultSet.begin(), ResultSet.end());
 }
 
 void RewriteMFMAFormStage::findReachingUses(
@@ -1365,6 +1426,12 @@ void RewriteMFMAFormStage::findReachingUses(
   SlotIndex DefIdx = LIS->getInstructionIndex(*DefMI);
   for (MachineOperand &UseMO :
        DAG.MRI.use_nodbg_operands(DefMI->getOperand(0).getReg())) {
+    // Skip implicit operands: partial subreg defs carry an implicit use of the
+    // full register for RMW lane preservation, not as a real consumer of the
+    // MFMA dst value. Treating them as reaching uses inserts a spurious bridge
+    // copy before the partial def, corrupting MappedReg's live range.
+    if (UseMO.isImplicit())
+      continue;
     SmallVector<SlotIndex, 8> ReachingDefIndexes;
     findReachingDefs(UseMO, LIS, ReachingDefIndexes);
 
@@ -1399,6 +1466,11 @@ bool RewriteMFMAFormStage::initGCNSchedStage() {
   TII = ST.getInstrInfo();
   SRI = ST.getRegisterInfo();
 
+  // rewrite() only inserts COPYs within existing blocks and never alters CFG
+  // edges, so the post-dominator tree is stable for the whole stage; compute it
+  // once here and reuse it in Check 3 and Case 1.
+  MPDT.recalculate(MF);
+
   std::vector<std::pair<MachineInstr *, unsigned>> RewriteCands;
   DenseMap<MachineBasicBlock *, std::set<Register>> CopyForUse;
   SmallPtrSet<MachineInstr *, 8> CopyForDef;
@@ -2178,6 +2250,31 @@ bool UnclusteredHighRPStage::shouldRevertScheduling(unsigned WavesAfter) {
   return Profit < ScheduleMetrics::ScaleFactor;
 }
 
+bool RewriteMFMAFormStage::shouldRevertScheduling(unsigned WavesAfter) {
+  if (PressureAfter == PressureBefore)
+    return false;
+
+  if (GCNSchedStage::shouldRevertScheduling(WavesAfter))
+    return true;
+
+  // This stage targets archVGPR pressure specifically, so the base
+  // mayCauseSpilling (gated on the total-RP isRegionWithExcessRP flag) may miss
+  // archVGPR excess. archVGPR and AGPR share one physical limit; revert if
+  // either dimension is still over that limit and worse than before rewrite.
+  if (RegionsWithExcessArchVGPR[RegionIdx]) {
+    unsigned MaxArchVGPRs = ST.getAddressableNumArchVGPRs();
+    if (PressureAfter.getArchVGPRNum() > MaxArchVGPRs &&
+        PressureAfter.getArchVGPRNum() > PressureBefore.getArchVGPRNum())
+      return true;
+    if (PressureAfter.getAGPRNum() > MaxArchVGPRs &&
+        PressureAfter.getAGPRNum() > PressureBefore.getAGPRNum())
+      return true;
+  } else if (mayCauseSpilling(WavesAfter)) {
+    return true;
+  }
+  return false;
+}
+
 bool ClusteredLowOccStage::shouldRevertScheduling(unsigned WavesAfter) {
   if (PressureAfter == PressureBefore)
     return false;
@@ -2290,12 +2387,29 @@ void GCNSchedStage::modifyRegionSchedule(unsigned RegionIdx,
   DAG.Regions[RegionIdx].first = MIOrder.front();
 }
 
+static unsigned getDefSubReg(const MachineInstr &MI, Register Reg) {
+  for (const MachineOperand &MO : MI.operands())
+    if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
+      return MO.getSubReg();
+  return AMDGPU::NoSubRegister;
+}
+
+/// Returns true if \p MI is a class-agnostic subreg writer (COPY or AV_MOV).
+/// These lower to v_accvgpr_write after AGPR reclassification and are legal.
+static bool isAgnosticSubregWriter(const MachineInstr *MI) {
+  if (MI->isCopy())
+    return true;
+  unsigned Opc = MI->getOpcode();
+  return Opc == AMDGPU::AV_MOV_B32_IMM_PSEUDO ||
+         Opc == AMDGPU::AV_MOV_B64_IMM_PSEUDO;
+}
+
 /// 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,
+    MachineInstr *RD, const SmallSetVector<MachineInstr *, 16> &RewriteSet,
     const DenseSet<Register> &CandSrc2Regs, const SIInstrInfo &TII) {
   if (TII.isMAI(*RD))
     return RewriteSet.contains(RD);
@@ -2309,9 +2423,14 @@ static bool isReachingDefAGPRForm(
 
 bool RewriteMFMAFormStage::hasUseRequiringVGPR(
     ArrayRef<SlotIndex> Src2ReachingDefs,
-    const SmallPtrSetImpl<MachineInstr *> &RewriteSet) {
+    const SmallSetVector<MachineInstr *, 16> &RewriteSet) {
   for (SlotIndex RDIdx : Src2ReachingDefs) {
     const MachineInstr *RD = DAG.LIS->getInstructionFromIndex(RDIdx);
+    // A rewritable candidate's dst becomes AGPR and Case 2 bridges its non-MAI
+    // uses, so it imposes no VGPR constraint on src2. Excluded MFMAs are no
+    // longer in RewriteSet.
+    if (TII->isMAI(*RD) && RewriteSet.contains(RD))
+      continue;
     SmallVector<MachineOperand *, 8> ReachingUses;
     findReachingUses(RD, DAG.LIS, ReachingUses);
     for (const MachineOperand *UseMO : ReachingUses) {
@@ -2349,123 +2468,487 @@ void RewriteMFMAFormStage::resetRewriteCandsToVGPR(
   }
 }
 
+SmallVector<RewriteMFMAFormStage::CopyGroup, 2>
+RewriteMFMAFormStage::getCopyGroups(ArrayRef<MachineOperand *> Uses,
+                                    Register Reg, MachineRegisterInfo &MRI,
+                                    const SIRegisterInfo *SRI,
+                                    const TargetRegisterInfo *TRI) {
+  const TargetRegisterClass *DstRC = MRI.getRegClass(Reg);
+  const TargetRegisterClass *AgprRC = SRI->getEquivalentAGPRClass(DstRC);
+  const TargetRegisterClass *FullVGPRRC = SRI->getEquivalentVGPRClass(DstRC);
+  DenseMap<unsigned, SmallVector<MachineOperand *, 4>> BySubReg;
+  for (MachineOperand *MO : Uses)
+    BySubReg[MO->getSubReg()].push_back(MO);
+  SmallVector<CopyGroup, 2> Groups;
+  for (auto &[SR, SRUses] : BySubReg) {
+    unsigned SrcSubReg = AMDGPU::NoSubRegister;
+    const TargetRegisterClass *VGPRRC = FullVGPRRC;
+    if (SR != AMDGPU::NoSubRegister)
+      if (const auto *SubRC = TRI->getSubRegisterClass(AgprRC, SR))
+        if (const auto *NarrowRC = SRI->getEquivalentVGPRClass(SubRC)) {
+          SrcSubReg = SR;
+          VGPRRC = NarrowRC;
+        }
+    Groups.push_back({SrcSubReg, VGPRRC, std::move(SRUses)});
+  }
+  return Groups;
+}
+
 bool RewriteMFMAFormStage::isRewriteCandidate(MachineInstr *MI) const {
   if (!static_cast<const SIInstrInfo *>(DAG.TII)->isMAI(*MI))
     return false;
   if (AMDGPU::getMFMASrcCVDstAGPROp(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 true;
+}
+
+bool RewriteMFMAFormStage::isSrc2MergePoint(
+    Register Src2Reg, const MachineBasicBlock *P,
+    const SmallPtrSetImpl<const MachineBasicBlock *> &DefBlocks) const {
+  auto &MDT = DAG.LIS->getDomTree();
+
+  // (A) P post-dominates every def block -- the COPY reads a single merged
+  // %acc.
+  for (const MachineBasicBlock *DefBB : DefBlocks)
+    if (!MPDT.dominates(P, DefBB))
       return false;
-  }
+
+  // (B) P dominates every use of Src2Reg -- %MappedReg reaches every consumer.
+  //     Scanning all uses is a safe superset (non-candidate uses can only
+  //     reject a rewrite, never break one).
+  for (const MachineOperand &UseMO : DAG.MRI.use_nodbg_operands(Src2Reg))
+    if (!MDT.dominates(P, UseMO.getParent()->getParent()))
+      return false;
+
   return true;
 }
 
-bool RewriteMFMAFormStage::initHeuristics(
-    std::vector<std::pair<MachineInstr *, unsigned>> &RewriteCands,
-    DenseMap<MachineBasicBlock *, std::set<Register>> &CopyForUse,
-    SmallPtrSetImpl<MachineInstr *> &CopyForDef) {
-  bool Changed = false;
+bool RewriteMFMAFormStage::hasSrc2BridgeConflict(
+    ArrayRef<SlotIndex> DefIdxs, Register Src2Reg,
+    const MachineBasicBlock *CandBlock,
+    const SmallPtrSetImpl<const MachineBasicBlock *> &BridgeBlocks,
+    const SmallPtrSetImpl<const MachineBasicBlock *> &RedefPartialBlocks,
+    const SmallSetVector<MachineInstr *, 16> &RewriteSet,
+    const DenseSet<Register> &CandSrc2Regs) const {
+  // Returns true (conflict, exclude the candidate) if any check below fires.
+  auto &MDT = DAG.LIS->getDomTree();
+
+  SmallVector<MachineInstr *, 8> MAIMIs;
+  SmallVector<MachineInstr *, 8> NonMAIMIs;
+  for (SlotIndex SI : DefIdxs) {
+    MachineInstr *MI = DAG.LIS->getInstructionFromIndex(SI);
+    if (TII->isMFMA(*MI))
+      MAIMIs.push_back(MI);
+    else
+      NonMAIMIs.push_back(MI);
+  }
+  if (NonMAIMIs.empty())
+    return false;
 
-  // 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))
+  // Check 1: MAI def dominating a non-MAI def = AGPR RMW the bridge can't do.
+  for (MachineInstr *M : MAIMIs)
+    for (MachineInstr *N : NonMAIMIs)
+      if (MDT.dominates(M, N))
+        return true;
+
+  // SkipBridgeCoverage: skip Check 2 when every MAI def is a candidate
+  // (supplies an AGPR value) not dominated by any non-MAI def (parallel; the
+  // other direction is Check 1).
+  bool SkipBridgeCoverage =
+      !MAIMIs.empty() && all_of(MAIMIs, [&](MachineInstr *M) {
+        return isRewriteCandidate(M) &&
+               none_of(NonMAIMIs,
+                       [&](MachineInstr *N) { return MDT.dominates(N, M); });
+      });
+  if (!SkipBridgeCoverage) {
+    // True if every entry->UseBlock path crosses a bridge block: walk preds,
+    // stopping at bridge blocks; reaching entry (no preds) means uncovered.
+    auto CoveredByBridgeSet = [&](const MachineBasicBlock *UseBlock) {
+      if (BridgeBlocks.contains(UseBlock))
+        return true;
+      SmallPtrSet<const MachineBasicBlock *, 16> Visited;
+      SmallVector<const MachineBasicBlock *, 16> Worklist(
+          UseBlock->pred_begin(), UseBlock->pred_end());
+      while (!Worklist.empty()) {
+        const MachineBasicBlock *B = Worklist.pop_back_val();
+        if (BridgeBlocks.contains(B))
+          continue;
+        if (B->pred_empty())
+          return false;
+        if (Visited.insert(B).second)
+          Worklist.append(B->pred_begin(), B->pred_end());
+      }
+      return true;
+    };
+    for (const MachineOperand &UseMO : DAG.MRI.use_nodbg_operands(Src2Reg)) {
+      const MachineBasicBlock *UseBlock = UseMO.getParent()->getParent();
+      if (!CoveredByBridgeSet(UseBlock))
+        return true;
+    }
+  }
+
+  // Check 3 (fragmentation gate): a non-fragmented interval needs no merge
+  // point; a fragmented one must funnel through a single merge block.
+  if (RedefPartialBlocks.size() < 2)
+    return false;
+  auto isAcyclicSingleBlockMFMAMerge = [&]() {
+    // MAIMIs is non-empty here; only the single-non-MAI-block shape is checked.
+    SmallPtrSet<const MachineBasicBlock *, 4> NonMAIBlocks;
+    for (MachineInstr *N : NonMAIMIs)
+      NonMAIBlocks.insert(N->getParent());
+    if (NonMAIBlocks.size() != 1)
+      return false;
+    const MachineBasicBlock *NonMAIBlock = *NonMAIBlocks.begin();
+    for (MachineInstr *M : MAIMIs) {
+      const MachineBasicBlock *MBlk = M->getParent();
+      if (MBlk == CandBlock || MBlk == NonMAIBlock ||
+          !MPDT.dominates(CandBlock, MBlk))
+        return false;
+    }
+    return true;
+  };
+  bool MergeOk = MAIMIs.empty()
+                     ? isSrc2MergePoint(Src2Reg, CandBlock, RedefPartialBlocks)
+                     : isAcyclicSingleBlockMFMAMerge();
+  if (!MergeOk)
+    return true;
+
+  // Coverage: bridge COPYs come only from non-AGPR-form reaching defs.  If
+  // those don't jointly cover every live lane of Src2Reg, neither emit strategy
+  // can reconstruct the full value.  No subranges = whole-reg live = no lane
+  // gap.
+  if (!DAG.LIS->hasInterval(Src2Reg))
+    return false;
+  const LiveInterval &LI = DAG.LIS->getInterval(Src2Reg);
+  if (!LI.hasSubRanges())
+    return false;
+
+  LaneBitmask LiveLanes = LaneBitmask::getNone();
+  for (const LiveInterval::SubRange &SR : LI.subranges())
+    LiveLanes |= SR.LaneMask;
+
+  LaneBitmask BridgeDefLanes = LaneBitmask::getNone();
+  for (MachineInstr *N : NonMAIMIs) {
+    if (isReachingDefAGPRForm(N, RewriteSet, CandSrc2Regs, *TII))
+      continue; // Match Src2DefsReplace's filter exactly.
+    unsigned Sub = getDefSubReg(*N, Src2Reg);
+    BridgeDefLanes |= (Sub == AMDGPU::NoSubRegister)
+                          ? LaneBitmask::getAll()
+                          : DAG.TRI->getSubRegIndexLaneMask(Sub);
+  }
+
+  return (BridgeDefLanes & LiveLanes) != LiveLanes;
+}
+
+void RewriteMFMAFormStage::propagateExclusionForward(
+    MachineInstr *Root, SmallPtrSetImpl<MachineInstr *> &ExcludedMFMAs) {
+  SmallVector<MachineInstr *, 8> Worklist = {Root};
+  while (!Worklist.empty()) {
+    MachineInstr *ExclMI = Worklist.pop_back_val();
+    MachineOperand &DstMO = ExclMI->getOperand(0);
+    if (!DstMO.isReg() || !DstMO.getReg().isVirtual())
+      continue;
+    Register DstReg = DstMO.getReg();
+    for (MachineOperand &UseMO : DAG.MRI.use_nodbg_operands(DstReg)) {
+      MachineInstr *UserMI = UseMO.getParent();
+      if (!isRewriteCandidate(UserMI))
+        continue;
+      MachineOperand *UserSrc2 =
+          TII->getNamedOperand(*UserMI, AMDGPU::OpName::src2);
+      if (!UserSrc2 || !UserSrc2->isReg() || UserSrc2->getReg() != DstReg)
         continue;
-      RewriteSet.insert(&MI);
-      MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
-      if (Src2 && Src2->isReg())
-        CandSrc2Regs.insert(Src2->getReg());
+      if (ExcludedMFMAs.insert(UserMI).second)
+        Worklist.push_back(UserMI);
     }
   }
+}
+
+bool RewriteMFMAFormStage::hasDstSubregConflict(Register DstReg,
+                                                MachineInstr *MFMA) {
+  SmallVector<MachineOperand *, 8> DstReachingUses;
+  findReachingUses(MFMA, DAG.LIS, DstReachingUses);
+  SmallPtrSet<MachineInstr *, 8> CheckedDefs;
+  SmallVector<MachineInstr *, 4> SafeSubregDefs;
 
-  // Prepare for the heuristics
-  for (MachineBasicBlock &MBB : MF) {
-    for (MachineInstr &MI : MBB) {
-      if (!isRewriteCandidate(&MI))
+  // Phase 1: non-agnostic subreg def → conflict; agnostic → defer to Phase 2.
+  for (MachineOperand *RUOp : DstReachingUses) {
+    SmallVector<SlotIndex, 8> ReachingDefs;
+    findReachingDefs(*RUOp, DAG.LIS, ReachingDefs);
+    for (SlotIndex RDIdx : ReachingDefs) {
+      MachineInstr *RD = DAG.LIS->getInstructionFromIndex...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/210703


More information about the llvm-commits mailing list