Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could this assembly be possible?

Tags:

c

x86

gcc

assembly

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

like image 504
Bechma Avatar asked Nov 06 '16 15:11

Bechma


Video Answer


1 Answers

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.
like image 176
zx485 Avatar answered Oct 23 '22 18:10

zx485