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]
103#[coverage(off)] // Ferrocene addition: this function breaks llvm-cov
104pub const unsafe fn unreachable_unchecked() -> ! {
105 ub_checks::assert_unsafe_precondition!(
106 check_language_ub,
107 "hint::unreachable_unchecked must never be reached",
108 () => false
109 );
110 // SAFETY: the safety contract for `intrinsics::unreachable` must
111 // be upheld by the caller.
112 unsafe { intrinsics::unreachable() }
113}
114
115/// Makes a *soundness* promise to the compiler that `cond` holds.
116///
117/// This may allow the optimizer to simplify things, but it might also make the generated code
118/// slower. Either way, calling it will most likely make compilation take longer.
119///
120/// You may know this from other places as
121/// [`llvm.assume`](https://llvm.org/docs/LangRef.html#llvm-assume-intrinsic) or, in C,
122/// [`__builtin_assume`](https://clang.llvm.org/docs/LanguageExtensions.html#builtin-assume).
123///
124/// This promotes a correctness requirement to a soundness requirement. Don't do that without
125/// very good reason.
126///
127/// # Usage
128///
129/// This is a situational tool for micro-optimization, and is allowed to do nothing. Any use
130/// should come with a repeatable benchmark to show the value, with the expectation to drop it
131/// later should the optimizer get smarter and no longer need it.
132///
133/// The more complicated the condition, the less likely this is to be useful. For example,
134/// `assert_unchecked(foo.is_sorted())` is a complex enough value that the compiler is unlikely
135/// to be able to take advantage of it.
136///
137/// There's also no need to `assert_unchecked` basic properties of things. For example, the
138/// compiler already knows the range of `count_ones`, so there is no benefit to
139/// `let n = u32::count_ones(x); assert_unchecked(n <= u32::BITS);`.
140///
141/// `assert_unchecked` is logically equivalent to `if !cond { unreachable_unchecked(); }`. If
142/// ever you are tempted to write `assert_unchecked(false)`, you should instead use
143/// [`unreachable_unchecked()`] directly.
144///
145/// # Safety
146///
147/// `cond` must be `true`. It is immediate UB to call this with `false`.
148///
149/// # Example
150///
151/// ```
152/// use core::hint;
153///
154/// /// # Safety
155/// ///
156/// /// `p` must be nonnull and valid
157/// pub unsafe fn next_value(p: *const i32) -> i32 {
158/// // SAFETY: caller invariants guarantee that `p` is not null
159/// unsafe { hint::assert_unchecked(!p.is_null()) }
160///
161/// if p.is_null() {
162/// return -1;
163/// } else {
164/// // SAFETY: caller invariants guarantee that `p` is valid
165/// unsafe { *p + 1 }
166/// }
167/// }
168/// ```
169///
170/// Without the `assert_unchecked`, the above function produces the following with optimizations
171/// enabled:
172///
173/// ```asm
174/// next_value:
175/// test rdi, rdi
176/// je .LBB0_1
177/// mov eax, dword ptr [rdi]
178/// inc eax
179/// ret
180/// .LBB0_1:
181/// mov eax, -1
182/// ret
183/// ```
184///
185/// Adding the assertion allows the optimizer to remove the extra check:
186///
187/// ```asm
188/// next_value:
189/// mov eax, dword ptr [rdi]
190/// inc eax
191/// ret
192/// ```
193///
194/// This example is quite unlike anything that would be used in the real world: it is redundant
195/// to put an assertion right next to code that checks the same thing, and dereferencing a
196/// pointer already has the builtin assumption that it is nonnull. However, it illustrates the
197/// kind of changes the optimizer can make even when the behavior is less obviously related.
198#[track_caller]
199#[inline(always)]
200#[doc(alias = "assume")]
201#[stable(feature = "hint_assert_unchecked", since = "1.81.0")]
202#[rustc_const_stable(feature = "hint_assert_unchecked", since = "1.81.0")]
203pub const unsafe fn assert_unchecked(cond: bool) {
204 // SAFETY: The caller promised `cond` is true.
205 unsafe {
206 ub_checks::assert_unsafe_precondition!(
207 check_language_ub,
208 "hint::assert_unchecked must never be called when the condition is false",
209 (cond: bool = cond) => cond,
210 );
211 crate::intrinsics::assume(cond);
212 }
213}
214
215/// Emits a machine instruction to signal the processor that it is running in
216/// a busy-wait spin-loop ("spin lock").
217///
218/// Upon receiving the spin-loop signal the processor can optimize its behavior by,
219/// for example, saving power or switching hyper-threads.
220///
221/// This function is different from [`thread::yield_now`] which directly
222/// yields to the system's scheduler, whereas `spin_loop` does not interact
223/// with the operating system.
224///
225/// A common use case for `spin_loop` is implementing bounded optimistic
226/// spinning in a CAS loop in synchronization primitives. To avoid problems
227/// like priority inversion, it is strongly recommended that the spin loop is
228/// terminated after a finite amount of iterations and an appropriate blocking
229/// syscall is made.
230///
231/// **Note**: On platforms that do not support receiving spin-loop hints this
232/// function does not do anything at all.
233///
234/// # Examples
235///
236/// ```ignore-wasm
237/// use std::sync::atomic::{AtomicBool, Ordering};
238/// use std::sync::Arc;
239/// use std::{hint, thread};
240///
241/// // A shared atomic value that threads will use to coordinate
242/// let live = Arc::new(AtomicBool::new(false));
243///
244/// // In a background thread we'll eventually set the value
245/// let bg_work = {
246/// let live = live.clone();
247/// thread::spawn(move || {
248/// // Do some work, then make the value live
249/// do_some_work();
250/// live.store(true, Ordering::Release);
251/// })
252/// };
253///
254/// // Back on our current thread, we wait for the value to be set
255/// while !live.load(Ordering::Acquire) {
256/// // The spin loop is a hint to the CPU that we're waiting, but probably
257/// // not for very long
258/// hint::spin_loop();
259/// }
260///
261/// // The value is now set
262/// # fn do_some_work() {}
263/// do_some_work();
264/// bg_work.join()?;
265/// # Ok::<(), Box<dyn core::any::Any + Send + 'static>>(())
266/// ```
267///
268/// [`thread::yield_now`]: ../../std/thread/fn.yield_now.html
269#[inline(always)]
270#[stable(feature = "renamed_spin_loop", since = "1.49.0")]
271#[cfg(not(feature = "ferrocene_subset"))]
272pub fn spin_loop() {
273 crate::cfg_select! {
274 miri => {
275 unsafe extern "Rust" {
276 safe fn miri_spin_loop();
277 }
278
279 // Miri does support some of the intrinsics that are called below, but to guarantee
280 // consistent behavior across targets, this custom function is used.
281 miri_spin_loop();
282 }
283 target_arch = "x86" => {
284 // SAFETY: the `cfg` attr ensures that we only execute this on x86 targets.
285 crate::arch::x86::_mm_pause()
286 }
287 target_arch = "x86_64" => {
288 // SAFETY: the `cfg` attr ensures that we only execute this on x86_64 targets.
289 crate::arch::x86_64::_mm_pause()
290 }
291 target_arch = "riscv32" => crate::arch::riscv32::pause(),
292 target_arch = "riscv64" => crate::arch::riscv64::pause(),
293 any(target_arch = "aarch64", target_arch = "arm64ec") => {
294 // SAFETY: the `cfg` attr ensures that we only execute this on aarch64 targets.
295 unsafe { crate::arch::aarch64::__isb(crate::arch::aarch64::SY) }
296 }
297 all(
298 target_arch = "arm",
299 any(
300 all(target_feature = "v6k", not(target_feature = "thumb-mode")),
301 target_feature = "v6t2",
302 all(target_feature = "v6", target_feature = "mclass"),
303 )
304 ) => {
305 // SAFETY: the `cfg` attr ensures that we only execute this on arm
306 // targets with support for the this feature. On ARMv6 in Thumb
307 // mode, T2 is required (see Arm DDI0406C Section A8.8.427),
308 // otherwise ARMv6-M or ARMv6K is enough
309 unsafe { crate::arch::arm::__yield() }
310 }
311 target_arch = "loongarch32" => crate::arch::loongarch32::ibar::<0>(),
312 target_arch = "loongarch64" => crate::arch::loongarch64::ibar::<0>(),
313 _ => { /* do nothing */ }
314 }
315}
316
317/// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
318/// `black_box` could do.
319///
320/// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
321/// use `dummy` in any possible valid way that Rust code is allowed to without introducing undefined
322/// behavior in the calling code. This property makes `black_box` useful for writing code in which
323/// certain optimizations are not desired, such as benchmarks.
324///
325/// <div class="warning">
326///
327/// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
328/// extent to which it can block optimisations may vary depending upon the platform and code-gen
329/// backend used. Programs cannot rely on `black_box` for *correctness*, beyond it behaving as the
330/// identity function. As such, it **must not be relied upon to control critical program behavior.**
331/// This also means that this function does not offer any guarantees for cryptographic or security
332/// purposes.
333///
334/// This limitation is not specific to `black_box`; there is no mechanism in the entire Rust
335/// language that can provide the guarantees required for constant-time cryptography.
336/// (There is also no such mechanism in LLVM, so the same is true for every other LLVM-based compiler.)
337///
338/// </div>
339///
340/// [`std::convert::identity`]: crate::convert::identity
341///
342/// # When is this useful?
343///
344/// While not suitable in those mission-critical cases, `black_box`'s functionality can generally be
345/// relied upon for benchmarking, and should be used there. It will try to ensure that the
346/// compiler doesn't optimize away part of the intended test code based on context. For
347/// example:
348///
349/// ```
350/// fn contains(haystack: &[&str], needle: &str) -> bool {
351/// haystack.iter().any(|x| x == &needle)
352/// }
353///
354/// pub fn benchmark() {
355/// let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
356/// let needle = "ghi";
357/// for _ in 0..10 {
358/// contains(&haystack, needle);
359/// }
360/// }
361/// ```
362///
363/// The compiler could theoretically make optimizations like the following:
364///
365/// - The `needle` and `haystack` do not change, move the call to `contains` outside the loop and
366/// delete the loop
367/// - Inline `contains`
368/// - `needle` and `haystack` have values known at compile time, `contains` is always true. Remove
369/// the call and replace with `true`
370/// - Nothing is done with the result of `contains`: delete this function call entirely
371/// - `benchmark` now has no purpose: delete this function
372///
373/// It is not likely that all of the above happens, but the compiler is definitely able to make some
374/// optimizations that could result in a very inaccurate benchmark. This is where `black_box` comes
375/// in:
376///
377/// ```
378/// use std::hint::black_box;
379///
380/// // Same `contains` function.
381/// fn contains(haystack: &[&str], needle: &str) -> bool {
382/// haystack.iter().any(|x| x == &needle)
383/// }
384///
385/// pub fn benchmark() {
386/// let haystack = vec!["abc", "def", "ghi", "jkl", "mno"];
387/// let needle = "ghi";
388/// for _ in 0..10 {
389/// // Force the compiler to run `contains`, even though it is a pure function whose
390/// // results are unused.
391/// black_box(contains(
392/// // Prevent the compiler from making assumptions about the input.
393/// black_box(&haystack),
394/// black_box(needle),
395/// ));
396/// }
397/// }
398/// ```
399///
400/// This essentially tells the compiler to block optimizations across any calls to `black_box`. So,
401/// it now:
402///
403/// - Treats both arguments to `contains` as unpredictable: the body of `contains` can no longer be
404/// optimized based on argument values
405/// - Treats the call to `contains` and its result as volatile: the body of `benchmark` cannot
406/// optimize this away
407///
408/// This makes our benchmark much more realistic to how the function would actually be used, where
409/// arguments are usually not known at compile time and the result is used in some way.
410///
411/// # How to use this
412///
413/// In practice, `black_box` serves two purposes:
414///
415/// 1. It prevents the compiler from making optimizations related to the value returned by `black_box`
416/// 2. It forces the value passed to `black_box` to be calculated, even if the return value of `black_box` is unused
417///
418/// ```
419/// use std::hint::black_box;
420///
421/// let zero = 0;
422/// let five = 5;
423///
424/// // The compiler will see this and remove the `* five` call, because it knows that multiplying
425/// // any integer by 0 will result in 0.
426/// let c = zero * five;
427///
428/// // Adding `black_box` here disables the compiler's ability to reason about the first operand in the multiplication.
429/// // It is forced to assume that it can be any possible number, so it cannot remove the `* five`
430/// // operation.
431/// let c = black_box(zero) * five;
432/// ```
433///
434/// While most cases will not be as clear-cut as the above example, it still illustrates how
435/// `black_box` can be used. When benchmarking a function, you usually want to wrap its inputs in
436/// `black_box` so the compiler cannot make optimizations that would be unrealistic in real-life
437/// use.
438///
439/// ```
440/// use std::hint::black_box;
441///
442/// // This is a simple function that increments its input by 1. Note that it is pure, meaning it
443/// // has no side-effects. This function has no effect if its result is unused. (An example of a
444/// // function *with* side-effects is `println!()`.)
445/// fn increment(x: u8) -> u8 {
446/// x + 1
447/// }
448///
449/// // Here, we call `increment` but discard its result. The compiler, seeing this and knowing that
450/// // `increment` is pure, will eliminate this function call entirely. This may not be desired,
451/// // though, especially if we're trying to track how much time `increment` takes to execute.
452/// let _ = increment(black_box(5));
453///
454/// // Here, we force `increment` to be executed. This is because the compiler treats `black_box`
455/// // as if it has side-effects, and thus must compute its input.
456/// let _ = black_box(increment(black_box(5)));
457/// ```
458///
459/// There may be additional situations where you want to wrap the result of a function in
460/// `black_box` to force its execution. This is situational though, and may not have any effect
461/// (such as when the function returns a zero-sized type such as [`()` unit][unit]).
462///
463/// Note that `black_box` has no effect on how its input is treated, only its output. As such,
464/// expressions passed to `black_box` may still be optimized:
465///
466/// ```
467/// use std::hint::black_box;
468///
469/// // The compiler sees this...
470/// let y = black_box(5 * 10);
471///
472/// // ...as this. As such, it will likely simplify `5 * 10` to just `50`.
473/// let _0 = 5 * 10;
474/// let y = black_box(_0);
475/// ```
476///
477/// In the above example, the `5 * 10` expression is considered distinct from the `black_box` call,
478/// and thus is still optimized by the compiler. You can prevent this by moving the multiplication
479/// operation outside of `black_box`:
480///
481/// ```
482/// use std::hint::black_box;
483///
484/// // No assumptions can be made about either operand, so the multiplication is not optimized out.
485/// let y = black_box(5) * black_box(10);
486/// ```
487///
488/// During constant evaluation, `black_box` is treated as a no-op.
489#[inline]
490#[stable(feature = "bench_black_box", since = "1.66.0")]
491#[rustc_const_stable(feature = "const_black_box", since = "1.86.0")]
492#[cfg(not(feature = "ferrocene_subset"))]
493pub const fn black_box<T>(dummy: T) -> T {
494 crate::intrinsics::black_box(dummy)
495}
496
497/// An identity function that causes an `unused_must_use` warning to be
498/// triggered if the given value is not used (returned, stored in a variable,
499/// etc) by the caller.
500///
501/// This is primarily intended for use in macro-generated code, in which a
502/// [`#[must_use]` attribute][must_use] either on a type or a function would not
503/// be convenient.
504///
505/// [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
506///
507/// # Example
508///
509/// ```
510/// #![feature(hint_must_use)]
511///
512/// use core::fmt;
513///
514/// pub struct Error(/* ... */);
515///
516/// #[macro_export]
517/// macro_rules! make_error {
518/// ($($args:expr),*) => {
519/// core::hint::must_use({
520/// let error = $crate::make_error(core::format_args!($($args),*));
521/// error
522/// })
523/// };
524/// }
525///
526/// // Implementation detail of make_error! macro.
527/// #[doc(hidden)]
528/// pub fn make_error(args: fmt::Arguments<'_>) -> Error {
529/// Error(/* ... */)
530/// }
531///
532/// fn demo() -> Option<Error> {
533/// if true {
534/// // Oops, meant to write `return Some(make_error!("..."));`
535/// Some(make_error!("..."));
536/// }
537/// None
538/// }
539/// #
540/// # // Make rustdoc not wrap the whole snippet in fn main, so that $crate::make_error works
541/// # fn main() {}
542/// ```
543///
544/// In the above example, we'd like an `unused_must_use` lint to apply to the
545/// value created by `make_error!`. However, neither `#[must_use]` on a struct
546/// nor `#[must_use]` on a function is appropriate here, so the macro expands
547/// using `core::hint::must_use` instead.
548///
549/// - We wouldn't want `#[must_use]` on the `struct Error` because that would
550/// make the following unproblematic code trigger a warning:
551///
552/// ```
553/// # struct Error;
554/// #
555/// fn f(arg: &str) -> Result<(), Error>
556/// # { Ok(()) }
557///
558/// #[test]
559/// fn t() {
560/// // Assert that `f` returns error if passed an empty string.
561/// // A value of type `Error` is unused here but that's not a problem.
562/// f("").unwrap_err();
563/// }
564/// ```
565///
566/// - Using `#[must_use]` on `fn make_error` can't help because the return value
567/// *is* used, as the right-hand side of a `let` statement. The `let`
568/// statement looks useless but is in fact necessary for ensuring that
569/// temporaries within the `format_args` expansion are not kept alive past the
570/// creation of the `Error`, as keeping them alive past that point can cause
571/// autotrait issues in async code:
572///
573/// ```
574/// # #![feature(hint_must_use)]
575/// #
576/// # struct Error;
577/// #
578/// # macro_rules! make_error {
579/// # ($($args:expr),*) => {
580/// # core::hint::must_use({
581/// # // If `let` isn't used, then `f()` produces a non-Send future.
582/// # let error = make_error(core::format_args!($($args),*));
583/// # error
584/// # })
585/// # };
586/// # }
587/// #
588/// # fn make_error(args: core::fmt::Arguments<'_>) -> Error {
589/// # Error
590/// # }
591/// #
592/// async fn f() {
593/// // Using `let` inside the make_error expansion causes temporaries like
594/// // `unsync()` to drop at the semicolon of that `let` statement, which
595/// // is prior to the await point. They would otherwise stay around until
596/// // the semicolon on *this* statement, which is after the await point,
597/// // and the enclosing Future would not implement Send.
598/// log(make_error!("look: {:p}", unsync())).await;
599/// }
600///
601/// async fn log(error: Error) {/* ... */}
602///
603/// // Returns something without a Sync impl.
604/// fn unsync() -> *const () {
605/// 0 as *const ()
606/// }
607/// #
608/// # fn test() {
609/// # fn assert_send(_: impl Send) {}
610/// # assert_send(f());
611/// # }
612/// ```
613#[unstable(feature = "hint_must_use", issue = "94745")]
614#[must_use] // <-- :)
615#[inline(always)]
616#[cfg(not(feature = "ferrocene_subset"))]
617pub const fn must_use<T>(value: T) -> T {
618 value
619}
620
621/// Hints to the compiler that a branch condition is likely to be true.
622/// Returns the value passed to it.
623///
624/// It can be used with `if` or boolean `match` expressions.
625///
626/// When used outside of a branch condition, it may still influence a nearby branch, but
627/// probably will not have any effect.
628///
629/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
630/// compound expressions, such as `likely(a && b)`. When applied to compound expressions, it has
631/// the following effect:
632/// ```text
633/// likely(!a) => !unlikely(a)
634/// likely(a && b) => likely(a) && likely(b)
635/// likely(a || b) => a || likely(b)
636/// ```
637///
638/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
639///
640/// # Examples
641///
642/// ```
643/// #![feature(likely_unlikely)]
644/// use core::hint::likely;
645///
646/// fn foo(x: i32) {
647/// if likely(x > 0) {
648/// println!("this branch is likely to be taken");
649/// } else {
650/// println!("this branch is unlikely to be taken");
651/// }
652///
653/// match likely(x > 0) {
654/// true => println!("this branch is likely to be taken"),
655/// false => println!("this branch is unlikely to be taken"),
656/// }
657///
658/// // Use outside of a branch condition may still influence a nearby branch
659/// let cond = likely(x != 0);
660/// if cond {
661/// println!("this branch is likely to be taken");
662/// }
663/// }
664/// ```
665#[unstable(feature = "likely_unlikely", issue = "151619")]
666#[inline(always)]
667#[cfg(not(feature = "ferrocene_subset"))]
668pub const fn likely(b: bool) -> bool {
669 crate::intrinsics::likely(b)
670}
671
672/// Hints to the compiler that a branch condition is unlikely to be true.
673/// Returns the value passed to it.
674///
675/// It can be used with `if` or boolean `match` expressions.
676///
677/// When used outside of a branch condition, it may still influence a nearby branch, but
678/// probably will not have any effect.
679///
680/// It can also be applied to parts of expressions, such as `likely(a) && unlikely(b)`, or to
681/// compound expressions, such as `unlikely(a && b)`. When applied to compound expressions, it has
682/// the following effect:
683/// ```text
684/// unlikely(!a) => !likely(a)
685/// unlikely(a && b) => a && unlikely(b)
686/// unlikely(a || b) => unlikely(a) || unlikely(b)
687/// ```
688///
689/// See also the function [`cold_path()`] which may be more appropriate for idiomatic Rust code.
690///
691/// # Examples
692///
693/// ```
694/// #![feature(likely_unlikely)]
695/// use core::hint::unlikely;
696///
697/// fn foo(x: i32) {
698/// if unlikely(x > 0) {
699/// println!("this branch is unlikely to be taken");
700/// } else {
701/// println!("this branch is likely to be taken");
702/// }
703///
704/// match unlikely(x > 0) {
705/// true => println!("this branch is unlikely to be taken"),
706/// false => println!("this branch is likely to be taken"),
707/// }
708///
709/// // Use outside of a branch condition may still influence a nearby branch
710/// let cond = unlikely(x != 0);
711/// if cond {
712/// println!("this branch is likely to be taken");
713/// }
714/// }
715/// ```
716#[unstable(feature = "likely_unlikely", issue = "151619")]
717#[inline(always)]
718#[cfg(not(feature = "ferrocene_subset"))]
719pub const fn unlikely(b: bool) -> bool {
720 crate::intrinsics::unlikely(b)
721}
722
723/// Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may
724/// choose to optimize paths that are not cold at the expense of paths that are cold.
725///
726/// Note that like all hints, the exact effect to codegen is not guaranteed. Using `cold_path`
727/// can actually *decrease* performance if the branch is called more than expected. It is advisable
728/// to perform benchmarks to tell if this function is useful.
729///
730/// # Examples
731///
732/// ```
733/// #![feature(cold_path)]
734/// use core::hint::cold_path;
735///
736/// fn foo(x: &[i32]) {
737/// if let Some(first) = x.get(0) {
738/// // this is the fast path
739/// } else {
740/// // this path is unlikely
741/// cold_path();
742/// }
743/// }
744///
745/// fn bar(x: i32) -> i32 {
746/// match x {
747/// 1 => 10,
748/// 2 => 100,
749/// 3 => { cold_path(); 1000 }, // this branch is unlikely
750/// _ => { cold_path(); 10000 }, // this is also unlikely
751/// }
752/// }
753/// ```
754///
755/// This can also be used to implement `likely` and `unlikely` helpers to hint the condition rather
756/// than the branch:
757///
758/// ```
759/// #![feature(cold_path)]
760/// use core::hint::cold_path;
761///
762/// #[inline(always)]
763/// pub const fn likely(b: bool) -> bool {
764/// if !b {
765/// cold_path();
766/// }
767/// b
768/// }
769///
770/// #[inline(always)]
771/// pub const fn unlikely(b: bool) -> bool {
772/// if b {
773/// cold_path();
774/// }
775/// b
776/// }
777///
778/// fn foo(x: i32) {
779/// if likely(x > 0) {
780/// println!("this branch is likely to be taken");
781/// } else {
782/// println!("this branch is unlikely to be taken");
783/// }
784/// }
785/// ```
786#[unstable(feature = "cold_path", issue = "136873")]
787#[inline(always)]
788#[cfg(not(feature = "ferrocene_subset"))]
789pub const fn cold_path() {
790 crate::intrinsics::cold_path()
791}
792
793/// Returns either `true_val` or `false_val` depending on the value of
794/// `condition`, with a hint to the compiler that `condition` is unlikely to be
795/// correctly predicted by a CPU’s branch predictor.
796///
797/// This method is functionally equivalent to
798/// ```ignore (this is just for illustrative purposes)
799/// fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
800/// if b { true_val } else { false_val }
801/// }
802/// ```
803/// but might generate different assembly. In particular, on platforms with
804/// a conditional move or select instruction (like `cmov` on x86 or `csel`
805/// on ARM) the optimizer might use these instructions to avoid branches,
806/// which can benefit performance if the branch predictor is struggling
807/// with predicting `condition`, such as in an implementation of binary
808/// search.
809///
810/// Note however that this lowering is not guaranteed (on any platform) and
811/// should not be relied upon when trying to write cryptographic constant-time
812/// code. Also be aware that this lowering might *decrease* performance if
813/// `condition` is well-predictable. It is advisable to perform benchmarks to
814/// tell if this function is useful.
815///
816/// # Examples
817///
818/// Distribute values evenly between two buckets:
819/// ```
820/// use std::hash::BuildHasher;
821/// use std::hint;
822///
823/// fn append<H: BuildHasher>(hasher: &H, v: i32, bucket_one: &mut Vec<i32>, bucket_two: &mut Vec<i32>) {
824/// let hash = hasher.hash_one(&v);
825/// let bucket = hint::select_unpredictable(hash % 2 == 0, bucket_one, bucket_two);
826/// bucket.push(v);
827/// }
828/// # let hasher = std::collections::hash_map::RandomState::new();
829/// # let mut bucket_one = Vec::new();
830/// # let mut bucket_two = Vec::new();
831/// # append(&hasher, 42, &mut bucket_one, &mut bucket_two);
832/// # assert_eq!(bucket_one.len() + bucket_two.len(), 1);
833/// ```
834#[inline(always)]
835#[stable(feature = "select_unpredictable", since = "1.88.0")]
836#[rustc_const_unstable(feature = "const_select_unpredictable", issue = "145938")]
837pub const fn select_unpredictable<T>(condition: bool, true_val: T, false_val: T) -> T
838where
839 T: [const] Destruct,
840{
841 // FIXME(https://github.com/rust-lang/unsafe-code-guidelines/issues/245):
842 // Change this to use ManuallyDrop instead.
843 let mut true_val = MaybeUninit::new(true_val);
844 let mut false_val = MaybeUninit::new(false_val);
845
846 struct DropOnPanic<T> {
847 // Invariant: valid pointer and points to an initialized value that is not further used,
848 // i.e. it can be dropped by this guard.
849 inner: *mut T,
850 }
851
852 impl<T> Drop for DropOnPanic<T> {
853 fn drop(&mut self) {
854 // SAFETY: Must be guaranteed on construction of local type `DropOnPanic`.
855 unsafe { self.inner.drop_in_place() }
856 }
857 }
858
859 let true_ptr = true_val.as_mut_ptr();
860 let false_ptr = false_val.as_mut_ptr();
861
862 // SAFETY: The value that is not selected is dropped, and the selected one
863 // is returned. This is necessary because the intrinsic doesn't drop the
864 // value that is not selected.
865 unsafe {
866 // Extract the selected value first, ensure it is dropped as well if dropping the unselected
867 // value panics. We construct a temporary by-pointer guard around the selected value while
868 // dropping the unselected value. Arguments overlap here, so we can not use mutable
869 // reference for these arguments.
870 let guard = crate::intrinsics::select_unpredictable(condition, true_ptr, false_ptr);
871 let drop = crate::intrinsics::select_unpredictable(condition, false_ptr, true_ptr);
872
873 // SAFETY: both pointers are well-aligned and point to initialized values inside a
874 // `MaybeUninit` each. In both possible values for `condition` the pointer `guard` and
875 // `drop` do not alias (even though the two argument pairs we have selected from did alias
876 // each other).
877 let guard = DropOnPanic { inner: guard };
878 drop.drop_in_place();
879 crate::mem::forget(guard);
880
881 // Note that it is important to use the values here. Reading from the pointer we got makes
882 // LLVM forget the !unpredictable annotation sometimes (in tests, integer sized values in
883 // particular seemed to confuse it, also observed in llvm/llvm-project #82340).
884 crate::intrinsics::select_unpredictable(condition, true_val, false_val).assume_init()
885 }
886}
887
888/// The expected temporal locality of a memory prefetch operation.
889///
890/// Locality expresses how likely the prefetched data is to be reused soon,
891/// and therefore which level of cache it should be brought into.
892///
893/// The locality is just a hint, and may be ignored on some targets or by the hardware.
894///
895/// Used with functions like [`prefetch_read`] and [`prefetch_write`].
896///
897/// [`prefetch_read`]: crate::hint::prefetch_read
898/// [`prefetch_write`]: crate::hint::prefetch_write
899#[cfg(not(feature = "ferrocene_subset"))]
900#[unstable(feature = "hint_prefetch", issue = "146941")]
901#[non_exhaustive]
902#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
903pub enum Locality {
904 /// Data is expected to be reused eventually.
905 ///
906 /// Typically prefetches into L3 cache (if the CPU supports it).
907 L3,
908 /// Data is expected to be reused in the near future.
909 ///
910 /// Typically prefetches into L2 cache.
911 L2,
912 /// Data is expected to be reused very soon.
913 ///
914 /// Typically prefetches into L1 cache.
915 L1,
916}
917
918#[cfg(not(feature = "ferrocene_subset"))]
919impl Locality {
920 /// Convert to the constant that LLVM associates with a locality.
921 const fn to_llvm(self) -> i32 {
922 match self {
923 Self::L3 => 1,
924 Self::L2 => 2,
925 Self::L1 => 3,
926 }
927 }
928}
929
930/// Prefetch the cache line containing `ptr` for a future read.
931///
932/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
933/// soon after, but may also increase bandwidth usage or evict other cache lines.
934///
935/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
936///
937/// Passing a dangling or invalid pointer is permitted: the memory will not
938/// actually be dereferenced, and no faults are raised.
939///
940/// # Examples
941///
942/// ```
943/// #![feature(hint_prefetch)]
944/// use std::hint::{Locality, prefetch_read};
945/// use std::mem::size_of_val;
946///
947/// // Prefetch all of `slice` into the L1 cache.
948/// fn prefetch_slice<T>(slice: &[T]) {
949/// // On most systems the cache line size is 64 bytes.
950/// for offset in (0..size_of_val(slice)).step_by(64) {
951/// prefetch_read(slice.as_ptr().wrapping_add(offset), Locality::L1);
952/// }
953/// }
954/// ```
955#[cfg(not(feature = "ferrocene_subset"))]
956#[inline(always)]
957#[unstable(feature = "hint_prefetch", issue = "146941")]
958pub const fn prefetch_read<T>(ptr: *const T, locality: Locality) {
959 match locality {
960 Locality::L3 => intrinsics::prefetch_read_data::<T, { Locality::L3.to_llvm() }>(ptr),
961 Locality::L2 => intrinsics::prefetch_read_data::<T, { Locality::L2.to_llvm() }>(ptr),
962 Locality::L1 => intrinsics::prefetch_read_data::<T, { Locality::L1.to_llvm() }>(ptr),
963 }
964}
965
966/// Prefetch the cache line containing `ptr` for a single future read, but attempt to avoid
967/// polluting the cache.
968///
969/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
970/// soon after, but may also increase bandwidth usage or evict other cache lines.
971///
972/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
973///
974/// Passing a dangling or invalid pointer is permitted: the memory will not
975/// actually be dereferenced, and no faults are raised.
976#[cfg(not(feature = "ferrocene_subset"))]
977#[inline(always)]
978#[unstable(feature = "hint_prefetch", issue = "146941")]
979pub const fn prefetch_read_non_temporal<T>(ptr: *const T, locality: Locality) {
980 // The LLVM intrinsic does not currently support specifying the locality.
981 let _ = locality;
982 intrinsics::prefetch_read_data::<T, 0>(ptr)
983}
984
985/// Prefetch the cache line containing `ptr` for a future write.
986///
987/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
988/// soon after, but may also increase bandwidth usage or evict other cache lines.
989///
990/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
991///
992/// Passing a dangling or invalid pointer is permitted: the memory will not
993/// actually be dereferenced, and no faults are raised.
994#[cfg(not(feature = "ferrocene_subset"))]
995#[inline(always)]
996#[unstable(feature = "hint_prefetch", issue = "146941")]
997pub const fn prefetch_write<T>(ptr: *mut T, locality: Locality) {
998 match locality {
999 Locality::L3 => intrinsics::prefetch_write_data::<T, { Locality::L3.to_llvm() }>(ptr),
1000 Locality::L2 => intrinsics::prefetch_write_data::<T, { Locality::L2.to_llvm() }>(ptr),
1001 Locality::L1 => intrinsics::prefetch_write_data::<T, { Locality::L1.to_llvm() }>(ptr),
1002 }
1003}
1004
1005/// Prefetch the cache line containing `ptr` for a single future write, but attempt to avoid
1006/// polluting the cache.
1007///
1008/// A strategically placed prefetch can reduce cache miss latency if the data is accessed
1009/// soon after, but may also increase bandwidth usage or evict other cache lines.
1010///
1011/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
1012///
1013/// Passing a dangling or invalid pointer is permitted: the memory will not
1014/// actually be dereferenced, and no faults are raised.
1015#[cfg(not(feature = "ferrocene_subset"))]
1016#[inline(always)]
1017#[unstable(feature = "hint_prefetch", issue = "146941")]
1018pub const fn prefetch_write_non_temporal<T>(ptr: *const T, locality: Locality) {
1019 // The LLVM intrinsic does not currently support specifying the locality.
1020 let _ = locality;
1021 intrinsics::prefetch_write_data::<T, 0>(ptr)
1022}
1023
1024/// Prefetch the cache line containing `ptr` into the instruction cache for a future read.
1025///
1026/// A strategically placed prefetch can reduce cache miss latency if the instructions are
1027/// accessed soon after, but may also increase bandwidth usage or evict other cache lines.
1028///
1029/// A prefetch is a *hint*, and may be ignored on certain targets or by the hardware.
1030///
1031/// Passing a dangling or invalid pointer is permitted: the memory will not
1032/// actually be dereferenced, and no faults are raised.
1033#[cfg(not(feature = "ferrocene_subset"))]
1034#[inline(always)]
1035#[unstable(feature = "hint_prefetch", issue = "146941")]
1036pub const fn prefetch_read_instruction<T>(ptr: *const T, locality: Locality) {
1037 match locality {
1038 Locality::L3 => intrinsics::prefetch_read_instruction::<T, { Locality::L3.to_llvm() }>(ptr),
1039 Locality::L2 => intrinsics::prefetch_read_instruction::<T, { Locality::L2.to_llvm() }>(ptr),
1040 Locality::L1 => intrinsics::prefetch_read_instruction::<T, { Locality::L1.to_llvm() }>(ptr),
1041 }
1042}