5

In Unsafe Code Guidelines Reference, it says

All interior mutation in Rust has to happen inside an UnsafeCell, so all data structures that have interior mutability must (directly or indirectly) use UnsafeCell for this purpose.

Also, in a discussion about UnsafeCell, it says

UnsafeCell is basically an optimization barrier to the compiler.

It is true that UnsafeCell acts as a compiler optimization barrier in Rust? If yes, which line in the standard library source code emits a barrier and how does it work?

[UPDATE]

The answer of a related question gives a very nice explanation. The TL;DR version is: UnsafeCell<T> is marked with #[lang = "unsafe_cell"] which forces it to be invariant over T.

Now I think this is not very much connected to optimization, but interacts more closely with lifetime analysis.

For the notion of variance in Rust, The Rustonomicon Book gives a detailed explanation.

Zhiyao
  • 4,152
  • 2
  • 12
  • 21
  • @user4815162342 I would like to confirm my understanding. By applying `#[lang = "unsafe_cell"]`, it turns that `Wrapper` is covariant over `T` into that `Wrapper` is invariant over `T`. This is the so-called "barrier". Is it correct? – Zhiyao Jan 19 '21 at 10:28
  • 3
    I'm not following you at all. My understanding is that `UnsafeCell` allows mutable aliasing to the data inside. The `lang = "unsafe_cell"` is the internal way how the standard library communicates to the compiler that it should disable the aliasing assumptions normally present. That is the "barrier" - the data is behind a barrier that prohibits normal optimizations based on aliasing rules. – user4815162342 Jan 19 '21 at 11:05
  • 1
    It is true that `#[lang = "unsafe_cell"]` causes `UnsafeCell` to be invariant over `T`, but it's not the invariance that inhibits optimization. Instead, it's because the `T` is mutable through a shared reference that certain optimizations are forbidden. Invariance is about making the type system aware of what you (the programmer) may do with the type; it doesn't relate to optimizations. – trent Jan 19 '21 at 17:13

0 Answers0