about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMark Rousskov <mark.simulacrum@gmail.com>2023-11-23 21:47:08 -0500
committerMark Rousskov <mark.simulacrum@gmail.com>2023-11-23 22:05:45 -0500
commitb81e788d16d9656b9fd8905de9a3f382ccdbb56c (patch)
treee71c4f790e97cb73c3f37c0206f951068d016012
parenta4a5c976fee30bdd350aa0df10b14cb87ade48fe (diff)
downloadrust-b81e788d16d9656b9fd8905de9a3f382ccdbb56c.tar.gz
rust-b81e788d16d9656b9fd8905de9a3f382ccdbb56c.zip
Indicate that multiplication in Layout::array cannot overflow
This allows LLVM to optimize comparisons to zero before & after the
multiplication into one, saving on code size and eliminating an (always
true) branch from most Vec allocations.
-rw-r--r--library/core/src/alloc/layout.rs6
1 files changed, 5 insertions, 1 deletions
diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs
index 65946e09ff9..9ef0a7d7608 100644
--- a/library/core/src/alloc/layout.rs
+++ b/library/core/src/alloc/layout.rs
@@ -450,7 +450,11 @@ impl Layout {
                 return Err(LayoutError);
             }
 
-            let array_size = element_size * n;
+            // SAFETY: We just checked that we won't overflow `usize` when we multiply.
+            // This is a useless hint inside this function, but after inlining this helps
+            // deduplicate checks for whether the overall capacity is zero (e.g., in RawVec's
+            // allocation path) before/after this multiplication.
+            let array_size = unsafe { element_size.unchecked_mul(n) };
 
             // SAFETY: We just checked above that the `array_size` will not
             // exceed `isize::MAX` even when rounded up to the alignment.