How can I set or clear overflow flag in x86 assembly?

前端 未结 3 1830
旧巷少年郎
旧巷少年郎 2020-12-11 07:29

I want to write a simple code (or algorithm) to set/clear overflow flag. For setting OF, I know that I can use signed values. But how can I clear that?

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 07:46

    Provided:

    • you have a register whose content you don't care about,
    • you must to preserve CF-Flag

    Best solution to clear OF (sar):

    Say register is al. (setc only with byte registers r/8)

    ; clear OF-Flag, preserve CF
    setc al
    sar al, 1
    

    Note: this is good because it has no partial flag updates, which may cause stalls. (sar xx, 1 writes all flags, not leaving any unmodified, unlike inc/dec) c.f. Intel Optimization Guide, 3.5.2.6: Partial Flag Register Stalls, but note that modern Intel CPUs don't have partial-flag stalls or flag-merging at all: instructions that read FLAGS just read either or both of CF or the SPAZO group as 2 separate inputs. (That's why cmovbe is still 2 uops on Broadwell and later: it needs CF and ZF. https://uops.info/)

    Source:Intel Documentation SAR p.1234

    General solution (inc/dec):

    Say register is al. (works with r/8, r/16, r/32, r/64)

    ; set OF-Flag, preserve CF
    mov al, 0x7F
    inc al
    
    ; clear OF-Flag, preserve CF
    mov al, 0x0
    inc al
    

    Source:Intel Documentation INC p.551

    Alternatively (adox):

    Different apporach, if you can assume:

    • an adx enabled processor (You check cpu flags with grep adx /proc/cpuinfo)

    Say register is eax. (need r64/r32)

    ; clear OF-Flag, preserve CF
    mov eax, 0x0
    adox eax, eax
    
    ; set OF-Flag, preserve CF
    mov eax, 0xFFFFFFFF
    adox eax, eax 
    

    Note: Don't try to replace mov with xor (or similar) since that will clear CF

    Source:Intel Documentation ADOX p.150

提交回复
热议问题