[llvm] [NVPTX] Lower -1/x to neg.f64(recp.rn.f64) instead of fdiv (PR #98343)

via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 10 09:17:52 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-nvptx

Author: Rajat Bajpai (rajatbajpai)

<details>
<summary>Changes</summary>

The NVPTX backend lowers 1/x to rcp.rn.f64 instruction instead of slower fdiv instruction. However, in the case of -1/x, it uses the slower fdiv instruction. After this change, -1/x will be lowered into neg.f64 (rcp.rn.f64).

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


2 Files Affected:

- (modified) llvm/lib/Target/NVPTX/NVPTXInstrInfo.td (+14) 
- (added) llvm/test/CodeGen/NVPTX/rcp-opt.ll (+13) 


``````````diff
diff --git a/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td b/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
index 827febe845a4c..4183d6ac2537c 100644
--- a/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
+++ b/llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
@@ -1150,6 +1150,16 @@ def DoubleConst1 : PatLeaf<(fpimm), [{
   return &N->getValueAPF().getSemantics() == &llvm::APFloat::IEEEdouble() &&
          N->getValueAPF().convertToDouble() == 1.0;
 }]>;
+// Constant -1.0 (double)
+def DoubleConstNeg1 : PatLeaf<(fpimm), [{
+  return &N->getValueAPF().getSemantics() == &llvm::APFloat::IEEEdouble() &&
+         N->getValueAPF().convertToDouble() == -1.0;
+}]>;
+// Constant -1.0 -> 1.0 (double)
+def NegDoubleConst : SDNodeXForm<fpimm, [{
+  return CurDAG->getTargetConstantFP(-(N->getValueAPF()),
+                                     SDLoc(N), MVT::f64);
+}]>;
 
 // Loads FP16 constant into a register.
 //
@@ -1225,6 +1235,10 @@ def FDIV64ri :
             "div.rn.f64 \t$dst, $a, $b;",
             [(set Float64Regs:$dst, (fdiv Float64Regs:$a, fpimm:$b))]>;
 
+// fdiv -1.0, X => fneg (rcp.rn X)
+def : Pat<(fdiv DoubleConstNeg1:$a, Float64Regs:$b),
+          (FNEGf64 (FDIV641r (NegDoubleConst node:$a), Float64Regs:$b))>;
+
 //
 // F32 Approximate reciprocal
 //
diff --git a/llvm/test/CodeGen/NVPTX/rcp-opt.ll b/llvm/test/CodeGen/NVPTX/rcp-opt.ll
new file mode 100644
index 0000000000000..889ba63610881
--- /dev/null
+++ b/llvm/test/CodeGen/NVPTX/rcp-opt.ll
@@ -0,0 +1,13 @@
+; RUN: llc < %s -march=nvptx64 | FileCheck %s
+; RUN: %if ptxas %{ llc < %s -march=nvptx64 | %ptxas-verify %}
+
+;; Check if fdiv -1, X lowers to fneg (rcp.rn X).
+
+; CHECK-LABEL: .func{{.*}}test1
+define double @test1(double %in) {
+; CHECK: rcp.rn.f64 [[RCP:%.*]], [[X:%.*]];
+; CHECK-NEXT: neg.f64 [[FNEG:%.*]], [[RCP]];
+  %div = fdiv double 1.000000e+00, %in
+  %neg = fsub double -0.000000e+00, %div
+  ret double %neg
+}

``````````

</details>


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


More information about the llvm-commits mailing list