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)
 else if (i == 0)
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
     .string "positive"
     .string "zero"
     .string "negative"
     .p2align 4,,15
.globl foo
     .type   foo, @function
     pushl   %ebp
     movl    %esp, %ebp
     subl    $8, %esp
     cmpl    $0, 8(%ebp)
     jle     .L17
     movl    $.LC0, (%esp)
     call    puts
     movl    %ebp, %esp
     popl    %ebp
     .p2align 4,,7
     jne     .L19
     movl    $.LC1, (%esp)
     jmp     .L21
     .p2align 4,,7
     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: