Auto merge of #63635 - oli-obk:default-slice-dangles, r=eddyb

Do not generate allocations for zero sized allocations

Alternative to https://github.com/rust-lang/rust/issues/62487

r? @eddyb

There are other places where we could do this, too, but that would cause `static FOO: () = ();` to not have a unique address
This commit is contained in:
bors 2019-08-18 13:22:38 +00:00
commit ea52be482a
2 changed files with 33 additions and 8 deletions

View File

@ -333,15 +333,21 @@ impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
offset: Size,
) -> PlaceRef<'tcx, &'ll Value> {
assert_eq!(alloc.align, layout.align.abi);
let init = const_alloc_to_llvm(self, alloc);
let base_addr = self.static_addr_of(init, alloc.align, None);
let llty = self.type_ptr_to(layout.llvm_type(self));
let llval = if layout.size == Size::ZERO {
let llval = self.const_usize(alloc.align.bytes());
unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
} else {
let init = const_alloc_to_llvm(self, alloc);
let base_addr = self.static_addr_of(init, alloc.align, None);
let llval = unsafe { llvm::LLVMConstInBoundsGEP(
self.const_bitcast(base_addr, self.type_i8p()),
&self.const_usize(offset.bytes()),
1,
)};
let llval = self.const_bitcast(llval, self.type_ptr_to(layout.llvm_type(self)));
let llval = unsafe { llvm::LLVMConstInBoundsGEP(
self.const_bitcast(base_addr, self.type_i8p()),
&self.const_usize(offset.bytes()),
1,
)};
self.const_bitcast(llval, llty)
};
PlaceRef::new_sized(llval, layout, alloc.align)
}

View File

@ -0,0 +1,19 @@
// run-pass
#[repr(align(4))]
struct Foo;
static FOO: Foo = Foo;
fn main() {
let x: &'static () = &();
assert_eq!(x as *const () as usize, 1);
let x: &'static Foo = &Foo;
assert_eq!(x as *const Foo as usize, 4);
// statics must have a unique address
assert_ne!(&FOO as *const Foo as usize, 4);
assert_eq!(<Vec<i32>>::new().as_ptr(), <&[i32]>::default().as_ptr());
assert_eq!(<Box<[i32]>>::default().as_ptr(), (&[]).as_ptr());
}