Rollup merge of #151612 - tgross35:cold-path-doc, r=scottmcm

Update documentation for `cold_path`, `likely`, and `unlikely`

* Add a note recommending benchmarks to `cold_path`, as other hints have
* Note that `cold_path` can be used to implement `likely` and `unlikely`
* Update the tracking issue for the `likely_unlikely` feature

Tracking issue: https://github.com/rust-lang/rust/issues/136873
Tracking issue: https://github.com/rust-lang/rust/issues/151619
This commit is contained in:
Stuart Cook 2026-01-26 19:52:41 +11:00 committed by GitHub
commit 443c5b0742
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -658,7 +658,7 @@ pub const fn must_use<T>(value: T) -> T {
/// }
/// }
/// ```
#[unstable(feature = "likely_unlikely", issue = "136873")]
#[unstable(feature = "likely_unlikely", issue = "151619")]
#[inline(always)]
pub const fn likely(b: bool) -> bool {
crate::intrinsics::likely(b)
@ -708,7 +708,7 @@ pub const fn likely(b: bool) -> bool {
/// }
/// }
/// ```
#[unstable(feature = "likely_unlikely", issue = "136873")]
#[unstable(feature = "likely_unlikely", issue = "151619")]
#[inline(always)]
pub const fn unlikely(b: bool) -> bool {
crate::intrinsics::unlikely(b)
@ -717,6 +717,10 @@ pub const fn unlikely(b: bool) -> bool {
/// Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may
/// choose to optimize paths that are not cold at the expense of paths that are cold.
///
/// Note that like all hints, the exact effect to codegen is not guaranteed. Using `cold_path`
/// can actually *decrease* performance if the branch is called more than expected. It is advisable
/// to perform benchmarks to tell if this function is useful.
///
/// # Examples
///
/// ```
@ -741,6 +745,38 @@ pub const fn unlikely(b: bool) -> bool {
/// }
/// }
/// ```
///
/// This can also be used to implement `likely` and `unlikely` helpers to hint the condition rather
/// than the branch:
///
/// ```
/// #![feature(cold_path)]
/// use core::hint::cold_path;
///
/// #[inline(always)]
/// pub const fn likely(b: bool) -> bool {
/// if !b {
/// cold_path();
/// }
/// b
/// }
///
/// #[inline(always)]
/// pub const fn unlikely(b: bool) -> bool {
/// if b {
/// cold_path();
/// }
/// b
/// }
///
/// fn foo(x: i32) {
/// if likely(x > 0) {
/// println!("this branch is likely to be taken");
/// } else {
/// println!("this branch is unlikely to be taken");
/// }
/// }
/// ```
#[unstable(feature = "cold_path", issue = "136873")]
#[inline(always)]
pub const fn cold_path() {