Question on signed overflow

Andrew Haley aph@redhat.com
Fri Jun 18 10:21:00 GMT 2010


On 06/18/2010 08:56 AM, Georg Lay wrote:
> Hi, I have a question on gcc's signed overflow optimisation in the
> following C function:
> 
> int abssat2 (int x)
> {
>     unsigned int y = x;
> 
>     if (x < 0)
>         y = -y;
> 
>     if (y >= 0x80000000)
>         y--;
> 
>     return y;
> }
> 
> gcc optimises the second comparison and throws it away, and that's the
> part I do not understand because all computations are performed on
> unsigned int which has no undefined behaviour on overflow.
> 
> For the unary - the standard says in 6.5.3.3.3:
>  The result of the unary - operator is the negative of its (promoted)
>  operand. The integer promotions are performed on the operand, and
>  the result has the promoted type.
> 
> And the promotion rules in 6.3.1.1.2:
>   If an int can represent all values of the original type, the value
>   is converted to an int; otherwise, it is converted to an unsigned int.
>   These are called the integer promotions. All other types are unchanged
>   by the integer promotions.
> 
> As an int cannot represent all values that can be represented by an
> unsigned int, there is no signed int in the line y = -y.
> 
> Could anyone explain this? I see this on gcc 4.4.3.

Works for me on gcc 4.4.3:

	movl	%edi, %eax
	sarl	$31, %eax
	xorl	%eax, %edi
	subl	%eax, %edi
	movl	%edi, %eax
	shrl	$31, %eax
	subl	%eax, %edi
	movl	%edi, %eax
	ret

Andrew.



More information about the Gcc-help mailing list