Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce Box::default stack copies in debug mode #136089

Merged
merged 2 commits into from
Feb 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion library/alloc/src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1730,7 +1730,20 @@ impl<T: Default> Default for Box<T> {
/// Creates a `Box<T>`, with the `Default` value for T.
#[inline]
fn default() -> Self {
Box::write(Box::new_uninit(), T::default())
let mut x: Box<mem::MaybeUninit<T>> = Box::new_uninit();
unsafe {
// SAFETY: `x` is valid for writing and has the same layout as `T`.
// If `T::default()` panics, dropping `x` will just deallocate the Box as `MaybeUninit<T>`
// does not have a destructor.
//
// We use `ptr::write` as `MaybeUninit::write` creates
// extra stack copies of `T` in debug mode.
//
// See https://github.com/rust-lang/rust/issues/136043 for more context.
ptr::write(&raw mut *x as *mut T, T::default());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't the stack frame of ptr::write also involve a stack allocation since it takes the argument by value? A more robust solution would be to use copy_nonoverlapping from the local in Box::default directly to the heap.

Copy link
Contributor Author

@jwong101 jwong101 Jan 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't the stack frame of ptr::write also involve a stack allocation since it takes the argument by value?

From what I've observed, ptr::write doesn't actually create a new alloca, and essentially just calls memcpy directly on the argument(assuming the argument is passed is big enough and not something like a usize). Godbolt. Let me check how we lower the ptr::write intrinsic to make sure of this though.

A more robust solution would be to use copy_nonoverlapping from the local in Box::default directly to the heap.

Unfortunately, we need to also mem::forget1 the actual value after copying it, or create a ManuallyDrop<T>. The mem::forget copy doesn't appear to be eliminated in debug mode, and ManuallyDrop::<T>::default() call copies T::default to an additional alloca on its stack frame. I created two additional functions in the Godbolt link to showcase this codegen behavior.

Footnotes

  1. Technically we can skip this if needs_drop::<T>() is false.

// SAFETY: `x` was just initialized above.
x.assume_init()
}
}
}

Expand Down
28 changes: 28 additions & 0 deletions tests/codegen/box-default-debug-copies.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//@ compile-flags: -Copt-level=0

// Test to make sure that `<Box<T>>::default` does not create too many copies of `T` on the stack.
// in debug mode. This regressed in dd0620b86721ae8cae86736443acd3f72ba6fc32 to
// four `T` allocas.
//
// See https://github.com/rust-lang/rust/issues/136043 for more context.
//
// FIXME: This test only wants to ensure that there are at most two allocas of `T` created, instead
// of checking for exactly two.

#![crate_type = "lib"]

#[allow(dead_code)]
pub struct Thing([u8; 1000000]);

impl Default for Thing {
fn default() -> Self {
Thing([0; 1000000])
}
}

// CHECK-COUNT-2: %{{.*}} = alloca {{.*}}1000000
// CHECK-NOT: %{{.*}} = alloca {{.*}}1000000
#[no_mangle]
pub fn box_default_single_copy() -> Box<Thing> {
Box::default()
}
Loading