https://gcc.gnu.org/bugzilla/show_bug.cgi?id=125221
--- 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:fd0911a7aace8da5d62e3530ec0fed0ed25d079e commit r17-6556-gfd0911a7aace8da5d62e3530ec0fed0ed25d079e Author: Shivam Gupta <[email protected]> Date: Sat Nov 21 08:07:30 2026 -0700 [PATCH v3] match.pd: Narrow popcount when operand fits in a narrower type [PR125221] If the value range of a popcount argument shows that it fits in a narrower unsigned type, convert the argument to that type and call the popcount function for it. This lets the target use a cheaper popcount, for example a 32-bit one for a 64-bit value that is known to be below 2^32. The function is chosen from the narrowed type: IFN_POPCOUNT if the target supports it for that type, otherwise __builtin_popcount (32 bits) or __builtin_popcountll (64 bits). The builtins are used only when the original type is wider than a word and has no popcount of its own, since libgcc has no popcount routine narrower than a word on most targets. Wide arguments such as __int128 and _BitInt are narrowed to 32, 64 or 128 bits, up to MAX_FIXED_MODE_SIZE. Changes since v2: * Restrict the __builtin_popcount / __builtin_popcountll fallback to types wider than a word that have no popcount of their own, as in popcount (zext (X)) (addressed sashiko LLM review comment - 20261115121407.2749144-1-Shivam98.tkg%40gmail.com) * Limit popcountll-narrow.c to targets with a popcount optab (aarch64, and x86 with -mpopcnt), and scan only for .POPCOUNT. * Limit popcountg-narrow-bitint.c to 64-bit aarch64 and x86_64. Changes since v1: * Fix the narrowed call. v1 reused the matched variant, so __builtin_popcountll could receive an unsigned int. v2 picks IFN_POPCOUNT, __builtin_popcount or __builtin_popcountll from the narrowed type, as popcount (zext (X)) does. * Also narrow to 64 and 128 bits where the target has an IFN_POPCOUNT for that type, covering __int128 and _BitInt. * Tests: accept both __builtin_popcount and .POPCOUNT, and add a scan that no narrowed value reaches __builtin_popcountll. Add _BitInt and aarch64 128-bit tests. Bootstrapped and tested on x86_64-linux-gnu. PR tree-optimization/125221 gcc/ChangeLog: * gimple-match-head.cc: Include vr-values.h. * match.pd (POPCOUNT): Narrow the argument when its value range fits in a narrower unsigned type. gcc/testsuite/ChangeLog: * gcc.dg/popcountll-narrow.c: New test. * gcc.dg/popcountg-narrow-bitint.c: New test. * gcc.target/aarch64/popcountg-narrow-128.c: New test. Signed-off-by: Shivam Gupta <[email protected]>
