From 669e25597c8244ce4991414a8dfb47869854fda3 Mon Sep 17 00:00:00 2001 From: Joshua Wong Date: Wed, 9 Oct 2024 14:24:05 -0400 Subject: [PATCH 1/2] allocate before calling T::default in >::default() The `Box` impl currently calls `T::default()` before allocating the `Box`. Most `Default` impls are trivial, which should in theory allow LLVM to construct `T: Default` directly in the `Box` allocation when calling `>::default()`. However, the allocation may fail, which necessitates calling `T's` destructor if it has one. If the destructor is non-trivial, then LLVM has a hard time proving that it's sound to elide, which makes it construct `T` on the stack first, and then copy it into the allocation. Create an uninit `Box` first, and then write `T::default` into it, so that LLVM now only needs to prove that the `T::default` can't panic, which should be trivial for most `Default` impls. --- alloc/src/boxed.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/alloc/src/boxed.rs b/alloc/src/boxed.rs index 5f20729568352..3e791416820ef 100644 --- a/alloc/src/boxed.rs +++ b/alloc/src/boxed.rs @@ -1688,7 +1688,7 @@ impl Default for Box { /// Creates a `Box`, with the `Default` value for T. #[inline] fn default() -> Self { - Box::new(T::default()) + Box::write(Box::new_uninit(), T::default()) } } From 8547f513811ade8044296fa8bda487d066c41afd Mon Sep 17 00:00:00 2001 From: Joshua Wong Date: Wed, 9 Oct 2024 14:24:05 -0400 Subject: [PATCH 2/2] allocate before calling T::default in >::default() Same rationale as in the previous commit. --- alloc/src/lib.rs | 1 + alloc/src/sync.rs | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/alloc/src/lib.rs b/alloc/src/lib.rs index c60c0743c7e12..dcfe96be7551d 100644 --- a/alloc/src/lib.rs +++ b/alloc/src/lib.rs @@ -104,6 +104,7 @@ #![feature(async_closure)] #![feature(async_fn_traits)] #![feature(async_iterator)] +#![feature(box_uninit_write)] #![feature(clone_to_uninit)] #![feature(coerce_unsized)] #![feature(const_align_of_val)] diff --git a/alloc/src/sync.rs b/alloc/src/sync.rs index 5d099a49854af..0038750d25dd1 100644 --- a/alloc/src/sync.rs +++ b/alloc/src/sync.rs @@ -3447,7 +3447,13 @@ impl Default for Arc { /// assert_eq!(*x, 0); /// ``` fn default() -> Arc { - Arc::new(Default::default()) + let x = Box::into_raw(Box::write(Box::new_uninit(), ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: T::default(), + })); + // SAFETY: `Box::into_raw` consumes the `Box` and never returns null + unsafe { Self::from_inner(NonNull::new_unchecked(x)) } } }