开发者

GCC generated assembly equivalent to continue statement in C

开发者 https://www.devze.com 2022-12-21 08:40 出处:网络
When a continue statement is used inside a loop in C code, GCC creates a new label with a nop instruction right before the end of the loop block and jumps to it, rather than jump to the end of the loo

When a continue statement is used inside a loop in C code, GCC creates a new label with a nop instruction right before the end of the loop block and jumps to it, rather than jump to the end of the loop block itself. For instance, the following C code

for (i=0; i<10; i++) {
    puts("blah\n");
    if (i < 10) continue;
    puts("This shouldn't be printed.\n");
}

produces the following ASM equivalent (using gcc -S ):

    movl    $0, 28(%esp)
    jmp L2
L5:
    movl    $LC0, (%esp)
    call    _puts
    cmpl    $9, 28(%esp)
    jle L7
L3:
    movl    $LC1, (%esp)
    call    _puts
    jmp L4
L7:
    nop
L4:
    incl    28(%esp)
L2:
    cmpl    $9, 28(%esp)
    jle L5

(The if (i<10) part is inserted so that the compiler doesn't "optimize" the section by removing whatever follows the continue statement)

My question is, why not jump directly to 开发者_如何转开发L4 instead? IMO we could just as well jump to L4, am I missing something?


What you're describing is an optimization. Surely enough, if you tell gcc to optimize (-O1 is enough), it'll do exactly what you describe.


My guess is that it's a placeholder for some kind of skipped-code fixup sequence. Perhaps the nop is sometimes replaced with instructions to store registers to the stack or some such.

But to get more evidence for this, it would help to find an example where the nop is replaced with something else.

0

精彩评论

暂无评论...
验证码 换一张
取 消