Issue
I have a question about assembly code generated by GCC (-S option). Since, I am new to assembly language and know very little about it, the question will be very primitive. Still, I hope somebody will answer:
Suppose, I have this C code:
main(){
int x = 15;
int y = 6;
int z = x - y;
return 0;
}
If we look at the assembly code (especially the part corresponding to int z = x - y ), we see:
main:
...
subl $16, %esp
movl $15, -4(%ebp)
movl $6, -8(%ebp)
movl -8(%ebp), %eax
movl -4(%ebp), %edx
movl %edx, %ecx
subl %eax, %ecx
movl %ecx, %eax
movl %eax, -12(%ebp)
...
Why doesn't GCC generate something like this, which is less copying things around.
main:
...
movl $15, -4(%ebp)
movl $6, -8(%ebp)
movl -8(%ebp), %edx
movl -4(%ebp), %eax
subl %edx, %eax
movl %eax, -12(%ebp)
...
P.S.
Linux zion-5 2.6.32-21-generic #32-Ubuntu SMP Fri Apr 16 08:10:02 UTC 2010 i686 GNU/Linux gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
Solution
First, as Mysticial commented, you should turn on some optimizations. Try passing -O2
(or -O3
, or just -O1
) to gcc
. If you want to understand more the generated assembly code, also pass -fverbose-asm
. If you want to understand why the code is generated (or not generated), learn GCC internals (perhaps pass also -fdump-tree-all
and -fdump-rtl-all
which produces a big lot of internal dump files).
Some slides on MELT (MELT is a domain specific language to extend GCC) might help and give other references.
You might be surprised by the amount of optimizations GCC can give you, when asked to. By default GCC does not optimize. There are some optimizations which you should explicitly ask for (not even done at -O3
).
Recent versions of GCC probably optimize more than older ones. Current GCC version in 2021 is GCC 11.
PS. I don't work anymore on MELT (abandoned it in 2017). in 2021, see also Bismon, RefPerSys, Frama-C.
Answered By - Basile Starynkevitch