core/
hint.rs

1#![stable(feature = "core_hint", since = "1.27.0")]
2
3//! Hints to compiler that affects how code should be emitted or optimized.
4//!
5//! Hints may be compile time or runtime.
6
7use crate::marker::Destruct;
8use crate::mem::MaybeUninit;
9use crate::{intrinsics, ub_checks};
10
11/// Informs the compiler that the site which is calling this function is not
12/// reachable, possibly enabling further optimizations.
13///
14/// # Safety
15///
16/// Reaching this function is *Undefined Behavior*.
17///
18/// As the compiler assumes that all forms of Undefined Behavior can never
19/// happen, it will eliminate all branches in the surrounding code that it can
20/// determine will invariably lead to a call to `unreachable_unchecked()`.
21///
22/// If the assumptions embedded in using this function turn out to be wrong -
23/// that is, if the site which is calling `unreachable_unchecked()` is actually
24/// reachable at runtime - the compiler may have generated nonsensical machine
25/// instructions for this situation, including in seemingly unrelated code,
26/// causing difficult-to-debug problems.
27///
28/// Use this function sparingly. Consider using the [`unreachable!`] macro,
29/// which may prevent some optimizations but will safely panic in case it is
30/// actually reached at runtime. Benchmark your code to find out if using
31/// `unreachable_unchecked()` comes with a performance benefit.
32///
33/// # Examples
34///
35/// `unreachable_unchecked()` can be used in situations where the compiler
36/// can't prove invariants that were previously established. Such situations
37/// have a higher chance of occurring if those invariants are upheld by
38/// external code that the compiler can't analyze.
39/// ```
40/// fn prepare_inputs(divisors: &mut Vec<u32>) {
41///     // Note to future-self when making changes: The invariant established
42///     // here is NOT checked in `do_computation()`; if this changes, you HAVE
43///     // to change `do_computation()`.
44///     divisors.retain(|divisor| *divisor != 0)
45/// }
46///
47/// /// # Safety
48/// /// All elements of `divisor` must be non-zero.
49/// unsafe fn do_computation(i: u32, divisors: &[u32]) -> u32 {
50///     divisors.iter().fold(i, |acc, divisor| {
51///         // Convince the compiler that a division by zero can't happen here
52///         // and a check is not needed below.
53///         if *divisor == 0 {
54///             // Safety: `divisor` can't be zero because of `prepare_inputs`,
55///             // but the compiler does not know about this. We *promise*
56///             // that we always call `prepare_inputs`.
57///             unsafe { std::hint::unreachable_unchecked() }
58///         }
59///         // The compiler would normally introduce a check here that prevents
60///         // a division by zero. However, if `divisor` was zero, the branch
61///         // above would reach what we explicitly marked as unreachable.
62///         // The compiler concludes that `divisor` can't be zero at this point
63///         // and removes the - now proven useless - check.
64///         acc / divisor
65///     })
66/// }
67///
68/// let mut divisors = vec![2, 0, 4];
69/// prepare_inputs(&mut divisors);
70/// let result = unsafe {
71///     // Safety: prepare_inputs() guarantees that divisors is non-zero
72///     do_computation(100, &divisors)
73/// };
74/// assert_eq!(result, 12);
75///
76/// ```
77///
78/// While using `unreachable_unchecked()` is perfectly sound in the following
79/// example, as the compiler is able to prove that a division by zero is not
80/// possible, benchmarking reveals that `unreachable_unchecked()` provides
81/// no benefit over using [`unreachable!`], while the latter does not introduce
82/// the possibility of Undefined Behavior.
83///
84/// ```
85/// fn div_1(a: u32, b: u32) -> u32 {
86///     use std::hint::unreachable_unchecked;
87///
88///     // `b.saturating_add(1)` is always positive (not zero),
89///     // hence `checked_div` will never return `None`.
90///     // Therefore, the else branch is unreachable.
91///     a.checked_div(b.saturating_add(1))
92///         .unwrap_or_else(|| unsafe { unreachable_unchecked() })
93/// }
94///
95/// assert_eq!(div_1(7, 0), 7);
96/// assert_eq!(div_1(9, 1), 4);
97/// assert_eq!(div_1(11, u32::MAX), 0);
98/// ```
99#[inline]
100#[stable(feature = "unreachable", since = "1.27.0")]
101#[rustc_const_stable(feature = "const_unreachable_unchecked", since = "1.57.0")]
102#[track_caller]
103pub const unsafe fn unreachable_unchecked() -> ! {
104    ub_checks::assert_unsafe_precondition!(
105        check_language_ub,
106        "hint::unreachable_unchecked must never be reached",
107        () => false
108    );
109    // SAFETY: the safety contract for `intrinsics::unreachable` must
110    // be upheld by the caller.
111    unsafe { intrinsics::unreachable() }
112}
113
114/// Makes a *soundness* promise to the compiler that `cond` holds.
115///
116/// This may allow the optimizer to simplify things, but it might also make the generated code
117/// slower. Either way, calling it will most likely make compilation take longer.
118///
119/// You may know this from other places as
120/// [`llvm.assume`](https://llvm.org/docs/LangRef.html#llvm-assume-intrinsic) or, in C,
121/// [`__builtin_assume`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-assume).
122///
123/// This promotes a correctness requirement to a soundness requirement. Don't do that without
124/// very good reason.
125///
126/// # Usage
127///
128/// This is a situational tool for micro-optimization, and is allowed to do nothing. Any use
129/// should come with a repeatable benchmark to show the value, with the expectation to drop it
130/// later should the optimizer get smarter and no longer need it.
131///
132/// The more complicated the condition, the less likely this is to be useful. For example,
133/// `assert_unchecked(foo.is_sorted())` is a complex enough value that the compiler is unlikely
134/// to be able to take advantage of it.
135///
136/// There's also no need to `assert_unchecked` basic properties of things.  For example, the
137/// compiler already knows the range of `count_ones`, so there is no benefit to
138/// `let n = u32::count_ones(x); assert_unchecked(n <= u32::BITS);`.
139///
140/// `assert_unchecked` is logically equivalent to `if !cond { unreachable_unchecked(); }`. If
141/// ever you are tempted to write `assert_unchecked(false)`, you should instead use
142/// [`unreachable_unchecked()`] directly.
143///
144/// # Safety
145///
146/// `cond` must be `true`. It is immediate UB to call this with `false`.
147///
148/// # Example
149///
150/// ```
151/// use core::hint;
152///
153/// /// # Safety
154/// ///
155/// /// `p` must be nonnull and valid
156/// pub unsafe fn next_value(p: *const i32) -> i32 {
157///     // SAFETY: caller invariants guarantee that `p` is not null
158///     unsafe { hint::assert_unchecked(!p.is_null()) }
159///
160///     if p.is_null() {
161///         return -1;
162///     } else {
163///         // SAFETY: caller invariants guarantee that `p` is valid
164///         unsafe { *p + 1 }
165///     }
166/// }
167/// ```
168///
169/// Without the `assert_unchecked`, the above function produces the following with optimizations
170/// enabled:
171///
172/// ```asm
173/// next_value:
174///         test    rdi, rdi
175///         je      .LBB0_1
176///         mov     eax, dword ptr [rdi]
177///         inc     eax
178///         ret
179/// .LBB0_1:
180///         mov     eax, -1
181///         ret
182/// ```
183///
184/// Adding the assertion allows the optimizer to remove the extra check:
185///
186/// ```asm
187/// next_value:
188///         mov     eax, dword ptr [rdi]
189///         inc     eax
190///         ret
191/// ```
192///
193/// This example is quite unlike anything that would be used in the real world: it is redundant
194/// to put an assertion right next to code that checks the same thing, and dereferencing a
195/// pointer already has the builtin assumption that it is nonnull. However, it illustrates the
196/// kind of changes the optimizer can make even when the behavior is less obviously related.
197#[track_caller]
198#[inline(always)]
199#[doc(alias = "assume")]
200#[stable(feature = "hint_assert_unchecked", since = "1.81.0")]
201#[rustc_const_stable(feature = "hint_assert_unchecked", since = "1.81.0")]
202pub const unsafe fn assert_unchecked(cond: bool) {
203    // SAFETY: The caller promised `cond` is true.
204    unsafe {
205        ub_checks::assert_unsafe_precondition!(
206            check_language_ub,
207            "hint::assert_unchecked must never be called when the condition is false",
208            (cond: bool = cond) => cond,
209        );
210        crate::intrinsics::assume(cond);
211    }
212}
213
214/// Emits a machine instruction to signal the processor that it is running in
215/// a busy-wait spin-loop ("spin lock").
216///
217/// Upon receiving the spin-loop signal the processor can optimize its behavior by,
218/// for example, saving power or switching hyper-threads.
219///
220/// This function is different from [`thread::yield_now`] which directly
221/// yields to the system's scheduler, whereas `spin_loop` does not interact
222/// with the operating system.
223///
224/// A common use case for `spin_loop` is implementing bounded optimistic
225/// spinning in a CAS loop in synchronization primitives. To avoid problems
226/// like priority inversion, it is strongly recommended that the spin loop is
227/// terminated after a finite amount of iterations and an appropriate blocking
228/// syscall is made.
229///
230/// **Note**: On platforms that do not support receiving spin-loop hints this
231/// function does not do anything at all.
232///
233/// # Examples
234///
235/// ```ignore-wasm, ignore-vxworks
236/// # // AdaCore: on VxWorks, threads of equal priority will not preempt each other, causing spin
237/// # // loops to deadlock.
238/// use std::sync::atomic::{AtomicBool, Ordering};
239/// use std::sync::Arc;
240/// use std::{hint, thread};
241///
242/// // A shared atomic value that threads will use to coordinate
243/// let live = Arc::new(AtomicBool::new(false));
244///
245/// // In a background thread we'll eventually set the value
246/// let bg_work = {
247///     let live = live.clone();
248///     thread::spawn(move || {
249///         // Do some work, then make the value live
250///         do_some_work();
251///         live.store(true, Ordering::Release);
252///     })
253/// };
254///
255/// // Back on our current thread, we wait for the value to be set
256/// while !live.load(Ordering::Acquire) {
257///     // The spin loop is a hint to the CPU that we're waiting, but probably
258///     // not for very long
259///     hint::spin_loop();
260/// }
261///
262/// // The value is now set
263/// # fn do_some_work() {}
264/// do_some_work();
265/// bg_work.join()?;
266/// # Ok::<(), Box<dyn core::any::Any + Send + 'static>>(())
267/// ```
268///
269/// [`thread::yield_now`]: ../../std/thread/fn.yield_now.html
270#[inline(always)]
271#[stable(feature = "renamed_spin_loop", since = "1.49.0")]
272pub fn spin_loop() {
273    crate::cfg_select! {
274        target_arch = "x86" => {
275            // SAFETY: the `cfg` attr ensures that we only execute this on x86 targets.
276            crate::arch::x86::_mm_pause()
277        }
278        target_arch = "x86_64" => {
279            // SAFETY: the `cfg` attr ensures that we only execute this on x86_64 targets.
280            crate::arch::x86_64::_mm_pause()
281        }
282        target_arch = "riscv32" => crate::arch::riscv32::pause(),
283        target_arch = "riscv64" => crate::arch::riscv64::pause(),
284        any(target_arch = "aarch64", target_arch = "arm64ec") => {
285            // SAFETY: the `cfg` attr ensures that we only execute this on aarch64 targets.
286            unsafe { crate::arch::aarch64::__isb(crate::arch::aarch64::SY) }
287        }
288        all(target_arch = "arm", target_feature = "v6") => {
289            // SAFETY: the `cfg` attr ensures that we only execute this on arm targets
290            // with support for the v6 feature.
291            unsafe { crate::arch::arm::__yield() }
292        }
293        target_arch = "loongarch32" => crate::arch::loongarch32::ibar::<0>(),
294        target_arch = "loongarch64" => crate::arch::loongarch64::ibar::<0>(),
295        _ => { /* do nothing */ }
296    }
297}
298
299/// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
300/// `black_box` could do.
301///
302/// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
303/// use `dummy` in any possible valid way that Rust code is allowed to without introducing undefined
304/// behavior in the calling code. This property makes `black_box` useful for writing code in which
305/// certain optimizations are not desired, such as benchmarks.
306///
307/// <div class="warning">
308///
309/// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
310/// extent to which it can block optimisations may vary depending upon the platform and code-gen
311/// backend used. Programs cannot rely on `black_box` for *correctness*, beyond it behaving as the
312/// identity function. As such, it **must not be relied upon to control critical program behavior.**
313/// This also means that this function does not offer any guarantees for cryptographic or security
314/// purposes.
315///
316/// This limitation is not specific to `black_box`; there is no mechanism in the entire Rust
317/// language that can provide the guarantees required for constant-time cryptography.
318/// (There is also no such mechanism in LLVM, so the same is true for every other LLVM-based compiler.)
319///
320/// </div>
321///
322/// [`std::convert::identity`]: crate::convert::identity
323///
324/// # When is this useful?
325///
326/// While not suitable in those mission-critical cases, `black_box`'s functionality can generally be
327/// relied upon for benchmarking, and should be used there. It will try to ensure that the
328/// compiler doesn't optimize away part of the intended test code based on context. For
329/// example:
330///
331/// ```
332/// fn contains(haystack: &[&str], needle: &str) -> bool {
333///     haystack.iter().any(|x| x == &needle)
334/// }
335///
336/// pub fn benchmark() {
337///     let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
338///     let needle = "ghi";
339///     for _ in 0..10 {
340///         contains(&haystack, needle);
341///     }
342/// }
343/// ```
344///
345/// The compiler could theoretically make optimizations like the following:
346///
347/// - The `needle` and `haystack` do not change, move the call to `contains` outside the loop and
348///   delete the loop
349/// - Inline `contains`
350/// - `needle` and `haystack` have values known at compile time, `contains` is always true. Remove
351///   the call and replace with `true`
352/// - Nothing is done with the result of `contains`: delete this function call entirely
353/// - `benchmark` now has no purpose: delete this function
354///
355/// It is not likely that all of the above happens, but the compiler is definitely able to make some
356/// optimizations that could result in a very inaccurate benchmark. This is where `black_box` comes
357/// in:
358///
359/// ```
360/// use std::hint::black_box;
361///
362/// // Same `contains` function.
363/// fn contains(haystack: &[&str], needle: &str) -> bool {
364///     haystack.iter().any(|x| x == &needle)
365/// }
366///
367/// pub fn benchmark() {
368///     let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
369///     let needle = "ghi";
370///     for _ in 0..10 {
371///         // Force the compiler to run `contains`, even though it is a pure function whose
372///         // results are unused.
373///         black_box(contains(
374///             // Prevent the compiler from making assumptions about the input.
375///             black_box(&haystack),
376///             black_box(needle),
377///         ));
378///     }
379/// }
380/// ```
381///
382/// This essentially tells the compiler to block optimizations across any calls to `black_box`. So,
383/// it now:
384///
385/// - Treats both arguments to `contains` as unpredictable: the body of `contains` can no longer be
386///   optimized based on argument values
387/// - Treats the call to `contains` and its result as volatile: the body of `benchmark` cannot
388///   optimize this away
389///
390/// This makes our benchmark much more realistic to how the function would actually be used, where
391/// arguments are usually not known at compile time and the result is used in some way.
392///
393/// # How to use this
394///
395/// In practice, `black_box` serves two purposes:
396///
397/// 1. It prevents the compiler from making optimizations related to the value returned by `black_box`
398/// 2. It forces the value passed to `black_box` to be calculated, even if the return value of `black_box` is unused
399///
400/// ```
401/// use std::hint::black_box;
402///
403/// let zero = 0;
404/// let five = 5;
405///
406/// // The compiler will see this and remove the `* five` call, because it knows that multiplying
407/// // any integer by 0 will result in 0.
408/// let c = zero * five;
409///
410/// // Adding `black_box` here disables the compiler's ability to reason about the first operand in the multiplication.
411/// // It is forced to assume that it can be any possible number, so it cannot remove the `* five`
412/// // operation.
413/// let c = black_box(zero) * five;
414/// ```
415///
416/// While most cases will not be as clear-cut as the above example, it still illustrates how
417/// `black_box` can be used. When benchmarking a function, you usually want to wrap its inputs in
418/// `black_box` so the compiler cannot make optimizations that would be unrealistic in real-life
419/// use.
420///
421/// ```
422/// use std::hint::black_box;
423///
424/// // This is a simple function that increments its input by 1. Note that it is pure, meaning it
425/// // has no side-effects. This function has no effect if its result is unused. (An example of a
426/// // function *with* side-effects is `println!()`.)
427/// fn increment(x: u8) -> u8 {
428///     x + 1
429/// }
430///
431/// // Here, we call `increment` but discard its result. The compiler, seeing this and knowing that
432/// // `increment` is pure, will eliminate this function call entirely. This may not be desired,
433/// // though, especially if we're trying to track how much time `increment` takes to execute.
434/// let _ = increment(black_box(5));
435///
436/// // Here, we force `increment` to be executed. This is because the compiler treats `black_box`
437/// // as if it has side-effects, and thus must compute its input.
438/// let _ = black_box(increment(black_box(5)));
439/// ```
440///
441/// There may be additional situations where you want to wrap the result of a function in
442/// `black_box` to force its execution. This is situational though, and may not have any effect
443/// (such as when the function returns a zero-sized type such as [`()` unit][unit]).
444///
445/// Note that `black_box` has no effect on how its input is treated, only its output. As such,
446/// expressions passed to `black_box` may still be optimized:
447///
448/// ```
449/// use std::hint::black_box;
450///
451/// // The compiler sees this...
452/// let y = black_box(5 * 10);
453///
454/// // ...as this. As such, it will likely simplify `5 * 10` to just `50`.
455/// let _0 = 5 * 10;
456/// let y = black_box(_0);
457/// ```
458///
459/// In the above example, the `5 * 10` expression is considered distinct from the `black_box` call,
460/// and thus is still optimized by the compiler. You can prevent this by moving the multiplication
461/// operation outside of `black_box`:
462///
463/// ```
464/// use std::hint::black_box;
465///
466/// // No assumptions can be made about either operand, so the multiplication is not optimized out.
467/// let y = black_box(5) * black_box(10);
468/// ```
469///
470/// During constant evaluation, `black_box` is treated as a no-op.
471#[inline]
472#[stable(feature = "bench_black_box", since = "1.66.0")]
473#[rustc_const_stable(feature = "const_black_box", since = "1.86.0")]
474pub const fn black_box<T>(dummy: T) -> T {
475    crate::intrinsics::black_box(dummy)
476}
477
478/// An identity function that causes an `unused_must_use` warning to be
479/// triggered if the given value is not used (returned, stored in a variable,
480/// etc) by the caller.
481///
482/// This is primarily intended for use in macro-generated code, in which a
483/// [`#[must_use]` attribute][must_use] either on a type or a function would not
484/// be convenient.
485///
486/// [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
487///
488/// # Example
489///
490/// ```
491/// #![feature(hint_must_use)]
492///
493/// use core::fmt;
494///
495/// pub struct Error(/* ... */);
496///
497/// #[macro_export]
498/// macro_rules! make_error {
499///     ($($args:expr),*) => {
500///         core::hint::must_use({
501///             let error = $crate::make_error(core::format_args!($($args),*));
502///             error
503///         })
504///     };
505/// }
506///
507/// // Implementation detail of make_error! macro.
508/// #[doc(hidden)]
509/// pub fn make_error(args: fmt::Arguments<'_>) -> Error {
510///     Error(/* ... */)
511/// }
512///
513/// fn demo() -> Option<Error> {
514///     if true {
515///         // Oops, meant to write `return Some(make_error!("..."));`
516///         Some(make_error!("..."));
517///     }
518///     None
519/// }
520/// #
521/// # // Make rustdoc not wrap the whole snippet in fn main, so that $crate::make_error works
522/// # fn main() {}
523/// ```
524///
525/// In the above example, we'd like an `unused_must_use` lint to apply to the
526/// value created by `make_error!`. However, neither `#[must_use]` on a struct
527/// nor `#[must_use]` on a function is appropriate here, so the macro expands
528/// using `core::hint::must_use` instead.
529///
530/// - We wouldn't want `#[must_use]` on the `struct Error` because that would
531///   make the following unproblematic code trigger a warning:
532///
533///   ```
534///   # struct Error;
535///   #
536///   fn f(arg: &str) -> Result<(), Error>
537///   # { Ok(()) }
538///
539///   #[test]
540///   fn t() {
541///       // Assert that `f` returns error if passed an empty string.
542///       // A value of type `Error` is unused here but that's not a problem.
543///       f("").unwrap_err();
544///   }
545///   ```
546///
547/// - Using `#[must_use]` on `fn make_error` can't help because the return value
548///   *is* used, as the right-hand side of a `let` statement. The `let`
549///   statement looks useless but is in fact necessary for ensuring that
550///   temporaries within the `format_args` expansion are not kept alive past the
551///   creation of the `Error`, as keeping them alive past that point can cause
552///   autotrait issues in async code:
553///
554///   ```
555///   # #![feature(hint_must_use)]
556///   #
557///   # struct Error;
558///   #
559///   # macro_rules! make_error {
560///   #     ($($args:expr),*) => {
561///   #         core::hint::must_use({
562///   #             // If `let` isn't used, then `f()` produces a non-Send future.
563///   #             let error = make_error(core::format_args!($($args),*));
564///   #             error
565///   #         })
566///   #     };
567///   # }
568///   #
569///   # fn make_error(args: core::fmt::Arguments<'_>) -> Error {
570///   #     Error
571///   # }
572///   #
573///   async fn f() {
574///       // Using `let` inside the make_error expansion causes temporaries like
575///       // `unsync()` to drop at the semicolon of that `let` statement, which
576///       // is prior to the await point. They would otherwise stay around until
577///       // the semicolon on *this* statement, which is after the await point,
578///       // and the enclosing Future would not implement Send.
579///       log(make_error!("look: {:p}", unsync())).await;
580///   }
581///
582///   async fn log(error: Error) {/* ... */}
583///
584///   // Returns something without a Sync impl.
585///   fn unsync() -> *const () {
586///       0 as *const ()
587///   }
588///   #
589///   # fn test() {
590///   #     fn assert_send(_: impl Send) {}
591///   #     assert_send(f());
592///   # }
593///   ```
594#[unstable(feature = "hint_must_use", issue = "94745")]
595#[must_use] // <-- :)
596#[inline(always)]
597pub const fn must_use<T>(value: T) -> T {
598    value
599}
600
601/// Hints to the compiler that a branch condition is likely to be true.
602/// Returns the value passed to it.
603///
604/// It can be used with `if` or boolean `match` expressions.
605///
606/// When used outside of a branch condition, it may still influence a nearby branch, but
607/// probably will not have any effect.
608///
609/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
610/// compound expressions, such as `likely(a && b)`. When applied to compound expressions, it has
611/// the following effect:
612/// ```text
613///     likely(!a) => !unlikely(a)
614///     likely(a && b) => likely(a) && likely(b)
615///     likely(a || b) => a || likely(b)
616/// ```
617///
618/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
619///
620/// # Examples
621///
622/// ```
623/// #![feature(likely_unlikely)]
624/// use core::hint::likely;
625///
626/// fn foo(x: i32) {
627///     if likely(x > 0) {
628///         println!("this branch is likely to be taken");
629///     } else {
630///         println!("this branch is unlikely to be taken");
631///     }
632///
633///     match likely(x > 0) {
634///         true => println!("this branch is likely to be taken"),
635///         false => println!("this branch is unlikely to be taken"),
636///     }
637///
638///     // Use outside of a branch condition may still influence a nearby branch
639///     let cond = likely(x != 0);
640///     if cond {
641///         println!("this branch is likely to be taken");
642///     }
643/// }
644/// ```
645#[unstable(feature = "likely_unlikely", issue = "136873")]
646#[inline(always)]
647pub const fn likely(b: bool) -> bool {
648    crate::intrinsics::likely(b)
649}
650
651/// Hints to the compiler that a branch condition is unlikely to be true.
652/// Returns the value passed to it.
653///
654/// It can be used with `if` or boolean `match` expressions.
655///
656/// When used outside of a branch condition, it may still influence a nearby branch, but
657/// probably will not have any effect.
658///
659/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
660/// compound expressions, such as `unlikely(a && b)`. When applied to compound expressions, it has
661/// the following effect:
662/// ```text
663///     unlikely(!a) => !likely(a)
664///     unlikely(a && b) => a && unlikely(b)
665///     unlikely(a || b) => unlikely(a) || unlikely(b)
666/// ```
667///
668/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
669///
670/// # Examples
671///
672/// ```
673/// #![feature(likely_unlikely)]
674/// use core::hint::unlikely;
675///
676/// fn foo(x: i32) {
677///     if unlikely(x > 0) {
678///         println!("this branch is unlikely to be taken");
679///     } else {
680///         println!("this branch is likely to be taken");
681///     }
682///
683///     match unlikely(x > 0) {
684///         true => println!("this branch is unlikely to be taken"),
685///         false => println!("this branch is likely to be taken"),
686///     }
687///
688///     // Use outside of a branch condition may still influence a nearby branch
689///     let cond = unlikely(x != 0);
690///     if cond {
691///         println!("this branch is likely to be taken");
692///     }
693/// }
694/// ```
695#[unstable(feature = "likely_unlikely", issue = "136873")]
696#[inline(always)]
697pub const fn unlikely(b: bool) -> bool {
698    crate::intrinsics::unlikely(b)
699}
700
701/// Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may
702/// choose to optimize paths that are not cold at the expense of paths that are cold.
703///
704/// # Examples
705///
706/// ```
707/// #![feature(cold_path)]
708/// use core::hint::cold_path;
709///
710/// fn foo(x: &[i32]) {
711///     if let Some(first) = x.get(0) {
712///         // this is the fast path
713///     } else {
714///         // this path is unlikely
715///         cold_path();
716///     }
717/// }
718///
719/// fn bar(x: i32) -> i32 {
720///     match x {
721///         1 => 10,
722///         2 => 100,
723///         3 => { cold_path(); 1000 }, // this branch is unlikely
724///         _ => { cold_path(); 10000 }, // this is also unlikely
725///     }
726/// }
727/// ```
728#[unstable(feature = "cold_path", issue = "136873")]
729#[inline(always)]
730pub const fn cold_path() {
731    crate::intrinsics::cold_path()
732}
733
734/// Returns either `true_val` or `false_val` depending on the value of
735/// `condition`, with a hint to the compiler that `condition` is unlikely to be
736/// correctly predicted by a CPU’s branch predictor.
737///
738/// This method is functionally equivalent to
739/// ```ignore (this is just for illustrative purposes)
740/// fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
741///     if b { true_val } else { false_val }
742/// }
743/// ```
744/// but might generate different assembly. In particular, on platforms with
745/// a conditional move or select instruction (like `cmov` on x86 or `csel`
746/// on ARM) the optimizer might use these instructions to avoid branches,
747/// which can benefit performance if the branch predictor is struggling
748/// with predicting `condition`, such as in an implementation of binary
749/// search.
750///
751/// Note however that this lowering is not guaranteed (on any platform) and
752/// should not be relied upon when trying to write cryptographic constant-time
753/// code. Also be aware that this lowering might *decrease* performance if
754/// `condition` is well-predictable. It is advisable to perform benchmarks to
755/// tell if this function is useful.
756///
757/// # Examples
758///
759/// Distribute values evenly between two buckets:
760/// ```
761/// use std::hash::BuildHasher;
762/// use std::hint;
763///
764/// fn append<H: BuildHasher>(hasher: &H, v: i32, bucket_one: &mut Vec<i32>, bucket_two: &mut Vec<i32>) {
765///     let hash = hasher.hash_one(&v);
766///     let bucket = hint::select_unpredictable(hash % 2 == 0, bucket_one, bucket_two);
767///     bucket.push(v);
768/// }
769/// # let hasher = std::collections::hash_map::RandomState::new();
770/// # let mut bucket_one = Vec::new();
771/// # let mut bucket_two = Vec::new();
772/// # append(&hasher, 42, &mut bucket_one, &mut bucket_two);
773/// # assert_eq!(bucket_one.len() + bucket_two.len(), 1);
774/// ```
775#[inline(always)]
776#[stable(feature = "select_unpredictable", since = "1.88.0")]
777#[rustc_const_unstable(feature = "const_select_unpredictable", issue = "145938")]
778pub const fn select_unpredictable<T>(condition: bool, true_val: T, false_val: T) -> T
779where
780    T: [const] Destruct,
781{
782    // FIXME(https://github.com/rust-lang/unsafe-code-guidelines/issues/245):
783    // Change this to use ManuallyDrop instead.
784    let mut true_val = MaybeUninit::new(true_val);
785    let mut false_val = MaybeUninit::new(false_val);
786
787    struct DropOnPanic<T> {
788        // Invariant: valid pointer and points to an initialized value that is not further used,
789        // i.e. it can be dropped by this guard.
790        inner: *mut T,
791    }
792
793    impl<T> Drop for DropOnPanic<T> {
794        fn drop(&mut self) {
795            // SAFETY: Must be guaranteed on construction of local type `DropOnPanic`.
796            unsafe { self.inner.drop_in_place() }
797        }
798    }
799
800    let true_ptr = true_val.as_mut_ptr();
801    let false_ptr = false_val.as_mut_ptr();
802
803    // SAFETY: The value that is not selected is dropped, and the selected one
804    // is returned. This is necessary because the intrinsic doesn't drop the
805    // value that is  not selected.
806    unsafe {
807        // Extract the selected value first, ensure it is dropped as well if dropping the unselected
808        // value panics. We construct a temporary by-pointer guard around the selected value while
809        // dropping the unselected value. Arguments overlap here, so we can not use mutable
810        // reference for these arguments.
811        let guard = crate::intrinsics::select_unpredictable(condition, true_ptr, false_ptr);
812        let drop = crate::intrinsics::select_unpredictable(condition, false_ptr, true_ptr);
813
814        // SAFETY: both pointers are well-aligned and point to initialized values inside a
815        // `MaybeUninit` each. In both possible values for `condition` the pointer `guard` and
816        // `drop` do not alias (even though the two argument pairs we have selected from did alias
817        // each other).
818        let guard = DropOnPanic { inner: guard };
819        drop.drop_in_place();
820        crate::mem::forget(guard);
821
822        // Note that it is important to use the values here. Reading from the pointer we got makes
823        // LLVM forget the !unpredictable annotation sometimes (in tests, integer sized values in
824        // particular seemed to confuse it, also observed in llvm/llvm-project #82340).
825        crate::intrinsics::select_unpredictable(condition, true_val, false_val).assume_init()
826    }
827}