简体   繁体   中英

NASM Difference between CMP and OR

I got 2 questions. The first one: what is the difference between 'or' and 'cmp'? I have seen both, and it seems like they do the same thing. My second question: what does

or al, al

mean? Should it not return true all the time (like x == x)?

Actually, assembly doesn't work as simply as return true . Generally speaking, conditional execution is usually based on a status register. I will use Intel x86 architecture in this explanation. Note that other architectures are different, but the basic principle stays as far as I know.

As mentioned before, the flow of the program is determined by status register, named FLAGS on x86 ( http://en.wikipedia.org/wiki/FLAGS_register ). As you can see there is for example ZF (zero flag) bit. In case when conditional instruction such as jz or jnz is executed, the ZF is checked and the jump is executed (or not) based on this state.

The FLAGS register is updated as the code is being executed, each instruction setting some (sometimes none) bits to appropriate values. This data can be read in appropriate manuals for the given architecture. On x86 for example, add instruction alters CF (carry flag).

If you look up or instruction, it updates FLAGS like this: "The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result." ( http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf#G5.251049 ).

Therefore, the

or al, al

code's functionality is based on whatever conditional instruction follows. It has no meaning standing alone as x |= x (in C-like languages) has basically no effect on the value but has a side-effect on the status register.

From what we could read, we could for example use

or al, al
jnz _someWhere

in order to decide whether the contents of al register are nonzero and in case it is, jump to _someWhere .

For an explanation of reasoning for using test al, al instead of cmp al, 0 or or al,al (all of which set FLAGS identically), I suggest reading Peter Cordes' excellent writeup at Test whether a register is zero with CMP reg,0 vs OR reg,reg?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM