GCC — asm goto

Author:Wojciech Muła
Added on:2014-03-09

Starting from GCC 4.5 the asm statement has new form: asm goto. A programmer can use any label from a C/C++ program, however a output from this block is not allowed.

Using an asm block in an old form requires more instructions and an additional storage:

uint32_t bit_set;
asm (
       "bt %2, %%eax  \n"
       "setc %%al  \n"
       "movzx %%al, %%eax \n"
       : "=a" (bit_set)
       : "a" (number), "r" (bit)
       : "cc"

if (bit_set)
       goto has_bit;

Above code is compiled to:

80483f6:       0f a3 d8                bt     %ebx,%eax
80483f9:       0f 92 c0                setb   %al
80483fc:       0f b6 c0                movzbl %al,%eax
80483ff:       85 c0                   test   %eax,%eax
8048401:       74 16                   je     8048419

With asm goto the same task could be writting shorter and easier:

asm goto (
       "bt %1, %0 \n"
       "jc %l[has_bit] \n"

       : /* no output */
       : "r" (number), "r" (bit)
       : "cc"
       : has_bit // name of label

Complete demo is available. See also GCC documentation about Extended Asm.