Skip to content

Commit

Permalink
Auto merge of #63635 - oli-obk:default-slice-dangles, r=eddyb
Browse files Browse the repository at this point in the history
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
  • Loading branch information
bors committed Aug 18, 2019
2 parents 71e2882 + 1ea88a8 commit ea52be4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/librustc_codegen_llvm/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 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,
)};
self.const_bitcast(llval, llty)
};
PlaceRef::new_sized(llval, layout, alloc.align)
}

Expand Down
19 changes: 19 additions & 0 deletions src/test/ui/consts/zst_no_llvm_alloc.rs
Original file line number Diff line number Diff line change
@@ -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());
}

0 comments on commit ea52be4

Please sign in to comment.