asm asm, , ( , ), //clobber .
lea mov / C ( / , asm- , ).
, mov , , . GNU C inline asm , .
BTW, GNU ++ C99, howmany const , . , asm GNU, .
, https://gcc.gnu.org/wiki/DontUseInlineAsm. asm, asm , gcc , inline-asm. asm , ( , ).
%[ptr] %2 %%ebx. , , , , x86 , "r", , "=a" rax/eax/ax/al. . https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html, inline-assembly wiki..
buf_loop%=: , , , .
+ asm output Godbolt
void ext(char *);
int foo(void)
{
int howmany = 5046;
char buffer[howmany];
const char *bufptr = buffer;
unsigned char result;
asm("buf_loop%=: \n\t"
" movb (%[ptr]), %%al \n\t"
" inc %[ptr] \n\t"
" dec %[count] \n\t"
" jnz buf_loop \n\t"
: [res]"=a"(result)
, [count] "+r" (howmany)
, [ptr] "+r" (bufptr)
:
: "memory"
);
return result;
}
%%al , : Extended Asm ( ) %, % asm-. %[res] %0 %al asm-. ( , cbw lodsb - .) result is unsigned char, . , %b[count], .
"memory" clobber, . , , , buffer[] C. ( ).
gcc7.2 -O3 :
pushq %rbp
movl $5046, %edx
movq %rsp, %rbp
subq $5056, %rsp
movq %rsp, %rcx
buf_loop18:
movb (%rcx), %al
inc %rcx
dec %edx
jnz buf_loop
movzbl %al, %eax
leave
ret
, leave asm, , inline asm . , , .
, , asm. . inline GNU Assembler , , , .
C , ++, using .
int bar(unsigned howmany)
{
char buffer[howmany];
buffer[0] = 1;
buffer[100] = 100;
using flexarray_t = const struct {char a; char x[];};
const char *dummy;
unsigned char result;
asm("buf_loop%=: \n\t"
" movb (%[ptr]), %%al \n\t"
" inc %[ptr] \n\t"
" dec %[count] \n\t"
" jnz buf_loop \n\t"
: [res]"=a"(result)
, [count] "+r" (howmany)
, "=r" (dummy)
: [ptr] "2" (buffer)
, "m" (*(flexarray_t *) buffer)
:
);
buffer[100] = 101;
return result;
}
, buffer , , . foo(), const char *bufptr = buffer;, , , C - , . C, , , ( : int dummy .)
Assignments buffer[100] = 100;and buffer[100] = 101;lie in the fact that they both appear in the asm instead be combined into inline-asm (what happens if you do not consider the input operand "m"). IDK, why buffer[100] = 101;not optimized; he is dead, it should be so. Also note that asm volatilethis reordering does not block, so it is not an alternative to clobber "memory"or uses the correct restrictions.