Auto merge of #123936 - Mark-Simulacrum:zst-no-alloc, r=oli-obk

Codegen ZSTs without an allocation

This makes sure that &[] is equivalent to unsafe code (from_raw_parts(dangling, 0)). No new stable guarantee is intended about whether or not we do this, this is just an optimization.

This regressed in #67000 (no comments I can see about that regression in the PR, though it did change the test modified here). We had previously performed this optimization since #63635.
This commit is contained in:
bors 2024-04-17 18:31:10 +00:00
commit 38104f3a88
4 changed files with 63 additions and 27 deletions

View file

@ -6,16 +6,21 @@ struct Foo;
static FOO: Foo = Foo;
fn main() {
// There's no stable guarantee that these are true.
// However, we want them to be true so that our LLVM IR and runtime are a bit faster:
// a constant address is cheap and doesn't result in relocations in comparison to a "real"
// global somewhere in the data section.
let x: &'static () = &();
assert_ne!(x as *const () as usize, 1);
assert_eq!(x as *const () as usize, 1);
let x: &'static Foo = &Foo;
assert_ne!(x as *const Foo as usize, 4);
assert_eq!(x as *const Foo as usize, 4);
// statics must have a unique address
// The exact addresses returned by these library functions are not necessarily stable guarantees
// but for now we assert that we're still matching.
assert_eq!(<Vec<i32>>::new().as_ptr(), <&[i32]>::default().as_ptr());
assert_eq!(<Box<[i32]>>::default().as_ptr(), (&[]).as_ptr());
// statics must have a unique address (see https://github.com/rust-lang/rust/issues/18297, not
// clear whether this is a stable guarantee)
assert_ne!(&FOO as *const Foo as usize, 4);
// FIXME this two tests should be assert_eq!
// this stopped working since we are promoting to constants instead of statics
assert_ne!(<Vec<i32>>::new().as_ptr(), <&[i32]>::default().as_ptr());
assert_ne!(<Box<[i32]>>::default().as_ptr(), (&[]).as_ptr());
}