Why UnsafeCell<T> is invariant wrt T?

#1

Looking at the definition of

#[lang = "unsafe_cell"]
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
pub struct UnsafeCell<T: ?Sized> {
    value: T,
}

It seems that the only part that enforces the invariance should be related #[lang = "unsafe_cell"]. Is it correct and how can I make sure of that? where’s the root of this perhaps in compiler? any relation with LLVM noalias?

#2

That’s correct - any types you see with #[lang=...] are things the compiler has intrinsic knowledge of. Unclear what “make sure of that” means in light of that - unless the compiler is broken, it’s a sure thing :slight_smile:.

There’s no real relationship to LLVM’s noalias apart from a peripheral one in so far as rustc can** use noalias to mark &mut references, which you can get from a raw ptr in an UnsafeCell.

** - rustc has done this before but each time noalias emission was turned on, some LLVM bugs were uncovered leading to miscompiles. As of today, it’s turned off in rust (unless something’s changed very recently).

2 Likes
#3

Great! thank you for the explanations. Where can I find the definition of attribute #[lang = "unsafe_cell] that enforces this in rustc?

#4

You’ll have to spelunk through the rustc codebase - perhaps starting from here

1 Like
#5

Awesome! thanks a lot. Exactly what I was looking for :blush: