Bechma Bechma - 1 month ago 15
C Question

How could this assembly be possible?

int sarl_n(int x, char n){
x <<= 2;
x >>= n;
return x;


}

When I assemble with "gcc -m32 -S sarl_n.c", it emits this code:

.cfi_startproc
movl 4(%esp), %eax
movsbl 8(%esp), %ecx
sall $2, %eax
sarl %cl, %eax #This is the part which I don't understand
ret
.cfi_endproc


Why is gcc using the "mini register"
%cl
instead of the big one
%ecx
?

EDIT: I used the O2 option to get shorter assembly code

Answer

The reason why the following line(previous version) in question

sarl    %cl, 8(%ebp)    #This is the part which I don't understand

or (current version)

sarl    %cl, %eax       #This is the part which I don't understand

is using the %cl and not %ecx is, that the SAR opcode only supports the %cl register as an input for a variable arithmetic shift(by %cl times).

See here, and I quote:

SAR r/m32, CL     MC   Valid   Valid   Signed divide* r/m32 by 2, CL times.