In x86 what's difference between “test eax,eax” and “cmp eax,0”

后端 未结 2 1794
慢半拍i
慢半拍i 2020-12-08 13:29

Is test eax, eax more efficient than cmp eax, 0? Is there any case that the test eax, eax is necessary where cmp eax, 0 d

2条回答
  •  渐次进展
    2020-12-08 14:19

    Difference(Theoretical)

    As stated above in comment and accepted answer also that these instructions are almost identical when used this way, but then why there are two instructions in the instruction set if they are same?

    Because they're different if used with different operands. The fact that test same,same works as a compare against zero is just a convenient consequence of how 2's complement and FLAGS work, making it a useful peephole optimization.

    TEST instruction uses AND logic on the bit pairs from both the arg0 and arg1 and can check if a specific bit is set or not, then FLAGS set accordingly. (With the integer result discarded). Just like cmp sets FLAGS from a subtract while discarding the integer result.

    Operation(TEST)

    HTML except from Intel's vol.2 PDF manual

    TEMP ← SRC1 **AND** SRC2;
    SF ← MSB(TEMP);
    IF TEMP=0
        THEN ZF ← 1;
        ELSE ZF ← 0;
    FI:
    
    PF ← BitwiseXNOR(TEMP[0:7]);
    CF ← 0;
    OF ← 0;
    (* AF is undefined *)
    

    Flags Affected

    The OF and CF flags are set to 0. The SF, ZF, and PF flags are set according to the result (see the “Operation” section above). The state of the AF flag is undefined.

    (The TEST operation sets the flags CF and OF to zero. The SF is set to the most significant bit of the result of the AND. If the result is 0, the ZF is set to 1, otherwise set to 0.)


    While CMP instruction uses SUB instruction and subtract arg1 from arg0 and will set CF(Carry Flag) and ZF(Zero Flag) based on given args to CMP instruction, if both are equal(arg1==arg0) then it's obvious that the result will be zero and ZF will be set to 1 and if arg0 > arg1 then no flag will be set(remains 0 for ZF and CF) and if arg0 < arg1 then ZF will remain 0 as they are not equal but CF will be set.

    Operation(CMP)

    temp ← SRC1 − SignExtend(SRC2); 
    ModifyStatusFlags; 
       (* Modify status flags in  the same manner as the SUB instruction*)
    

    Flags Affected

    The CF, OF, SF, ZF, AF, and PF flags are set according to the result.

    Reference from: assembly_language_for_x86_processors.pdf

提交回复
热议问题