title: Is `UnsafeCell` a compiler optimization barrier in Rust?
body: <p>In <a href="https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#interior-mutability" rel="nofollow noreferrer">Unsafe Code Guidelines Reference</a>, it says</p>
  <blockquote>
  <p>All interior mutation in Rust has to happen inside an <code>UnsafeCell</code>, so all data structures that have interior mutability must (directly or indirectly) use <code>UnsafeCell</code> for this purpose.</p>
  </blockquote>
  <p>Also, in a <a href="https://users.rust-lang.org/t/unsafecell-what-exactly-does-it-do-and-when-do-i-need-it/17471" rel="nofollow noreferrer">discussion about <code>UnsafeCell</code></a>, it says</p>
  <blockquote>
  <p><code>UnsafeCell</code> is basically an optimization barrier to the compiler.</p>
  </blockquote>
  <p>It is true that <code>UnsafeCell</code> 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?</p>
  <p>[UPDATE]</p>
  <p>The <a href="https://stackoverflow.com/questions/43210387/is-this-error-due-to-the-compilers-special-knowledge-about-refcell">answer of a related question</a> gives a very nice explanation. The TL;DR version is: <code>UnsafeCell&lt;T&gt;</code> is marked with <code>#[lang = &quot;unsafe_cell&quot;]</code> which forces it to be invariant over <code>T</code>.</p>
  <p>Now I think this is not very much connected to optimization, but interacts more closely with lifetime analysis.</p>
  <p>For the notion of variance in Rust, <a href="https://doc.rust-lang.org/nomicon/subtyping.html" rel="nofollow noreferrer">The Rustonomicon Book</a> gives a detailed explanation.</p>