[llvm] 4793c2c - [DAGCombiner][RISCV] Prefer to sext i32 non-negative values (#65984)

via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 12 04:02:39 PDT 2023


Author: Yingwei Zheng
Date: 2023-09-12T19:02:35+08:00
New Revision: 4793c2c3de79236f5cdfed2a4f3c07026f519571

URL: https://github.com/llvm/llvm-project/commit/4793c2c3de79236f5cdfed2a4f3c07026f519571
DIFF: https://github.com/llvm/llvm-project/commit/4793c2c3de79236f5cdfed2a4f3c07026f519571.diff

LOG: [DAGCombiner][RISCV] Prefer to sext i32 non-negative values (#65984)

By default, `DAGCombiner` folds `sext x` to `zext x` when `x` is
non-negative. It will generate redundant `zext` inst seq on riscv64
(typically `slli (srli x, 32), 32`).
godbolt: https://godbolt.org/z/osf6adP1o
This patch applies the transform iff `zext` is **cheaper** than `sext`.

Added: 
    

Modified: 
    llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
    llvm/test/CodeGen/RISCV/aext-to-sext.ll

Removed: 
    


################################################################################
diff  --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
index d917e8c00c4f92a..f574c746142f959 100644
--- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
@@ -13271,7 +13271,8 @@ SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
     return V;
 
   // fold (sext x) -> (zext x) if the sign bit is known zero.
-  if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
+  if (!TLI.isSExtCheaperThanZExt(N0.getValueType(), VT) &&
+      (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
       DAG.SignBitIsZero(N0))
     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
 

diff  --git a/llvm/test/CodeGen/RISCV/aext-to-sext.ll b/llvm/test/CodeGen/RISCV/aext-to-sext.ll
index 6322f84bad0baae..09803012001c26c 100644
--- a/llvm/test/CodeGen/RISCV/aext-to-sext.ll
+++ b/llvm/test/CodeGen/RISCV/aext-to-sext.ll
@@ -1,5 +1,5 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
-; RUN: llc -mtriple=riscv64 -verify-machineinstrs < %s \
+; RUN: llc -mtriple=riscv64 -mattr=+m -verify-machineinstrs < %s \
 ; RUN:   | FileCheck %s -check-prefix=RV64I
 
 ; Make sure we don't generate an addi in the loop in
@@ -100,3 +100,14 @@ merge:
   %d = zext i32 %b to i64
   ret i64 %d
 }
+
+; We prefer to sign extend i32 non-negative values. The default behavior in
+; DAGCombiner is zero extend. We have a target hook to override it.
+define signext i32 @square(i32 signext %num) {
+; RV64I-LABEL: square:
+; RV64I:       # %bb.0:
+; RV64I-NEXT:    mulw a0, a0, a0
+; RV64I-NEXT:    ret
+  %mul = mul nsw i32 %num, %num
+  ret i32 %mul
+}


        


More information about the llvm-commits mailing list