From bca0c5f2a939999dcb8d83d06a793f39f4815736 Mon Sep 17 00:00:00 2001 From: burlinchen Date: Fri, 9 Aug 2024 11:10:30 +0800 Subject: [PATCH 1/2] fix: Ensure `Guard`'s `drop` method is removed at `opt-level=s` for `Copy` types Added `#[inline]` to the `drop` method in the `Guard` implementation to ensure that the method is removed by the compiler at optimization level `opt-level=s` for `Copy` types. This change aims to align the method's behavior with optimization expectations and ensure it does not affect performance. --- library/core/src/array/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 5c826b9993f86..61c713c9e81cf 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -889,6 +889,7 @@ impl Guard<'_, T> { } impl Drop for Guard<'_, T> { + #[inline] fn drop(&mut self) { debug_assert!(self.initialized <= self.array_mut.len()); From 3dc083dfd80d0436560c34c41be815b88510ffdc Mon Sep 17 00:00:00 2001 From: burlinchen Date: Sat, 10 Aug 2024 10:44:24 +0800 Subject: [PATCH 2/2] test(std): Add codegen test for array::from_fn optimization This commit adds a new test file 'array-from_fn.rs' to the codegen test suite. The test checks the behavior of std::array::from_fn under different optimization levels: 1. At opt-level=0 (debug build), it verifies that the core::array::Guard is present in the generated code. 2. At opt-level=s (size optimization), it ensures that the Guard is optimized out. This test helps ensure that the compiler correctly optimizes array::from_fn calls in release builds while maintaining safety checks in debug builds. --- tests/codegen/array-from_fn.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 tests/codegen/array-from_fn.rs diff --git a/tests/codegen/array-from_fn.rs b/tests/codegen/array-from_fn.rs new file mode 100644 index 0000000000000..7202d0c67e690 --- /dev/null +++ b/tests/codegen/array-from_fn.rs @@ -0,0 +1,13 @@ +//@ revisions: NORMAL OPT +//@ [NORMAL] compile-flags: -C opt-level=0 -C debuginfo=2 +//@ [OPT] compile-flags: -C opt-level=s -C debuginfo=0 + +#![crate_type = "lib"] +#![feature(array_from_fn)] + +#[no_mangle] +pub fn iota() -> [u8; 16] { + // OPT-NOT: core..array..Guard + // NORMAL: core..array..Guard + std::array::from_fn(|i| i as _) +}