GCC Newspaper
NOVEMBER 30, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
gcc

Make CLZ and CTZ defined for zero when executed unconditionally

Ensures CLZ and CTZ intrinsics produce defined results for zero inputs in unconditional execution contexts.

Previously, GCC’s Value Range Propagation (VRP) incorrectly folded CLZ (count leading zeros) and CTZ (count trailing zeros) intrinsic calls when executed unconditionally, because the result for an input of zero was considered undefined. This led to incorrect optimizations and testsuite failures at higher optimization levels. This commit extends internal rewrite mechanisms to define the behavior of one-argument CLZ/CTZ for zero inputs, ensuring correct results and preventing optimization-related issues.

In Details

The __builtin_ctzg(c, -1) intrinsic, when lowered, typically becomes c != 0 ? __builtin_ctz(c) : -1. If this expression is then if-converted or otherwise executed unconditionally, VRP uses the documented range of __builtin_ctz(c) which is [0, prec - 1], excluding the zero input case. When c is zero, the VRP fold results in an incorrect value, causing test aborts. This patch enhances gimple_needing_rewrite_undefined and rewrite_to_defined_unconditional to handle one-argument CLZ and CTZ calls on integral types. These calls are rewritten to IFN_CLZ(x, val) or IFN_CTZ(x, val),…

For Context
CLZ
Count Leading Zeros. An operation that returns the number of zero bits preceding the most significant set bit in an integer.
CTZ
Count Trailing Zeros. An operation that returns the number of zero bits following the least significant set bit in an integer.
Intrinsic
A built-in function provided by the compiler that often maps directly to a specific machine instruction, offering performance benefits.
VRP
Value Range Propagation. A compiler optimization pass that determines the possible range of values for variables, enabling further optimizations.
SSA
Static Single Assignment form. A program representation where each variable is assigned exactly once. PHI nodes are used to merge values at control flow join points.
if-conversion
A compiler optimization that transforms conditional branches into conditional instructions, allowing more instruction-level parallelism.
Filed Under: optimizationintrinsicsvrp