Repository: llvm/llvm-project
Pull request #131387: [AMDGPU] Fix register class constraints for si-fold-operands pass when folding immediate into copies
Author: login: mssefat
Labels: name: backend:AMDGPU
Created: 2025-03-14T20:39:54Z | Merged: 2025-04-30T22:36:46Z

Fixes https://github.com/llvm/llvm-project/issues/130020

This fixes an issue where the si-fold-operands pass would incorrectly fold immediate values into COPY instructions targeting av_32 registers.

The pass now checks register class constraints before attempting to fold the immediate.


Diff:
diff --git a/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp b/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
index d6acf9e081b9f..5caf23e41c16a 100644
--- a/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
+++ b/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
@@ -1068,6 +1068,16 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Fold if the destination register class of the MOV instruction (ResRC)
+    // is a superclass of (or equal to) the destination register class of the
+    // COPY (DestRC). If this condition fails, folding would be illegal.
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    assert(MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1);
+    const TargetRegisterClass *ResRC =
+        TRI->getRegClass(MovDesc.operands()[0].RegClass);
+    if (!DestRC->hasSuperClassEq(ResRC))
+      return;
+
     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
     while (ImpOpI != ImpOpE) {
diff --git a/llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir b/llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
index 300bae7551ca5..706c0d8178d70 100644
--- a/llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
+++ b/llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
@@ -202,52 +202,70 @@ body:             |
 
 ...
 
-# FIXME: Register class restrictions of av register not respected,
-# issue 130020
-
-# ---
-# name: s_mov_b32_inlineimm_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 32
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_inlineimm_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#  bb.0:
-#    %0:vgpr_32 = V_MOV_B32_e32 32, implicit $exec
-#    %1:av_32 = COPY %0
-#    $agpr0 = COPY %1
-#    S_ENDPGM 0
-# ...
-
-# ---
-# name: s_mov_b32_imm_literal_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 999
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_imm_literal_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
+---
+name: s_mov_b32_inlineimm_copy_s_to_av_32
+tracksRegLiveness: true
+body:             |
+  bb.0:
+    ; GCN-LABEL: name: s_mov_b32_inlineimm_copy_s_to_av_32
+    ; GCN: [[S_MOV_B32_:%[0-9]+]]:sreg_32 = S_MOV_B32 32
+    ; GCN-NEXT: [[COPY:%[0-9]+]]:av_32 = COPY [[S_MOV_B32_]]
+    ; GCN-NEXT: $agpr0 = COPY [[COPY]]
+    ; GCN-NEXT: S_ENDPGM 0
+    %0:sreg_32 = S_MOV_B32 32
+    %1:av_32 = COPY %0
+    $agpr0 = COPY %1
+    S_ENDPGM 0
+
+...
+
+---
+name: v_mov_b32_inlineimm_copy_v_to_av_32
+tracksRegLiveness: true
+body:             |
+ bb.0:
+    ; GCN-LABEL: name: v_mov_b32_inlineimm_copy_v_to_av_32
+    ; GCN: [[V_MOV_B32_e32_:%[0-9]+]]:vgpr_32 = V_MOV_B32_e32 32, implicit $exec
+    ; GCN-NEXT: [[COPY:%[0-9]+]]:av_32 = COPY [[V_MOV_B32_e32_]]
+    ; GCN-NEXT: $agpr0 = COPY [[COPY]]
+    ; GCN-NEXT: S_ENDPGM 0
+   %0:vgpr_32 = V_MOV_B32_e32 32, implicit $exec
+   %1:av_32 = COPY %0
+   $agpr0 = COPY %1
+   S_ENDPGM 0
+
+...
+
+---
+name: s_mov_b32_imm_literal_copy_s_to_av_32
+tracksRegLiveness: true
+body:             |
+  bb.0:
+    ; GCN-LABEL: name: s_mov_b32_imm_literal_copy_s_to_av_32
+    ; GCN: [[S_MOV_B32_:%[0-9]+]]:sreg_32 = S_MOV_B32 999
+    ; GCN-NEXT: [[COPY:%[0-9]+]]:av_32 = COPY [[S_MOV_B32_]]
+    ; GCN-NEXT: $agpr0 = COPY [[COPY]]
+    ; GCN-NEXT: S_ENDPGM 0
+    %0:sreg_32 = S_MOV_B32 999
+    %1:av_32 = COPY %0
+    $agpr0 = COPY %1
+    S_ENDPGM 0
+
+...
+
+---
+name: v_mov_b32_imm_literal_copy_v_to_av_32
+tracksRegLiveness: true
+body:             |
+  bb.0:
+    ; GCN-LABEL: name: v_mov_b32_imm_literal_copy_v_to_av_32
+    ; GCN: [[V_MOV_B32_e32_:%[0-9]+]]:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
+    ; GCN-NEXT: [[COPY:%[0-9]+]]:av_32 = COPY [[V_MOV_B32_e32_]]
+    ; GCN-NEXT: $agpr0 = COPY [[COPY]]
+    ; GCN-NEXT: S_ENDPGM 0
+    %0:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
+    %1:av_32 = COPY %0
+    $agpr0 = COPY %1
+    S_ENDPGM 0
+
+...


Reviews:
user: login: jayfoad
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T11:38:38Z
user: login: arsenm
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-17T12:51:40Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-18T20:10:43Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-26T18:11:25Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-26T18:11:39Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-07T13:45:20Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-07T13:45:35Z
user: login: jayfoad
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-08T09:43:00Z
user: login: arsenm
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-08T09:52:46Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-15T19:04:14Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-15T19:04:37Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-17T20:17:05Z
user: login: arsenm
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-18T19:42:29Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-21T16:45:12Z
user: login: jayfoad
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-29T08:38:13Z
user: login: jayfoad
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-29T08:40:50Z
user: login: mssefat
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-30T16:30:38Z
user: login: arsenm
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-04-30T16:57:33Z

Review comments:
diff_hunk: @@ -185,52 +185,49 @@ body:             |
 
 ...
 
-# FIXME: Register class restrictions of av register not respected,
-# issue 130020
-
-# ---
-# name: s_mov_b32_inlineimm_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 32
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_inlineimm_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#  bb.0:
-#    %0:vgpr_32 = V_MOV_B32_e32 32, implicit $exec
-#    %1:av_32 = COPY %0
-#    $agpr0 = COPY %1
-#    S_ENDPGM 0
-# ...
-
-# ---
-# name: s_mov_b32_imm_literal_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 999
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_imm_literal_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
+---
+name: s_mov_b32_inlineimm_copy_s_to_av_32
path: llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
user: login: jayfoad
body: New tests need checks for the expected output. Maybe convert the while file to use update_mir_test_checks?
created_at: 2025-03-17T11:38:38Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,11 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check if the destination register of the MOV operation belongs
+    // to a vector superclass. Folding would be illegal.
+    if (TRI->isVectorSuperClass(DestRC))
+      return;
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: arsenm
body: Would be better to query the register class of the result register, and check if there is a common class between it and the virtual register class. In the future it would be better to replace the instruction and modify the register class to enable folds in some cases 
created_at: 2025-03-17T12:51:40Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,11 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check if the destination register of the MOV operation belongs
+    // to a vector superclass. Folding would be illegal.
+    if (TRI->isVectorSuperClass(DestRC))
+      return;
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: mssefat
body: 
Thanks for your suggestion. Based on your comment, I've implemented the check. The snippet looks like following:

```
    // Check if the destination register class has a common class
    // with the expected register class for the MOV instruction.
    const MCInstrDesc &MovDesc = TII->get(MovOp);
    if (MovDesc.operands()[0].RegClass != -1) {
      const TargetRegisterClass *ResRC = 
          TRI->getRegClass(MovDesc.operands()[0].RegClass);
      const TargetRegisterClass *CommonRC = 
          TRI->getCommonSubClass(DestRC, ResRC);

      if (!CommonRC) {
        return;
      }
    }
```

Can you please confirm if this aligns correctly with your suggestion or further adjustments are needed?
created_at: 2025-03-18T20:10:43Z
author_association: CONTRIBUTOR
diff_hunk: @@ -185,52 +185,49 @@ body:             |
 
 ...
 
-# FIXME: Register class restrictions of av register not respected,
-# issue 130020
-
-# ---
-# name: s_mov_b32_inlineimm_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 32
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_inlineimm_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#  bb.0:
-#    %0:vgpr_32 = V_MOV_B32_e32 32, implicit $exec
-#    %1:av_32 = COPY %0
-#    $agpr0 = COPY %1
-#    S_ENDPGM 0
-# ...
-
-# ---
-# name: s_mov_b32_imm_literal_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 999
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_imm_literal_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
+---
+name: s_mov_b32_inlineimm_copy_s_to_av_32
path: llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
user: login: mssefat
body: I have pushed the updated changes. Could you please review?
created_at: 2025-03-26T18:11:25Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,11 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check if the destination register of the MOV operation belongs
+    // to a vector superclass. Folding would be illegal.
+    if (TRI->isVectorSuperClass(DestRC))
+      return;
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: mssefat
body: I have pushed the updated changes. Could you please review?
created_at: 2025-03-26T18:11:39Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,11 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check if the destination register of the MOV operation belongs
+    // to a vector superclass. Folding would be illegal.
+    if (TRI->isVectorSuperClass(DestRC))
+      return;
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: mssefat
body: Ping
created_at: 2025-04-07T13:45:20Z
author_association: CONTRIBUTOR
diff_hunk: @@ -185,52 +185,49 @@ body:             |
 
 ...
 
-# FIXME: Register class restrictions of av register not respected,
-# issue 130020
-
-# ---
-# name: s_mov_b32_inlineimm_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 32
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_inlineimm_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#  bb.0:
-#    %0:vgpr_32 = V_MOV_B32_e32 32, implicit $exec
-#    %1:av_32 = COPY %0
-#    $agpr0 = COPY %1
-#    S_ENDPGM 0
-# ...
-
-# ---
-# name: s_mov_b32_imm_literal_copy_s_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:sreg_32 = S_MOV_B32 999
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
-
-# ---
-# name: v_mov_b32_imm_literal_copy_v_to_av_32
-# tracksRegLiveness: true
-# body:             |
-#   bb.0:
-#     %0:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
-#     %1:av_32 = COPY %0
-#     $agpr0 = COPY %1
-#     S_ENDPGM 0
-
-# ...
+---
+name: s_mov_b32_inlineimm_copy_s_to_av_32
path: llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
user: login: mssefat
body: Ping
created_at: 2025-04-07T13:45:35Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,16 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Fold if the destination register class of the MOV instruction (ResRC)
+    // is a superclass of (or equal to) the destination register class of the COPY (DestRC).
+    // If this condition fails, folding would be illegal.
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    if (MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1) {
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: jayfoad
body: Can you just assert these conditions? I don't think they should ever fail.
created_at: 2025-04-08T09:40:48Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,16 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Fold if the destination register class of the MOV instruction (ResRC)
+    // is a superclass of (or equal to) the destination register class of the COPY (DestRC).
+    // If this condition fails, folding would be illegal.
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    if (MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1) {
+      const TargetRegisterClass *ResRC = 
+          TRI->getRegClass(MovDesc.operands()[0].RegClass);
+      if (!DestRC -> hasSuperClassEq(ResRC)) return;
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: jayfoad
body: No space around `->`. Body of `if` on separate line.
```suggestion
      if (!DestRC->hasSuperClassEq(ResRC))
        return;
```
created_at: 2025-04-08T09:41:40Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,14 +1,23 @@
-# RUN: llc -mtriple=amdgcn -run-pass si-fold-operands -verify-machineinstrs %s -o - | FileCheck -check-prefix=GCN %s
-
-# GCN-LABEL:       name: fold-imm-copy
-# GCN:             V_AND_B32_e32 65535
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py UTC_ARGS: --version 5
path: llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
user: login: jayfoad
body: Please make a separate PR for this and commit it first. Then rebase the current PR.
created_at: 2025-04-08T09:42:56Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,16 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Fold if the destination register class of the MOV instruction (ResRC)
+    // is a superclass of (or equal to) the destination register class of the COPY (DestRC).
+    // If this condition fails, folding would be illegal.
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    if (MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1) {
+      const TargetRegisterClass *ResRC = 
+          TRI->getRegClass(MovDesc.operands()[0].RegClass);
+      if (!DestRC -> hasSuperClassEq(ResRC)) return;
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: arsenm
body: Can you use getCommonSubClass or getMatchingSuperRegClass instead of directly checking hasSuperClassEq 
created_at: 2025-04-08T09:52:46Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,14 +1,23 @@
-# RUN: llc -mtriple=amdgcn -run-pass si-fold-operands -verify-machineinstrs %s -o - | FileCheck -check-prefix=GCN %s
-
-# GCN-LABEL:       name: fold-imm-copy
-# GCN:             V_AND_B32_e32 65535
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py UTC_ARGS: --version 5
path: llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir
user: login: mssefat
body: Done and I have pushed the updated changes. Could you please review?
created_at: 2025-04-15T19:04:14Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,16 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Fold if the destination register class of the MOV instruction (ResRC)
+    // is a superclass of (or equal to) the destination register class of the COPY (DestRC).
+    // If this condition fails, folding would be illegal.
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    if (MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1) {
+      const TargetRegisterClass *ResRC = 
+          TRI->getRegClass(MovDesc.operands()[0].RegClass);
+      if (!DestRC -> hasSuperClassEq(ResRC)) return;
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: mssefat
body: I have pushed the updated changes. Could you please review?
created_at: 2025-04-15T19:04:37Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1047,6 +1047,16 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Fold if the destination register class of the MOV instruction (ResRC)
+    // is a superclass of (or equal to) the destination register class of the COPY (DestRC).
+    // If this condition fails, folding would be illegal.
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    if (MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1) {
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: mssefat
body: Done, can you please review?
created_at: 2025-04-17T20:17:05Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1068,6 +1068,20 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check for common register subclass between destination (DestRC) and MOV
+    // result (ResRC). If exists, verify this common subclass is a superclass of
+    // (or equal to) the destination register class, otherwise folding is
+    // illegal.
+
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    assert(MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1);
+    const TargetRegisterClass *ResRC =
+        TRI->getRegClass(MovDesc.operands()[0].RegClass);
+    const TargetRegisterClass *CommonRC = TRI->getCommonSubClass(DestRC, ResRC);
+
+    if (!CommonRC || !DestRC->hasSuperClassEq(CommonRC))
+      return;
+
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: arsenm
body: ```suggestion
    if (!CommonRC)
      return;

```

hasSuperClassEq should be redundant with finding the common class 
created_at: 2025-04-18T19:42:14Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1068,6 +1068,20 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check for common register subclass between destination (DestRC) and MOV
+    // result (ResRC). If exists, verify this common subclass is a superclass of
+    // (or equal to) the destination register class, otherwise folding is
+    // illegal.
+
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    assert(MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1);
+    const TargetRegisterClass *ResRC =
+        TRI->getRegClass(MovDesc.operands()[0].RegClass);
+    const TargetRegisterClass *CommonRC = TRI->getCommonSubClass(DestRC, ResRC);
+
+    if (!CommonRC || !DestRC->hasSuperClassEq(CommonRC))
+      return;
+
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: mssefat
body: I think hasSuperClassEq is not redundant with finding common subclass. Consider this basic block where the copy operation is illegal:

```
bb.0:
  %1:av_32 = V_MOV_B32_e32 32, implicit $exec
  $agpr0 = COPY %1:av_32
  S_ENDPGM 0
```

In this example:

DestRC is AV_32
ResRC is VGPR_32
CommonRC is VGPR_32

If we only check for CommonRC, the check would allow folding in this case since CommonRC exists (VGPR_32). However, folding here is illegal. And I think we need the condition `if (!DestRC->hasSuperClassEq(CommonRC)) return;`.
created_at: 2025-04-21T16:45:12Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1068,6 +1068,20 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check for common register subclass between destination (DestRC) and MOV
+    // result (ResRC). If exists, verify this common subclass is a superclass of
+    // (or equal to) the destination register class, otherwise folding is
+    // illegal.
+
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    assert(MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1);
+    const TargetRegisterClass *ResRC =
+        TRI->getRegClass(MovDesc.operands()[0].RegClass);
+    const TargetRegisterClass *CommonRC = TRI->getCommonSubClass(DestRC, ResRC);
+
+    if (!CommonRC || !DestRC->hasSuperClassEq(CommonRC))
+      return;
+
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: jayfoad
body: Why do you need CommonRC? Isn't the whole check equivalent to `DestRC->hasSuperClassEq(ResRC)`?
created_at: 2025-04-29T08:38:12Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1068,6 +1068,20 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check for common register subclass between destination (DestRC) and MOV
+    // result (ResRC). If exists, verify this common subclass is a superclass of
+    // (or equal to) the destination register class, otherwise folding is
+    // illegal.
+
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    assert(MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1);
+    const TargetRegisterClass *ResRC =
+        TRI->getRegClass(MovDesc.operands()[0].RegClass);
+    const TargetRegisterClass *CommonRC = TRI->getCommonSubClass(DestRC, ResRC);
+
+    if (!CommonRC || !DestRC->hasSuperClassEq(CommonRC))
+      return;
+
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: jayfoad
body: The code as you have written it is weird, because CommonRC is by construction a subclass of DestRC, and then you are checking that it is a superclass of DestRC. These can only both be true if CommonRC *is* DestRC.
created_at: 2025-04-29T08:40:50Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1068,6 +1068,20 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check for common register subclass between destination (DestRC) and MOV
+    // result (ResRC). If exists, verify this common subclass is a superclass of
+    // (or equal to) the destination register class, otherwise folding is
+    // illegal.
+
+    const MCInstrDesc &MovDesc = TII->get(MovOp);
+    assert(MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1);
+    const TargetRegisterClass *ResRC =
+        TRI->getRegClass(MovDesc.operands()[0].RegClass);
+    const TargetRegisterClass *CommonRC = TRI->getCommonSubClass(DestRC, ResRC);
+
+    if (!CommonRC || !DestRC->hasSuperClassEq(CommonRC))
+      return;
+
path: llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
user: login: mssefat
body: They should be equivalent check. I am reverting to the previous use of DestRC->hasSuperClassEq(ResRC). @arsenm please let me know if I am missing something.  
created_at: 2025-04-30T16:30:38Z
author_association: CONTRIBUTOR

PR comments:
user: login: github-actions[bot]
created_at: 2025-03-14T20:40:15Z
body: <!--LLVM NEW CONTRIBUTOR COMMENT-->

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/).
author_association: NONE
user: login: llvmbot
created_at: 2025-03-14T20:40:50Z
body: 
<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-amdgpu

Author: None (mssefat)

<details>
<summary>Changes</summary>

This fixes an issue where the si-fold-operands pass would incorrectly fold immediate values into COPY instructions targeting av_32 registers.

The pass now checks register class constraints before attempting to fold the immediate.

---
Full diff: https://github.com/llvm/llvm-project/pull/131387.diff


2 Files Affected:

- (modified) llvm/lib/Target/AMDGPU/SIFoldOperands.cpp (+5) 
- (added) llvm/test/CodeGen/AMDGPU/si-fold-operands-imm-into-copy.mir (+36) 


``````````diff
diff --git a/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp b/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
index 91df516b80857..5a7fefaafd768 100644
--- a/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
+++ b/llvm/lib/Target/AMDGPU/SIFoldOperands.cpp
@@ -1047,6 +1047,11 @@ void SIFoldOperandsImpl::foldOperand(
     if (MovOp == AMDGPU::COPY)
       return;
 
+    // Check if the destination register of the MOV operation belongs
+    // to a vector superclass. Folding would be illegal.
+    if (TRI->isVectorSuperClass(DestRC))
+      return;
+
     MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
     MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
     while (ImpOpI != ImpOpE) {
diff --git a/llvm/test/CodeGen/AMDGPU/si-fold-operands-imm-into-copy.mir b/llvm/test/CodeGen/AMDGPU/si-fold-operands-imm-into-copy.mir
new file mode 100644
index 0000000000000..869da156a83d6
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/si-fold-operands-imm-into-copy.mir
@@ -0,0 +1,36 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py UTC_ARGS: --version 5
+# RUN: llc -mtriple=amdgcn -mcpu=gfx90a -run-pass=si-fold-operands -verify-machineinstrs -o - %s 2>&1 | FileCheck %s
+
+---
+
+name: s_mov_b32_imm_literal_copy_s_to_av_32
+tracksRegLiveness: true
+body:             |
+  bb.0:
+    ; CHECK-LABEL: name: s_mov_b32_imm_literal_copy_s_to_av_32
+    ; CHECK: [[S_MOV_B32_:%[0-9]+]]:sreg_32 = S_MOV_B32 999
+    ; CHECK-NEXT: [[COPY:%[0-9]+]]:av_32 = COPY [[S_MOV_B32_]]
+    ; CHECK-NEXT: $agpr0 = COPY [[COPY]]
+    ; CHECK-NEXT: S_ENDPGM 0
+    %0:sreg_32 = S_MOV_B32 999
+    %1:av_32 = COPY %0
+    $agpr0 = COPY %1
+    S_ENDPGM 0
+...
+
+---
+
+name: v_mov_b32_imm_literal_copy_v_to_av_32
+tracksRegLiveness: true
+body:             |
+  bb.0:
+    ; CHECK-LABEL: name: v_mov_b32_imm_literal_copy_v_to_av_32
+    ; CHECK: [[V_MOV_B32_e32_:%[0-9]+]]:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
+    ; CHECK-NEXT: [[COPY:%[0-9]+]]:av_32 = COPY [[V_MOV_B32_e32_]]
+    ; CHECK-NEXT: $agpr0 = COPY [[COPY]]
+    ; CHECK-NEXT: S_ENDPGM 0
+    %0:vgpr_32 = V_MOV_B32_e32 999, implicit $exec
+    %1:av_32 = COPY %0
+    $agpr0 = COPY %1
+    S_ENDPGM 0
+...

``````````

</details>

author_association: MEMBER
user: login: mssefat
created_at: 2025-03-14T20:47:01Z
body: @arsenm could you please review? 
author_association: CONTRIBUTOR
user: login: arsenm
created_at: 2025-03-16T02:23:07Z
body: The tests for the issue are already in llvm/test/CodeGen/AMDGPU/fold-imm-copy.mir (and you should also mention this fixes issue number in the description) 
author_association: CONTRIBUTOR
user: login: mssefat
created_at: 2025-03-17T02:31:54Z
body: @arsenm I updated accordingly. Please check. 
author_association: CONTRIBUTOR
user: login: mssefat
created_at: 2025-04-28T21:40:25Z
body: @arsenm @jayfoad Ping
author_association: CONTRIBUTOR
user: login: github-actions[bot]
created_at: 2025-04-30T16:32:49Z
body: <!--LLVM CODE FORMAT COMMENT: {clang-format}-->

:white_check_mark: With the latest revision this PR passed the C/C++ code formatter.
author_association: NONE
user: login: github-actions[bot]
created_at: 2025-04-30T22:37:07Z
body: <!--LLVM BUILDBOT INFORMATION COMMENT-->

@mssefat Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail [here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of [LLVM development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy). You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

author_association: NONE
user: login: llvm-ci
created_at: 2025-04-30T22:42:21Z
body: LLVM Buildbot has detected a new failure on builder `ml-opt-dev-x86-64` running on `ml-opt-dev-x86-64-b2` while building `llvm` at step 4 "cmake-configure".

Full details are available at: https://lab.llvm.org/buildbot/#/builders/137/builds/17778

<details>
<summary>Here is the relevant piece of the build log for the reference</summary>

```
Step 4 (cmake-configure) failure: cmake (failure)
...
-- Targeting XCore
-- Registering ExampleIRTransforms as a pass plugin (static build: OFF)
-- Registering Bye as a pass plugin (static build: OFF)
-- Failed to find LLVM FileCheck
-- Google Benchmark version: v0.0.0, normalized to 0.0.0
-- Looking for shm_open in rt
-- Looking for shm_open in rt - found
-- Performing Test HAVE_CXX_FLAG_WALL
-- Performing Test HAVE_CXX_FLAG_WALL - Success
-- Performing Test HAVE_CXX_FLAG_WEXTRA
-- Performing Test HAVE_CXX_FLAG_WEXTRA - Success
-- Performing Test HAVE_CXX_FLAG_WSHADOW
-- Performing Test HAVE_CXX_FLAG_WSHADOW - Success
-- Performing Test HAVE_CXX_FLAG_WFLOAT_EQUAL
-- Performing Test HAVE_CXX_FLAG_WFLOAT_EQUAL - Success
-- Performing Test HAVE_CXX_FLAG_WOLD_STYLE_CAST
-- Performing Test HAVE_CXX_FLAG_WOLD_STYLE_CAST - Success
-- Performing Test HAVE_CXX_FLAG_WSUGGEST_OVERRIDE
-- Performing Test HAVE_CXX_FLAG_WSUGGEST_OVERRIDE - Success
-- Performing Test HAVE_CXX_FLAG_PEDANTIC
-- Performing Test HAVE_CXX_FLAG_PEDANTIC - Success
-- Performing Test HAVE_CXX_FLAG_PEDANTIC_ERRORS
-- Performing Test HAVE_CXX_FLAG_PEDANTIC_ERRORS - Success
-- Performing Test HAVE_CXX_FLAG_WSHORTEN_64_TO_32
-- Performing Test HAVE_CXX_FLAG_WSHORTEN_64_TO_32 - Failed
-- Performing Test HAVE_CXX_FLAG_FSTRICT_ALIASING
-- Performing Test HAVE_CXX_FLAG_FSTRICT_ALIASING - Success
-- Performing Test HAVE_CXX_FLAG_WNO_DEPRECATED_DECLARATIONS
-- Performing Test HAVE_CXX_FLAG_WNO_DEPRECATED_DECLARATIONS - Success
-- Performing Test HAVE_CXX_FLAG_FNO_EXCEPTIONS
-- Performing Test HAVE_CXX_FLAG_FNO_EXCEPTIONS - Success
-- Performing Test HAVE_CXX_FLAG_WSTRICT_ALIASING
-- Performing Test HAVE_CXX_FLAG_WSTRICT_ALIASING - Success
-- Performing Test HAVE_CXX_FLAG_WD654
-- Performing Test HAVE_CXX_FLAG_WD654 - Failed
-- Performing Test HAVE_CXX_FLAG_WTHREAD_SAFETY
-- Performing Test HAVE_CXX_FLAG_WTHREAD_SAFETY - Failed
-- Performing Test HAVE_CXX_FLAG_COVERAGE
-- Performing Test HAVE_CXX_FLAG_COVERAGE - Success
-- Compiling and running to test HAVE_GNU_POSIX_REGEX
-- Performing Test HAVE_GNU_POSIX_REGEX -- failed to compile
-- Compiling and running to test HAVE_POSIX_REGEX
-- Performing Test HAVE_POSIX_REGEX -- success
-- Compiling and running to test HAVE_STEADY_CLOCK
-- Performing Test HAVE_STEADY_CLOCK -- success
-- Compiling and running to test HAVE_PTHREAD_AFFINITY
-- Performing Test HAVE_PTHREAD_AFFINITY -- failed to compile
-- Configuring incomplete, errors occurred!
See also "/b/ml-opt-dev-x86-64-b1/build/CMakeFiles/CMakeOutput.log".
See also "/b/ml-opt-dev-x86-64-b1/build/CMakeFiles/CMakeError.log".

```

</details>
author_association: NONE
user: login: llvm-ci
created_at: 2025-04-30T22:53:42Z
body: LLVM Buildbot has detected a new failure on builder `llvm-clang-aarch64-darwin` running on `doug-worker-4` while building `llvm` at step 6 "test-build-unified-tree-check-all".

Full details are available at: https://lab.llvm.org/buildbot/#/builders/190/builds/19286

<details>
<summary>Here is the relevant piece of the build log for the reference</summary>

```
Step 6 (test-build-unified-tree-check-all) failure: test (failure)
******************** TEST 'Clang-Unit :: ./AllClangUnitTests/36/51' FAILED ********************
Script(shard):
--
GTEST_OUTPUT=json:/Users/buildbot/buildbot-root/aarch64-darwin/build/tools/clang/unittests/./AllClangUnitTests-Clang-Unit-99198-36-51.json GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=51 GTEST_SHARD_INDEX=36 /Users/buildbot/buildbot-root/aarch64-darwin/build/tools/clang/unittests/./AllClangUnitTests
--

Script:
--
/Users/buildbot/buildbot-root/aarch64-darwin/build/tools/clang/unittests/./AllClangUnitTests --gtest_filter=TimeProfilerTest.ConstantEvaluationCxx20
--
/Users/buildbot/buildbot-root/aarch64-darwin/llvm-project/clang/unittests/Support/TimeProfilerTest.cpp:238: Failure
Expected equality of these values:
  R"(
Frontend (test.cc)
| ParseDeclarationOrFunctionDefinition (test.cc:2:1)
| ParseDeclarationOrFunctionDefinition (test.cc:6:1)
| | ParseFunctionDefinition (slow_func)
| | | EvaluateAsRValue (<test.cc:8:21>)
| | | EvaluateForOverflow (<test.cc:8:21, col:25>)
| | | EvaluateForOverflow (<test.cc:8:30, col:32>)
| | | EvaluateAsRValue (<test.cc:9:14>)
| | | EvaluateForOverflow (<test.cc:9:9, col:14>)
| | | isPotentialConstantExpr (slow_namespace::slow_func)
| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)
| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)
| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)
| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)
| ParseDeclarationOrFunctionDefinition (test.cc:16:1)
| | ParseFunctionDefinition (slow_test)
| | | EvaluateAsInitializer (slow_value)
| | | EvaluateAsConstantExpr (<test.cc:17:33, col:59>)
| | | EvaluateAsConstantExpr (<test.cc:18:11, col:37>)
| ParseDeclarationOrFunctionDefinition (test.cc:22:1)
| | EvaluateAsConstantExpr (<test.cc:23:31, col:57>)
| | EvaluateAsRValue (<test.cc:22:14, line:23:58>)
| ParseDeclarationOrFunctionDefinition (test.cc:25:1)
| | EvaluateAsInitializer (slow_init_list)
| PerformPendingInstantiations
)"
    Which is: "\nFrontend (test.cc)\n| ParseDeclarationOrFunctionDefinition (test.cc:2:1)\n| ParseDeclarationOrFunctionDefinition (test.cc:6:1)\n| | ParseFunctionDefinition (slow_func)\n| | | EvaluateAsRValue (<test.cc:8:21>)\n| | | EvaluateForOverflow (<test.cc:8:21, col:25>)\n| | | EvaluateForOverflow (<test.cc:8:30, col:32>)\n| | | EvaluateAsRValue (<test.cc:9:14>)\n| | | EvaluateForOverflow (<test.cc:9:9, col:14>)\n| | | isPotentialConstantExpr (slow_namespace::slow_func)\n| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)\n| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)\n| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)\n| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)\n| ParseDeclarationOrFunctionDefinition (test.cc:16:1)\n| | ParseFunctionDefinition (slow_test)\n| | | EvaluateAsInitializer (slow_value)\n| | | EvaluateAsConstantExpr (<test.cc:17:33, col:59>)\n| | | EvaluateAsConstantExpr (<test.cc:18:11, col:37>)\n| ParseDeclarationOrFunctionDefinition (test.cc:22:1)\n| | EvaluateAsConstantExpr (<test.cc:23:31, col:57>)\n| | EvaluateAsRValue (<test.cc:22:14, line:23:58>)\n| ParseDeclarationOrFunctionDefinition (test.cc:25:1)\n| | EvaluateAsInitializer (slow_init_list)\n| PerformPendingInstantiations\n"
  buildTraceGraph(Json)
    Which is: "\nFrontend (test.cc)\n| ParseDeclarationOrFunctionDefinition (test.cc:2:1)\n| ParseDeclarationOrFunctionDefinition (test.cc:6:1)\n| | ParseFunctionDefinition (slow_func)\n| | | EvaluateAsRValue (<test.cc:8:21>)\n| | | EvaluateForOverflow (<test.cc:8:21, col:25>)\n| | | EvaluateForOverflow (<test.cc:8:30, col:32>)\n| | | EvaluateAsRValue (<test.cc:9:14>)\n| | | EvaluateForOverflow (<test.cc:9:9, col:14>)\n| | | isPotentialConstantExpr (slow_namespace::slow_func)\n| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)\n| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)\n| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)\n| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)\n| ParseDeclarationOrFunctionDefinition (test.cc:16:1)\n| | ParseFunctionDefinition (slow_test)\n| | | EvaluateAsInitializer (slow_value)\n| | | EvaluateAsConstantExpr (<test.cc:17:33, col:59>)\n| | | EvaluateAsConstantExpr (<test.cc:18:11, col:37>)\n| ParseDeclarationOrFunctionDefinition (test.cc:22:1)\n| | EvaluateAsConstantExpr (<test.cc:23:31, col:57>)\n| | EvaluateAsRValue (<test.cc:22:14, line:23:58>)\n| ParseDeclarationOrFunctionDefinition (test.cc:25:1)\n| | EvaluateAsInitializer (slow_init_list)\n| | PerformPendingInstantiations\n"
With diff:
@@ -24,3 +24,3 @@
 | ParseDeclarationOrFunctionDefinition (test.cc:25:1)
 | | EvaluateAsInitializer (slow_init_list)
-| PerformPendingInstantiations\n
+| | PerformPendingInstantiations\n


...

```

</details>
author_association: NONE