Re: test eax, eax - why?



On 24 Aug 2006 07:41:06 -0700, spamtrap@xxxxxxxxxx wrote in
comp.lang.asm.x86:

Hi everyone,
I'm trying to learn x86 assembly language, and in addition to reading
the necessary books, trying the programmes etc., I'm also compiling my
own example C code and comparing it with the resultant (Visual C++)
code.

One thing I tried was compiling the "infinite" while(1){ ... } loop. I
got something like this:

mov eax, 1
test eax, eax
je label2

this seems somewhat odd. I know that "test" does a bitwise and of eax
and eax, but in this case, the rest of the
instruction (je) is not carried out. Why bother with this at all? Or
have I got the wrong end of the stick?

The C (or C++) code that you wrote contained the expression
"while(1)". Like all conditional expressions in C (and C++), this is
considered to be false if it evaluates to 0, and true if it evaluates
to any non-zero value.

You instructed the compiler to evaluate whether or not 1 is zero or
non-zero, and in the non-optimizing compiler it generated code to do
so. So you got exactly what you programmed.

Presumably the optimizing compiler would eliminate the test, but of
course VC++ makes it extremely difficult to see the assembly output of
optimized code.

Most likely you will find that if you replace this the defined C
idiom:

for ( ; ; )

....even the non-optimizing compiler will probably not include extra
code.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

.



Relevant Pages

  • 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)
  • Re: missing optimization?
    ... Both, function1 and function2, have duplicated ... > movl _data, %eax ... > subl 4, %eax ... > If compiler is *newer* than 2.95, then it puts the TEST opcode. ...
    (comp.os.msdos.djgpp)
  • Re: C/C++ Compilers Optimization Failed
    ... > xor eax, eax ... If you don't like the code generated by that compiler, ... And why are you complaining in an assembly language newsgroup about ... > (Optimization is not important YET!!) ...
    (comp.lang.asm.x86)
  • Re: compiler generated output
    ... > compiler to generate code which only uses 386 instruction). ... > Thus, while replacing mov/and with movzx, the jump is still there. ... mov eax, ... Software Optimization Guide for ...
    (comp.lang.asm.x86)
  • Re: No need to optimize in assembly anymore
    ... > inlining etc. - precisely the ones that a good compiler will perform. ... Now in MSVC 7.1 it generates a single div. ... mov eax, DWORD PTR _b$ ...
    (alt.lang.asm)