Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does GCC need to clear edx for mysterious reasons?

Consider the following code:

int isqrt(int x) {
    unsigned int r;

    r = x >> 7;

    r += x / r;
    r >>= 1;
    r += x / r;
    r >>= 1;
    r += x / r;
    r >>= 1;

    return r;
}

gcc -O3 isqrt.c -S generates this:

_isqrt:
    pushl   %ebx
    movl    8(%esp), %ecx
    movl    %ecx, %ebx
    sarl    $7, %ebx
    movl    %ecx, %eax
    xorl    %edx, %edx  ; huh?
    divl    %ebx
    addl    %eax, %ebx
    shrl    %ebx
    movl    %ecx, %eax
    xorl    %edx, %edx  ; huh?
    divl    %ebx
    addl    %eax, %ebx
    shrl    %ebx
    movl    %ecx, %eax
    xorl    %edx, %edx  ; huh?
    divl    %ebx
    addl    %ebx, %eax
    shrl    %eax
    popl    %ebx
    ret

Why does it clear %edx for seamingly no reason 3 times?

like image 496
orlp Avatar asked Dec 19 '25 03:12

orlp


1 Answers

divl x divides %edx:%eax by x, so %edx should be something that makes sense (often zero). It also puts the remainder in %edx so it has to be cleared again, not just once.

like image 98
harold Avatar answered Dec 20 '25 17:12

harold