简体   繁体   中英

Assembly Code from C program

I have a C program which has a function decod and the function has the following statements.

My decode.c script:

int decod(int x, int y, int z) {
   int ty = y;
   ty = ty - z;
   int py = ty;
   py = py << 31;
   py = py >> 31;
   ty = ty * x;
   py = py ^ ty;
   }

The assembly code of this program (generated by gcc -S decod.c ) shows the following code.

    movl    %edi, -20(%rbp)
movl    %esi, -24(%rbp)
movl    %edx, -28(%rbp)
movl    -24(%rbp), %eax
movl    %eax, -8(%rbp)
movl    -28(%rbp), %eax
subl    %eax, -8(%rbp)
movl    -8(%rbp), %eax
movl    %eax, -4(%rbp)
sall    $31, -4(%rbp)
sarl    $31, -4(%rbp)
movl    -8(%rbp), %eax
imull   -20(%rbp), %eax
movl    %eax, -8(%rbp)
movl    -8(%rbp), %eax
xorl    %eax, -4(%rbp)
popq    %rbp
.cfi_def_cfa 7, 8
ret

But, I want the program generate an assembly file with only the following lines of code.

subl    %edx, %esi
movl    %esi, %eax
sall    $31, %eax
sarl    $31, %eax
imull   %edi, %esi
xorl    %esi, %eax
ret

I know I am pretty close to write a program which will generate the above mentioned code. But, I am clueless why the script generates different assembly code. Any direction will be helpful.

If you compile your function as is, in optimization level3, -O3 the entire function is optimized out. This is because there is no return value and py and ty are anyways discarded after the function.

For reference the code is below

    .globl  decod
    .def    decod;  .scl    2;  .type   32; .endef
    .seh_proc   decod
decod:
    .seh_endprologue
    ret
    .seh_endproc

If however, you add a return py; at the end the code generated is as follows.

    .globl  decod
    .def    decod;  .scl    2;  .type   32; .endef
    .seh_proc   decod
decod:
    .seh_endprologue
    subl    %r8d, %edx
    movl    %edx, %eax
    imull   %edx, %ecx
    sall    $31, %eax
    sarl    $31, %eax
    xorl    %ecx, %eax
    ret
    .seh_endproc

This is functionally identical to what you are expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM