Skip to content

[AMDGPU] Handle negated f16 and fp conversion DAG combines - #213202

Open
HalfBloodPrince010 wants to merge 2 commits into
llvm:mainfrom
HalfBloodPrince010:amdgpu-negated-fp-conversions
Open

HalfBloodPrince010 wants to merge 2 commits into
llvm:mainfrom
HalfBloodPrince010:amdgpu-negated-fp-conversions

Conversation

@HalfBloodPrince010

Copy link
Copy Markdown

Issues

#177448

Description

Add changes to teach AMDGPU getNegatedExpressions to handle f16 conversion nodes while avoiding the source modifier regressions for existing users. In particular preserve profitable subtract forms instead of pushing negation into the f16 conversion.

Handles the following cases

Generic Conversion

For,

FP16_TO_FP

The input is raw half encoding, so negation can be represented by flipping the sign bit (X ^ 0x8000)

FP_TO_FP16

Input is already a floating point value (FP) so negate the source (FNEG X)

Source Modifier Profitability Checks

Do not convert if any users has source modifier, for example if its FSUB. Also, teach the source-modifier profitability check to look through the legalization bitcast used around f16 conversion values. For example, FMUL which doesn't have the souce modifier it does the following even with bitcast:

FP_TO_FP16 X
BITCAST
FNEG
FMUL negated_val, z

When profitable, the negation can be pushed into the conversion:

FP_TO_FP16 (FNEG X)
BITCAST 
FMUL bitcast_val, z

Double Negation

Also handle the double-negation case for FP_TO_FP16:

-(FP_TO_FP16 (fneg X)) -> FP_TO_FP16 X

@github-actions

Copy link
Copy Markdown

Hello @HalfBloodPrince010 👋

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.

  • All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
  • The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
  • Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.

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 questions

How 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 @ followed by their GitHub username.

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,
The LLVM Community

@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-backend-amdgpu

Author: Prashanth (HalfBloodPrince010)

Changes

Issues

#177448

Description

Add changes to teach AMDGPU getNegatedExpressions to handle f16 conversion nodes while avoiding the source modifier regressions for existing users. In particular preserve profitable subtract forms instead of pushing negation into the f16 conversion.

Handles the following cases

Generic Conversion

For,

FP16_TO_FP

The input is raw half encoding, so negation can be represented by flipping the sign bit (X ^ 0x8000)

FP_TO_FP16

Input is already a floating point value (FP) so negate the source (FNEG X)

Source Modifier Profitability Checks

Do not convert if any users has source modifier, for example if its FSUB. Also, teach the source-modifier profitability check to look through the legalization bitcast used around f16 conversion values. For example, FMUL which doesn't have the souce modifier it does the following even with bitcast:

FP_TO_FP16 X
BITCAST
FNEG
FMUL negated_val, z

When profitable, the negation can be pushed into the conversion:

FP_TO_FP16 (FNEG X)
BITCAST 
FMUL bitcast_val, z

Double Negation

Also handle the double-negation case for FP_TO_FP16:

-(FP_TO_FP16 (fneg X)) -> FP_TO_FP16 X

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

2 Files Affected:

  • (modified) llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp (+51)
  • (added) llvm/test/CodeGen/AMDGPU/fneg-f16-conversions.ll (+94)
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp b/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp
index 962988ff97e39..e26836f198510 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp
@@ -21,7 +21,9 @@
 #include "SIMachineFunctionInfo.h"
 #include "llvm/CodeGen/Analysis.h"
 #include "llvm/CodeGen/GlobalISel/GISelValueTracking.h"
+#include "llvm/CodeGen/ISDOpcodes.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
+#include "llvm/CodeGen/SelectionDAGNodes.h"
 #include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/Support/CommandLine.h"
@@ -788,6 +790,21 @@ bool AMDGPUTargetLowering::allUsesHaveSourceMods(const SDNode *N,
 
   // XXX - Should this limit number of uses to check?
   for (const SDNode *U : N->users()) {
+    if(U->getOpcode() == ISD::BITCAST && N->getOpcode() == ISD::FP_TO_FP16) {
+      for(const SDNode *BU : U->users()) {
+        if(!hasSourceMods(BU)) {
+          return false;
+        }
+
+        if (!opMustUseVOP3Encoding(BU, VT)) {
+          if (++NumMayIncreaseSize > CostThreshold)
+            return false;
+        }
+      }
+
+      continue;
+    }
+
     if (!hasSourceMods(U))
       return false;
 
@@ -940,6 +957,40 @@ SDValue AMDGPUTargetLowering::getNegatedExpression(
       return SDValue();
     break;
   }
+  case ISD::FP16_TO_FP: {
+    // If the Users of the Op can handle the negation, defer it for that Op
+    // and do not handle the conversion
+    if (allUsesHaveSourceMods(Op.getNode()))
+      return SDValue();
+
+    SDValue Src = Op.getOperand(0);
+    EVT VT = Op.getValueType();
+    EVT SrcVT = Src.getValueType();
+    SDLoc SL(Op);
+    Cost = NegatibleCost::Neutral;
+    SDValue Negated = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
+                                  DAG.getConstant(0x8000, SL, SrcVT));
+    return DAG.getNode(ISD::FP16_TO_FP, SL, VT, Negated);
+  }
+  case ISD::FP_TO_FP16: {
+    if (allUsesHaveSourceMods(Op.getNode()))
+      return SDValue();
+
+    SDValue Src = Op.getOperand(0);
+    EVT VT = Op.getValueType();
+    EVT SrcVT = Src.getValueType();
+    SDLoc SL(Op);
+
+    if(Src->getOpcode() == ISD::FNEG) {
+      Cost = NegatibleCost::Cheaper;
+      // Negative of Negative is the Source Operand itself
+      // -(FP_TO_FP16(FNEG(X)) = FP_TO_FP16(X)
+      return DAG.getNode(ISD::FP_TO_FP16, SL, VT, Src->getOperand(0));
+    }
+    Cost = NegatibleCost::Neutral;
+    SDValue Negated = DAG.getNode(ISD::FNEG, SL, SrcVT, Src);
+    return DAG.getNode(ISD::FP_TO_FP16, SL, VT, Negated);
+  }
   case AMDGPUISD::RCP: {
     SDValue Src = Op.getOperand(0);
     EVT VT = Op.getValueType();
diff --git a/llvm/test/CodeGen/AMDGPU/fneg-f16-conversions.ll b/llvm/test/CodeGen/AMDGPU/fneg-f16-conversions.ll
new file mode 100644
index 0000000000000..d5ed0ad0d7efb
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/fneg-f16-conversions.ll
@@ -0,0 +1,94 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 6
+
+; RUN: llc -mtriple=amdgcn-amd-amdhsa -mcpu=gfx90a < %s | FileCheck %s
+
+define amdgpu_kernel void @fneg_fpext_half(ptr addrspace(1) %out, ptr addrspace(1) %in) {
+; CHECK-LABEL: fneg_fpext_half:
+; CHECK:       ; %bb.0: ; %entry
+; CHECK-NEXT:    s_load_dwordx4 s[0:3], s[8:9], 0x0
+; CHECK-NEXT:    v_mov_b32_e32 v0, 0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    global_load_ushort v1, v0, s[2:3]
+; CHECK-NEXT:    s_waitcnt vmcnt(0)
+; CHECK-NEXT:    v_cvt_f32_f16_e64 v1, -v1
+; CHECK-NEXT:    global_store_dword v0, v1, s[0:1]
+; CHECK-NEXT:    s_endpgm
+entry:
+  %h = load half, ptr addrspace(1) %in, align 2
+  %f = fpext half %h to float
+  %neg = fneg float %f
+  store float %neg, ptr addrspace(1) %out, align 4
+  ret void
+}
+
+define amdgpu_kernel void @fadd_fptrunc_half_bitcast_user(ptr addrspace(1) %out, ptr addrspace(1) %a, ptr addrspace(1) %b) {
+; CHECK-LABEL: fadd_fptrunc_half_bitcast_user:
+; CHECK:       ; %bb.0: ; %entry
+; CHECK-NEXT:    s_load_dwordx2 s[0:1], s[8:9], 0x10
+; CHECK-NEXT:    v_mov_b32_e32 v0, 0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    global_load_ushort v1, v0, s[0:1]
+; CHECK-NEXT:    s_load_dwordx4 s[0:3], s[8:9], 0x0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    s_load_dword s2, s[2:3], 0x0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    v_cvt_f16_f32_e32 v2, s2
+; CHECK-NEXT:    s_waitcnt vmcnt(0)
+; CHECK-NEXT:    v_sub_f16_e32 v1, v1, v2
+; CHECK-NEXT:    global_store_short v0, v1, s[0:1]
+; CHECK-NEXT:    s_endpgm
+entry:
+  %av = load float, ptr addrspace(1) %a, align 4
+  %bv = load half, ptr addrspace(1) %b, align 2
+  %h = fptrunc float %av to half
+  %neg = fneg half %h
+  %r = fadd half %neg, %bv
+  store half %r, ptr addrspace(1) %out, align 2
+  ret void
+}
+
+define amdgpu_kernel void @fmul_fneg_fptrunc_half(ptr addrspace(1) %out, ptr addrspace(1) %a, ptr addrspace(1) %b) {
+; CHECK-LABEL: fmul_fneg_fptrunc_half:
+; CHECK:       ; %bb.0: ; %entry
+; CHECK-NEXT:    s_load_dwordx2 s[0:1], s[8:9], 0x10
+; CHECK-NEXT:    v_mov_b32_e32 v0, 0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    global_load_ushort v1, v0, s[0:1]
+; CHECK-NEXT:    s_load_dwordx4 s[0:3], s[8:9], 0x0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    s_load_dword s2, s[2:3], 0x0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    v_cvt_f16_f32_e64 v2, -s2
+; CHECK-NEXT:    s_waitcnt vmcnt(0)
+; CHECK-NEXT:    v_mul_f16_e32 v1, v2, v1
+; CHECK-NEXT:    global_store_short v0, v1, s[0:1]
+; CHECK-NEXT:    s_endpgm
+entry:
+  %av = load float, ptr addrspace(1) %a, align 4
+  %bv = load half, ptr addrspace(1) %b, align 2
+  %h = fptrunc float %av to half
+  %neg = fneg half %h
+  %r = fmul half %neg, %bv
+  store half %r, ptr addrspace(1) %out, align 2
+  ret void
+}
+
+define amdgpu_kernel void @fneg_fneg_fpext_half(ptr addrspace(1) %out, ptr addrspace(1) %in) {
+; CHECK-LABEL: fneg_fneg_fpext_half:
+; CHECK:       ; %bb.0: ; %entry
+; CHECK-NEXT:    s_load_dwordx4 s[0:3], s[8:9], 0x0
+; CHECK-NEXT:    v_mov_b32_e32 v0, 0
+; CHECK-NEXT:    s_waitcnt lgkmcnt(0)
+; CHECK-NEXT:    global_load_ushort v1, v0, s[2:3]
+; CHECK-NEXT:    s_waitcnt vmcnt(0)
+; CHECK-NEXT:    v_cvt_f32_f16_e32 v1, v1
+; CHECK-NEXT:    global_store_dword v0, v1, s[0:1]
+; CHECK-NEXT:    s_endpgm
+entry:
+  %h = load half, ptr addrspace(1) %in, align 2
+  %f = fpext half %h to float
+  %neg0 = fneg float %f
+  %neg1 = fneg float %neg0
+  store float %neg1, ptr addrspace(1) %out, align 4
+  ret void
+}

@github-actions

Copy link
Copy Markdown

⚠️ C/C++ code formatter, clang-format found issues in your code. ⚠️

You can test this locally with the following command:
git-clang-format --diff origin/main HEAD --extensions cpp -- llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp --diff_from_common_commit

⚠️
The reproduction instructions above might return results for more than one PR
in a stack if you are using a stacked PR workflow. You can limit the results by
changing origin/main to the base branch/commit you want to compare against.
⚠️

View the diff from clang-format here.
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp b/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp
index e26836f19..09b99f264 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp
@@ -790,9 +790,9 @@ bool AMDGPUTargetLowering::allUsesHaveSourceMods(const SDNode *N,
 
   // XXX - Should this limit number of uses to check?
   for (const SDNode *U : N->users()) {
-    if(U->getOpcode() == ISD::BITCAST && N->getOpcode() == ISD::FP_TO_FP16) {
-      for(const SDNode *BU : U->users()) {
-        if(!hasSourceMods(BU)) {
+    if (U->getOpcode() == ISD::BITCAST && N->getOpcode() == ISD::FP_TO_FP16) {
+      for (const SDNode *BU : U->users()) {
+        if (!hasSourceMods(BU)) {
           return false;
         }
 
@@ -981,7 +981,7 @@ SDValue AMDGPUTargetLowering::getNegatedExpression(
     EVT SrcVT = Src.getValueType();
     SDLoc SL(Op);
 
-    if(Src->getOpcode() == ISD::FNEG) {
+    if (Src->getOpcode() == ISD::FNEG) {
       Cost = NegatibleCost::Cheaper;
       // Negative of Negative is the Source Operand itself
       // -(FP_TO_FP16(FNEG(X)) = FP_TO_FP16(X)

@@ -0,0 +1,94 @@
; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 6

; RUN: llc -mtriple=amdgcn-amd-amdhsa -mcpu=gfx90a < %s | FileCheck %s

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
; RUN: llc -mtriple=amdgcn-amd-amdhsa -mcpu=gfx90a < %s | FileCheck %s
; RUN: llc -mtriple=amdgpu9.0a-amd-amdhsa < %s | FileCheck %s

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gfx90a shouldn't be using these instructions in the first place; it has legal half instructions. This would need to be a gfx6 or gfx7 gpu to use these instructions

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, I will update this.

// XXX - Should this limit number of uses to check?
for (const SDNode *U : N->users()) {
if(U->getOpcode() == ISD::BITCAST && N->getOpcode() == ISD::FP_TO_FP16) {
for(const SDNode *BU : U->users()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably a bad idea to scan over all users, and then further scan all users of a user. Is this part really necessary?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right. I misunderstood, and I was trying to handle BITCAST look through to handle regressions

FP_TO_FP16
BITCAST
FSUB

but its not needed, I will remove that. Thank you.

@HalfBloodPrince010
HalfBloodPrince010 force-pushed the amdgpu-negated-fp-conversions branch from 4b51190 to a1b1858 Compare July 31, 2026 16:57
@HalfBloodPrince010

Copy link
Copy Markdown
Author

Fixed the above comments, and added an additional test.

Comment on lines +956 to +958
SDValue Negated = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
DAG.getConstant(0x8000, SL, SrcVT));
return DAG.getNode(ISD::FP16_TO_FP, SL, VT, Negated);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe the source modifier should fold, so this would be free? Should double check in the test

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was able to verify this case for FP16_TO_FP, legalization replaces FP_EXTEND with FP16_TO_FP, and a later DAG-combine calls getNegatedExpression which hits the FP16_TO_FP switch case, and XOR gets folded in the final assembly. I have added a test for this with fneg and fdiv.

// -(FP_TO_FP16(FNEG(X)) = FP_TO_FP16(X)
return DAG.getNode(ISD::FP_TO_FP16, SL, VT, Src->getOperand(0));
}
Cost = NegatibleCost::Neutral;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same, this should be a source modifier and free. This is the easier case

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For ordinary fptrunc patterns, getNegatedExpression is invoked while the conversion is still represented as FP_ROUND.

However I was able to reach the FP_TO_FP16 switch case with another pattern, but allUsesHaveSourceMods() returned true and the guard prevented the negation from being pushed into the source.

If you have any pointers on an IR pattern that produces FP_TO_FP16 path past this guard, I can try it.

@@ -0,0 +1,117 @@
; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 6
; RUN: llc -mtriple=amdgpu9.0a-amd-amdhsa < %s | FileCheck %s

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
; RUN: llc -mtriple=amdgpu9.0a-amd-amdhsa < %s | FileCheck %s
; RUN: llc -mtriple=amdgpu7-amd-amdhsa < %s | FileCheck %s

This is still testing a target with legal f16, which won't use these nodes. Please recommit the test so we can see the diff from the patch in the second commit

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated this, thanks!

entry:
%h = load half, ptr addrspace(1) %in, align 2
%f = fpext half %h to float
%neg = fneg float %f

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The straightforward pattern probably isn't enough. this needs to be something where the combiner will make a negation change

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a new test case for the FP16_TO_FP case.

@arsenm arsenm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you rebase this so the first commit in the PR adds the tests generated with the baseline checks, and then the diff that demonstrates the patch does anything is in the second commit

Add changes to teach AMDGPU getNegatedExpressions to handle f16
conversion nodes while avoiding the source modifier regressions
for existing users. In particular preserve profitable subtract
forms instead of pushing negation into the f16 conversion.
@HalfBloodPrince010
HalfBloodPrince010 force-pushed the amdgpu-negated-fp-conversions branch from 6e7469f to edbb76e Compare August 3, 2026 01:04
@HalfBloodPrince010

Copy link
Copy Markdown
Author

Can you rebase this so the first commit in the PR adds the tests generated with the baseline checks, and then the diff that demonstrates the patch does anything is in the second commit

Done, I have rebased the changes.

First commit adds the baseline tests/checks, and second commit has my changes along with the updated check.

ret void
}

define amdgpu_kernel void @fadd_fptrunc_half_bitcast_user(ptr addrspace(1) %out, ptr addrspace(1) %a, ptr addrspace(1) %b) {

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The remaining tests ensure there are no regressions after my patch.

@mgcarrasco

Copy link
Copy Markdown
Contributor

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 edbb76ed7f59, we found 3 lines added or modified here that we couldn't find a test for:

  1. EVT SrcVT = Src.getValueType();
  2. Cost = NegatibleCost::Cheaper;

If it makes sense, adding a regression test that validates these lines would be great. And if any of them are already tested and we missed it, we'd love to hear so we can improve the tool. Feel free to give us some feedback on whether this review was useful from your perspective. Thanks!

@HalfBloodPrince010

HalfBloodPrince010 commented Aug 5, 2026 •

Copy link
Copy Markdown
Author

Hi! Thanks! I was able to add end-to-end tests for the FP16_TO_FP path. The baseline commit should have the tests for regression case. I'll take a look.

@HalfBloodPrince010

Copy link
Copy Markdown
Author

Hi @arsenm Good day! I’ve reordered the commits as suggested. Did you get a chance to review the updated changes? Thank you!

@HalfBloodPrince010

Copy link
Copy Markdown
Author

Hi @arsenm, good day! Just following up on this. When you get a chance, could you please take another look at the updated commits? Thank you!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants