Search code examples
cassemblyx86-64inline-assembly

How to manipulating C variable directly (not via register) via inline assembly "incl" instruction in gcc?


I have the following code

#include <stdio.h>

volatile int global_counter = 0;

void increment_counter() {
    for (int i = 0; i < 100000; ++i) {
        //global_counter++;
        asm ("incl %0"
            :"+a"(global_counter)
        );
    }
}

int main() {

    increment_counter();
    printf("Final value of global_counter: %d\n", global_counter);

    return 0;
}

However, gcc with -S -O2 options compiles to the following assembly code

_increment_counter:
LFB1:
    movl    $100000, %edx
    .p2align 4,,10
    .p2align 3
L2:
    movl    _global_counter(%rip), %eax
# 8 "x_test.c" 1
    incl %eax
# 0 "" 2
    subl    $1, %edx
    movl    %eax, _global_counter(%rip)
    jne L2
    ret

It means that the assembly code is compiled to:

    movl    _global_counter(%rip), %eax
    incl %eax
    movl    %eax, _global_counter(%rip)

How can I make it compile to

    incl _global_counter(%rip)

directly without the movl instruction?

Is it possible to make the gcc inline assembly to use the incl instruction directly on the memory, without using the register eax?


Solution

  • I am the OP. Sorry for my fault. It should be "+m" instead of "+a" for using the memory instead of register.

    I modified the code to:

            asm ("incl %0":"+m"(global_counter));
    

    Problem solved.