Re: [WIP 0/3] Memory model and atomic API in Rust

comex
2024-03-27T21:56:30Z

> On Mar 27, 2024, at 2:21 PM, Boqun Feng <boqun.feng@gmail.com> wrote:
>
> I don't know whether I'm 100% correct on this, but Rust has references,
> so things like "you have a unique reference to a part of memory, no one
> would touch it in the meanwhile" are represented by `&mut`, to get a
> `&mut` from a raw pointer, you need unsafe, where programmers can
> provide the reasoning of the safety of the accesses. More like "pointers
> can alias anyone but references cannot" to me.

Right. When I said “strict aliasing” I meant type-based aliasing rules, which is what GCC calls “strict aliasing". But Rust does have stricter aliasing rules than C in a different way. Both mutable and immutable references are annotated with LLVM `noalias` by default, equivalent to C `restrict`. For mutable references it’s justified because those references should be unique. For immutable references it's justified because the memory behind the reference shouldn’t be mutated at all. (There’s an exception for types with ‘interior mutability’, where ‘immutable' references actually can be used for mutation.)

The hope has always been that this gives Rust better overall optimizability than C or C++ and makes up for the losses from the lack of type-based aliasing rules. If there’s any empirical data to justify or refute this, I’m not aware of it. But that’s the hope, and by this point Rust is committed to the approach.

(Why only function parameters? Mainly because of limitations of what LLVM IR can express. From the perspective of the work-in-progress Rust memory model spec, function parameters are special in *some* ways, but many of the optimizations could apply to all uses of references. That's just not currently implemented.)