Re: Compiler inserts redundant comparison against zero



spamtrap@xxxxxxxxxx wrote:
> I've been led to believe that modern optimising
> compilers are so sharp that it would be a waste
> of time writing my own assembly language code
> for general purposes.
>
> So I was surprised to find out how the C compiler
> I use, described as having "world-class
> optimization, both for speed and size", deals
> with the fragment:
>
> if( x >= 0 && x < 14 )...
>
> which is often encountered, especially in validation
> code (I mean the zero is often met with, the 14 could
> be anything).
>
> The compiler issues these instructions:
>
> test eax, eax ; value of variable x already in eax
> jl condition_false
> cmp eax, 0Eh
> jge condition_false
> condition_true:
> etc
>
> instead of the economical:
>
> cmp eax, 0Eh
> jae condition_false
> condition_true:
> etc
>
> Is this optimisation not well-known?
>

It is well-known. From C code:

extern int y;
void
foo(int x)
{
if( x >= 0 && x < 14 )
y = 1;
}

gcc -O gives:

foo:
pushl %ebp
movl %esp, %ebp
cmpl $13, 8(%ebp)
ja .L1
movl $1, y
..L1:
popl %ebp
ret

this assumes that the target is i386. Works both with new gcc (3.4.3 and
3.3.6) and quite old (2.8.1 and 2.95.3).
If I use -O -march=athlon-xp I get jumpless code:

foo:
pushl %ebp
movl %esp, %ebp
cmpl $13, 8(%ebp)
movl $1, %eax
cmova y, %eax
movl %eax, y
leave
ret


--
Waldek Hebisch
hebisch@xxxxxxxxxxxxxxxx

.



Relevant Pages

  • Re: Compiler inserts redundant comparison against zero
    ... > I've been led to believe that modern optimising ... > So I was surprised to find out how the C compiler ... > test eax, eax; value of variable x already in eax ... > cmp eax, 0Eh ...
    (comp.lang.asm.x86)
  • Compiler inserts redundant comparison against zero
    ... I've been led to believe that modern optimising ... of time writing my own assembly language code ... So I was surprised to find out how the C compiler ... test eax, eax; value of variable x already in eax ...
    (comp.lang.asm.x86)
  • Re: Compiler inserts redundant comparison against zero
    ... > I've been led to believe that modern optimising ... > of time writing my own assembly language code ... > So I was surprised to find out how the C compiler ... > test eax, eax; value of variable x already in eax ...
    (comp.lang.asm.x86)
  • Re: Release Dll Problem - Optimization Issue
    ... If optimising for speed on smaller size processors, ... This limits the compiler in using fast registers for the ... and speeds up access to the variable. ...
    (microsoft.public.pocketpc.developer)
  • Re: C/C++ Compilers Optimization Failed
    ... I used C/C++ Compiler's Optimization. ... >> xor eax, eax ... I am shocked that C/C++ Compiler did not tune optimization very well ...
    (comp.lang.asm.x86)