Skip to content

Commit e4bc79d

Browse files
committed
Also get add nuw from uN::checked_add
1 parent a48f3d6 commit e4bc79d

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

core/src/num/uint_macros.rs

+13-2
Original file line numberDiff line numberDiff line change
@@ -455,8 +455,19 @@ macro_rules! uint_impl {
455455
without modifying the original"]
456456
#[inline]
457457
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
458-
let (a, b) = self.overflowing_add(rhs);
459-
if unlikely!(b) { None } else { Some(a) }
458+
// This used to use `overflowing_add`, but that means it ends up being
459+
// a `wrapping_add`, losing some optimization opportunities. Notably,
460+
// phrasing it this way helps `.checked_add(1)` optimize to a check
461+
// against `MAX` and a `add nuw`.
462+
// Per <https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305>,
463+
// LLVM is happy to re-form the intrinsic later if useful.
464+
465+
if unlikely!(intrinsics::add_with_overflow(self, rhs).1) {
466+
None
467+
} else {
468+
// SAFETY: Just checked it doesn't overflow
469+
Some(unsafe { intrinsics::unchecked_add(self, rhs) })
470+
}
460471
}
461472

462473
/// Strict integer addition. Computes `self + rhs`, panicking

0 commit comments

Comments
 (0)