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

Optimize RcInnerPtr::inc_strong()/inc_weak() instruction count #95224

Merged
merged 3 commits into from
Apr 16, 2022
Merged
Changes from 1 commit
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
34 changes: 24 additions & 10 deletions library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2512,14 +2512,21 @@ trait RcInnerPtr {
fn inc_strong(&self) {
let strong = self.strong();

// We insert an `assume` here to hint LLVM at an otherwise
// missed optimization.
// SAFETY: The reference count will never be zero when this is
// called.
unsafe { core::intrinsics::assume(strong != 0); }

let strong = strong.wrapping_add(1);
self.strong_ref().set(strong);
yaahc marked this conversation as resolved.
Show resolved Hide resolved

// We want to abort on overflow instead of dropping the value.
// The reference count will never be zero when this is called;
// nevertheless, we insert an abort here to hint LLVM at
// an otherwise missed optimization.
if strong == 0 || strong == usize::MAX {
// Checking after the store instead of before allows for
// slightly better code generation.
if core::intrinsics::unlikely(strong == 0) {
mjbshaw marked this conversation as resolved.
Show resolved Hide resolved
abort();
}
self.strong_ref().set(strong + 1);
}

#[inline]
Expand All @@ -2536,14 +2543,21 @@ trait RcInnerPtr {
fn inc_weak(&self) {
let weak = self.weak();

// We insert an `assume` here to hint LLVM at an otherwise
// missed optimization.
// SAFETY: The reference count will never be zero when this is
// called.
unsafe { core::intrinsics::assume(weak != 0); }

let weak = weak.wrapping_add(1);
self.weak_ref().set(weak);

// We want to abort on overflow instead of dropping the value.
// The reference count will never be zero when this is called;
// nevertheless, we insert an abort here to hint LLVM at
// an otherwise missed optimization.
if weak == 0 || weak == usize::MAX {
// Checking after the store instead of before allows for
// slightly better code generation.
if core::intrinsics::unlikely(weak == 0) {
abort();
}
self.weak_ref().set(weak + 1);
}

#[inline]
Expand Down