If I compile a program with -O2
optimization, then a any function with math operations is done "inline", without physicall cpu instruction in assembly enter link description here. So having this in c
:
#include <stdio.h>#include <stdlib.h>int f(int a, int b, int c){ return a*b+c;}int main(){ printf("%i\n",f(1,2,4)); return 0;}
And compiled as cc -O2 -fverbose-asm -S a.c
, gas output:
.text .p2align 4,,15 .globl f .type f, @functionf:.LFB22:# a.c:5: return a*b+c; imull %esi, %edi # b, tmp93# a.c:5: return a*b+c; leal (%rdi,%rdx), %eax #, tmp92# a.c:6: } ret .LFE22: .size f, .-f .section .rodata.str1.1,"aMS",@progbits,1.LC0: .string "%i\n" .section .text.startup,"ax",@progbits .p2align 4,,15 .globl main .type main, @functionmain:.LFB23: subq $8, %rsp #,# a.c:8: printf("%i\n",f(1,2,4)); movl $6, %esi # HERE, I can change the value and gcc will not even notice leaq .LC0(%rip), %rdi #, xorl %eax, %eax # call printf@PLT ## a.c:10: } xorl %eax, %eax # addq $8, %rsp # ret .LFE23: .size main, .-main .ident "GCC: (Debian 8.3.0-6) 8.3.0" .section .note.GNU-stack,"",@progbits
Here can you see, the the f
function will not even be called from main. So the function is simply avoided and its return value is calculated somehow in compile time to some instruction cycles. But how is math calculation done in compile-time, when compiler does not directly operate upon CPU, which only does assembly? Or does compiler in compil-time perform some cpu task before compiled to asm? Why is then asm needed, when compiler can directly translate to opcode and execute program without "by-step" of assembler?