The best kittens, technology, and video games blog in the world.

Sunday, May 14, 2006

gcc partial redundancy elimination

Compilers are usually a pretty boring subject, but this is really sweet. Take a look at the following snippet and try to guess what will the generated asm code look like (for your convenience, the interesting parts marked with different colors):


#include <stdio.h>

int foo(int i) {
 if(i > 0)
     puts("positive");
 else if (i == 0)
     puts("zero");
 else
     puts("negative");
}
Now look at the actual generated code (colored parts correspond to the colors in C code):

     .file   "puts_pre.c"
     .section        .rodata.str1.1,"aMS",@progbits,1
.LC0:
     .string "positive"
.LC1:
     .string "zero"
.LC2:
     .string "negative"
     .text
     .p2align 4,,15
.globl foo
     .type   foo, @function
foo:
     pushl   %ebp
     movl    %esp, %ebp
     subl    $8, %esp
     cmpl    $0, 8(%ebp)
     jle     .L17
     movl    $.LC0, (%esp)
.L21:
     call    puts
     movl    %ebp, %esp
     popl    %ebp
     ret
     .p2align 4,,7
.L17:
     jne     .L19
     movl    $.LC1, (%esp)
     jmp     .L21
     .p2align 4,,7
.L19:
     movl    $.LC2, (%esp)
     jmp     .L21
     .size   foo, .-foo
     .section        .note.GNU-stack,"",@progbits
     .ident  "GCC: (GNU) 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)"
LOL ZOMG, call to puts has been taken out of the if ^_^

No comments: