Skip to content

Commit ea52be4

Browse files
committed
Auto merge of #63635 - oli-obk:default-slice-dangles, r=eddyb
Do not generate allocations for zero sized allocations Alternative to #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
2 parents 71e2882 + 1ea88a8 commit ea52be4

File tree

2 files changed

+34
-9
lines changed

2 files changed

+34
-9
lines changed

src/librustc_codegen_llvm/common.rs

+15-9
Original file line numberDiff line numberDiff line change
@@ -333,15 +333,21 @@ impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
333333
offset: Size,
334334
) -> PlaceRef<'tcx, &'ll Value> {
335335
assert_eq!(alloc.align, layout.align.abi);
336-
let init = const_alloc_to_llvm(self, alloc);
337-
let base_addr = self.static_addr_of(init, alloc.align, None);
338-
339-
let llval = unsafe { llvm::LLVMConstInBoundsGEP(
340-
self.const_bitcast(base_addr, self.type_i8p()),
341-
&self.const_usize(offset.bytes()),
342-
1,
343-
)};
344-
let llval = self.const_bitcast(llval, self.type_ptr_to(layout.llvm_type(self)));
336+
let llty = self.type_ptr_to(layout.llvm_type(self));
337+
let llval = if layout.size == Size::ZERO {
338+
let llval = self.const_usize(alloc.align.bytes());
339+
unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
340+
} else {
341+
let init = const_alloc_to_llvm(self, alloc);
342+
let base_addr = self.static_addr_of(init, alloc.align, None);
343+
344+
let llval = unsafe { llvm::LLVMConstInBoundsGEP(
345+
self.const_bitcast(base_addr, self.type_i8p()),
346+
&self.const_usize(offset.bytes()),
347+
1,
348+
)};
349+
self.const_bitcast(llval, llty)
350+
};
345351
PlaceRef::new_sized(llval, layout, alloc.align)
346352
}
347353

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// run-pass
2+
3+
#[repr(align(4))]
4+
struct Foo;
5+
6+
static FOO: Foo = Foo;
7+
8+
fn main() {
9+
let x: &'static () = &();
10+
assert_eq!(x as *const () as usize, 1);
11+
let x: &'static Foo = &Foo;
12+
assert_eq!(x as *const Foo as usize, 4);
13+
14+
// statics must have a unique address
15+
assert_ne!(&FOO as *const Foo as usize, 4);
16+
17+
assert_eq!(<Vec<i32>>::new().as_ptr(), <&[i32]>::default().as_ptr());
18+
assert_eq!(<Box<[i32]>>::default().as_ptr(), (&[]).as_ptr());
19+
}

0 commit comments

Comments
 (0)