Re: [PATCH v2] tools: memory-model: Make plain accesses carry dependencies

From: stern@xxxxxxxxxxxxxxxxxxx
Date: Thu Dec 08 2022 - 16:37:48 EST


On Tue, Dec 06, 2022 at 12:52:47PM -0800, Boqun Feng wrote:
> On Tue, Dec 06, 2022 at 12:46:58PM -0800, Boqun Feng wrote:
> > Thank you, Alan! One question though, can a "smart" compiler optimize
> > out the case below, with the same logic?
> >
> > void P0(int *x, int *y, int *a)
> > {
> > int r1, r2;
> >
> > r1 = READ_ONCE(*x); // A
> >
> > *a = r1 & 0xffff; // B
> >
> > r2 = *a & 0xffff0000; // C
> >
> > WRITE_ONCE(*y, r2); // D
> >
> > }
> >
> > I think we have A ->data B ->rfi C ->data D, however a "smart" compiler
> > can figure out that r2 is actually zero, right? And the code get
> > optimized to:
> >
> > r1 = READ_ONCE(*x);
> > r2 = 0;
> > WRITE_ONCE(*y, r2);
> > *a = r1 & 0xffff;
> >
> > and break the dependency.

Yes, that could happen.

> > I know that our memory model is actually unware of the differences of
> > syntatics dependencies vs semantics syntatics, so one may argue that in
> > the (data; rfi) example above the compiler optimization is outside the
> > scope of LKMM, but won't the same reasoning apply to the (addr; rfi)
> > example from you? The WRITE_ONCE() _syntatically_ depends on load of
> > a[r1], therefore even a "smart" compiler can figure out the value, LKMM
>
> I guess it should be that r2 (i.e. the load of a[r1]) _syntatically_
> depends on the value of r1.

Yes. But more to the point, the LKMM already has this problem for
ordinary dependencies. If you do:

r1 = READ_ONCE(*x);
r2 = r1 & 0x0000ffff;
r3 = r2 & 0xffff0000;
WRITE_ONCE(*y, r3);

then the LKMM will think there is a dependency (because there is a
_syntactic_ dependency), but the compiler is likely to realize that
there isn't a _semantic_ dependency and will destroy the ordering.

We warn people about this possibility, and the same warning applies to
dependencies carried by plain accesses. So I don't think this is a
reason to object to Jonas's carries-dep relation.

Alan