Using a TEST Statement with the Same Case

Here are a few Cs found in the tutorial I'm studying:

... do { ... n--; } while (n > 0) ... 

I assume n is in %edx .

Generated build code:

 testl %edx, %edx jle .L5 

I understand jle tests jle less than or equal to (SF ^ OF) | ZF (SF ^ OF) | ZF . However, I'm not sure how this instruction matches n > 0 . Can anyone explain this?

+6
source share
2 answers

Some of them were covered, but I will tell you a little more.

The general purpose of the test reg,mask command checks the value of the register against the mask (the value of the register is internal AND with the mask), and then sets the status flags SF, ZF and PF in accordance with the result. [EDIT for comment from @ChrisDodd] It also unconditionally clears the status bit O (overflow) and C (carry). [/ EDIT]

 SF = sign flag (1 if sign bit is set (a 2 complement negative value)) ZF = zero flag (1 if result is 0) PF = parity flag (1 if result has an even number of 1 bits) 

In this particular example ( test eax,eax ), the command accepts eax AND eax . When this is done, the bits will be:

 SF = 1 if EAX has a negative value (since sign bit will not change when ANDed with itself) ZF = 1 if EAX is zero (the only value that yields a zero when ANDed with itself is zero) PF = 1 if EAX has an even number of 1 bits 

In other words, this is a simple test for zero or negative. This is a very common compiler code generation pattern.

+12
source

TEST "sets the status flags SF, ZF and PF according to the result." (Intel Manual, near TEST ).

So, SF will reflect if n negative, and ZF will reflect if n zero.

It sets OF to zero.

So, (SF ^ OF)|ZF simplifies to SF | ZF SF | ZF , therefore, in conclusion, the jump will be performed if n <= 0 . This seems wrong, so hopefully .L5 is the label after the loop, not the label before the loop.

+1
source

Source: https://habr.com/ru/post/948419/


All Articles