https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63375

--- Comment #16 from Pranith Kumar <bobby.prani at gmail dot com> ---
This is not a good use case(it is a bit twisted, invalid too maybe?), but when
I try to read the stack without aliasing, the volatile write which I performed
is not visible.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

typedef struct {
    int counter;
} atomic_t;

static inline int atomic_read(atomic_t *v)
{
    return (*(volatile int *)&(v)->counter);
}

static inline void atomic_write(atomic_t *v, int val)
{
    v->counter = val;
}

#define smp_mb() asm volatile ("mfence":::"memory")

int i = 0;

int main(int argc, char *argv[])
{
    atomic_t val1 = {2};
    atomic_t val2 = {5};
    int p = 0;

    printf("%p %p\n", &val1, &val2); // try commenting this
    smp_mb();
    p = atomic_read(&val1);
    smp_mb();
    atomic_write(&val2, 9);
    smp_mb();

    printf("%d\n", *(int *)(&val1+4));

    return 0;
}

In the above program, if I comment the first printf() there is no alias for
val2 and the atomic_write() is optimized out and I see 0 printed out in the
second printf(). But without commenting the first printf() the write is issued
because of which I see 9 printed in the second printf.

Reply via email to