https://gcc.gnu.org/bugzilla/show_bug.cgi?id=123905
--- Comment #3 from GCC Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Jeff Law <[email protected]>: https://gcc.gnu.org/g:5827af4ea1ea11036b336e1029b4a25ca670b594 commit r17-5472-g5827af4ea1ea11036b336e1029b4a25ca670b594 Author: Milan Tripkovic <[email protected]> Date: Wed Oct 21 16:35:53 2026 -0600 PR rtl-optimization/123905 - Failure to optimize away sign extension on RISC-V This patch fixes PR123905, where the compiler generates redundant sign extensions and bit masks on RISC-V when using __builtin_clz, __builtin_ctz and __builtin_popcount. To solve this, the patch introduces the following changes based on Jeff's suggestions: ext-dce.cc: Extract the redundant sign extension check into a new helper function is_trivially_redundant_extension. This uses num_sign_bit_copies evaluated in the outer mode to check if the extension is already redundant, which allows combine to eliminate it instead of ext-dce leaving SUBREGs that are harder to optimize. rtlanal.cc: Improve nonzero_bits1 so that CLZ and CTZ are handled when the operand mode differs from MODE, as long as it is a scalar integer mode, since the result depends on the operand. If the value at zero is not defined, the fallback is the same as before. ASM Before: clzw a0,a0 andn t0,a0,a1 sext.w a0,t0 ret ASM After: clzwââa0,a0 andnââa0,a0,a1 ret Additionally, this patch includes a new test case gcc.target/riscv/pr123905.c which covers several scenarios: AND, ANDN, and combinations like clz & ctz and clz & ctz & popcount. Changes since v4: -Eliminated the redundant num_sign_bit_copies1 handling. -Removed the POPCOUNT change from nonzero_bits1. -nonzero_bits1 keeps the old fallback for CLZ/CTZ, but not for mismatched modes, since the result depends on the operand. Bootstrapped and regression tested on x86_64. Regression tested on riscv64. PR rtl-optimization/123905 gcc/ChangeLog: * ext-dce.cc (is_trivially_redundant_extension): New helper function. (ext_dce_try_optimize_extension): Keep trivially redundant extensions. * rtlanal.cc (nonzero_bits1): Improve CLZ and CTZ handling. gcc/testsuite/ChangeLog: * gcc.target/riscv/pr123905.c: New test case.
