gccとprintf

http://d.hatena.ne.jp/kohtani/20061204/p1より。へ〜そうなんだ〜と感心しました。僕も実際に手を動かして確認してみました。

$ gcc --version
gcc (GCC) 3.4.4 (cygming special) (gdc 0.12, using dmd 0.125)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ cat a.c
#include <stdio.h>

int
main(int argc, char *argv[])
{
    char str[] = "hoge";

    printf("string\n");
    printf("%s\n", str);
    printf("\n");

    return 0;
}
$ gcc -S -O1 a.c -o-               ← 最適化あり。
...
_main:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $40, %esp
        andl    $-16, %esp
        movl    $16, %eax
        call    __alloca
        call    ___main
        movl    LC0, %eax
        movl    %eax, -24(%ebp)
        movzbl  LC0+4, %eax
        movb    %al, -20(%ebp)
        movl    $LC1, (%esp)
        call    _puts              ← putsになってる。
        leal    -24(%ebp), %eax
        movl    %eax, (%esp)
        call    _puts              ← putsになってる。
        movl    $10, (%esp)
        call    _putchar           ← putcharになってる。
        movl    $0, %eax
        leave
        ret
...
$ gcc -S -O0 a.c -o-               ← 最適化なし。
...
_main:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $56, %esp
        andl    $-16, %esp
        movl    $0, %eax
        addl    $15, %eax
        addl    $15, %eax
        shrl    $4, %eax
        sall    $4, %eax
        movl    %eax, -28(%ebp)
        movl    -28(%ebp), %eax
        call    __alloca
        call    ___main
        movl    LC0, %eax
        movl    %eax, -24(%ebp)
        movzbl  LC0+4, %eax
        movb    %al, -20(%ebp)
        movl    $LC1, (%esp)
        call    _printf            ← printfのまま。
        leal    -24(%ebp), %eax
        movl    %eax, 4(%esp)
        movl    $LC2, (%esp)
        call    _printf            ← printfのまま。
        movl    $LC3, (%esp)
        call    _printf            ← printfのまま。
        movl    $0, %eax
        leave
        ret
...