1 #![stable(feature = "core_hint", since = "1.27.0")]
3 //! Hints to compiler that affects how code should be emitted or optimized.
4 //! Hints may be compile time or runtime.
8 /// Informs the compiler that the site which is calling this function is not
9 /// reachable, possibly enabling further optimizations.
13 /// Reaching this function is *Undefined Behavior*.
15 /// As the compiler assumes that all forms of Undefined Behavior can never
16 /// happen, it will eliminate all branches in the surrounding code that it can
17 /// determine will invariably lead to a call to `unreachable_unchecked()`.
19 /// If the assumptions embedded in using this function turn out to be wrong -
20 /// that is, if the site which is calling `unreachable_unchecked()` is actually
21 /// reachable at runtime - the compiler may have generated nonsensical machine
22 /// instructions for this situation, including in seemingly unrelated code,
23 /// causing difficult-to-debug problems.
25 /// Use this function sparingly. Consider using the [`unreachable!`] macro,
26 /// which may prevent some optimizations but will safely panic in case it is
27 /// actually reached at runtime. Benchmark your code to find out if using
28 /// `unreachable_unchecked()` comes with a performance benefit.
32 /// `unreachable_unchecked()` can be used in situations where the compiler
33 /// can't prove invariants that were previously established. Such situations
34 /// have a higher chance of occurring if those invariants are upheld by
35 /// external code that the compiler can't analyze.
37 /// fn prepare_inputs(divisors: &mut Vec<u32>) {
38 /// // Note to future-self when making changes: The invariant established
39 /// // here is NOT checked in `do_computation()`; if this changes, you HAVE
40 /// // to change `do_computation()`.
41 /// divisors.retain(|divisor| *divisor != 0)
45 /// /// All elements of `divisor` must be non-zero.
46 /// unsafe fn do_computation(i: u32, divisors: &[u32]) -> u32 {
47 /// divisors.iter().fold(i, |acc, divisor| {
48 /// // Convince the compiler that a division by zero can't happen here
49 /// // and a check is not needed below.
50 /// if *divisor == 0 {
51 /// // Safety: `divisor` can't be zero because of `prepare_inputs`,
52 /// // but the compiler does not know about this. We *promise*
53 /// // that we always call `prepare_inputs`.
54 /// std::hint::unreachable_unchecked()
56 /// // The compiler would normally introduce a check here that prevents
57 /// // a division by zero. However, if `divisor` was zero, the branch
58 /// // above would reach what we explicitly marked as unreachable.
59 /// // The compiler concludes that `divisor` can't be zero at this point
60 /// // and removes the - now proven useless - check.
65 /// let mut divisors = vec![2, 0, 4];
66 /// prepare_inputs(&mut divisors);
67 /// let result = unsafe {
68 /// // Safety: prepare_inputs() guarantees that divisors is non-zero
69 /// do_computation(100, &divisors)
71 /// assert_eq!(result, 12);
75 /// While using `unreachable_unchecked()` is perfectly sound in the following
76 /// example, the compiler is able to prove that a division by zero is not
77 /// possible. Benchmarking reveals that `unreachable_unchecked()` provides
78 /// no benefit over using [`unreachable!`], while the latter does not introduce
79 /// the possibility of Undefined Behavior.
82 /// fn div_1(a: u32, b: u32) -> u32 {
83 /// use std::hint::unreachable_unchecked;
85 /// // `b.saturating_add(1)` is always positive (not zero),
86 /// // hence `checked_div` will never return `None`.
87 /// // Therefore, the else branch is unreachable.
88 /// a.checked_div(b.saturating_add(1))
89 /// .unwrap_or_else(|| unsafe { unreachable_unchecked() })
92 /// assert_eq!(div_1(7, 0), 7);
93 /// assert_eq!(div_1(9, 1), 4);
94 /// assert_eq!(div_1(11, u32::MAX), 0);
97 #[stable(feature = "unreachable", since = "1.27.0")]
98 #[rustc_const_stable(feature = "const_unreachable_unchecked", since = "1.57.0")]
99 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
100 pub const unsafe fn unreachable_unchecked() -> ! {
101 // SAFETY: the safety contract for `intrinsics::unreachable` must
102 // be upheld by the caller.
103 unsafe { intrinsics::unreachable() }
106 /// Emits a machine instruction to signal the processor that it is running in
107 /// a busy-wait spin-loop ("spin lock").
109 /// Upon receiving the spin-loop signal the processor can optimize its behavior by,
110 /// for example, saving power or switching hyper-threads.
112 /// This function is different from [`thread::yield_now`] which directly
113 /// yields to the system's scheduler, whereas `spin_loop` does not interact
114 /// with the operating system.
116 /// A common use case for `spin_loop` is implementing bounded optimistic
117 /// spinning in a CAS loop in synchronization primitives. To avoid problems
118 /// like priority inversion, it is strongly recommended that the spin loop is
119 /// terminated after a finite amount of iterations and an appropriate blocking
122 /// **Note**: On platforms that do not support receiving spin-loop hints this
123 /// function does not do anything at all.
128 /// use std::sync::atomic::{AtomicBool, Ordering};
129 /// use std::sync::Arc;
130 /// use std::{hint, thread};
132 /// // A shared atomic value that threads will use to coordinate
133 /// let live = Arc::new(AtomicBool::new(false));
135 /// // In a background thread we'll eventually set the value
137 /// let live = live.clone();
138 /// thread::spawn(move || {
139 /// // Do some work, then make the value live
141 /// live.store(true, Ordering::Release);
145 /// // Back on our current thread, we wait for the value to be set
146 /// while !live.load(Ordering::Acquire) {
147 /// // The spin loop is a hint to the CPU that we're waiting, but probably
148 /// // not for very long
149 /// hint::spin_loop();
152 /// // The value is now set
153 /// # fn do_some_work() {}
156 /// # Ok::<(), Box<dyn core::any::Any + Send + 'static>>(())
159 /// [`thread::yield_now`]: ../../std/thread/fn.yield_now.html
161 #[stable(feature = "renamed_spin_loop", since = "1.49.0")]
163 #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "sse2"))]
165 #[cfg(target_arch = "x86")]
167 // SAFETY: the `cfg` attr ensures that we only execute this on x86 targets.
168 unsafe { crate::arch::x86::_mm_pause() };
171 #[cfg(target_arch = "x86_64")]
173 // SAFETY: the `cfg` attr ensures that we only execute this on x86_64 targets.
174 unsafe { crate::arch::x86_64::_mm_pause() };
178 // RISC-V platform spin loop hint implementation
180 // RISC-V RV32 and RV64 share the same PAUSE instruction, but they are located in different
181 // modules in `core::arch`.
182 // In this case, here we call `pause` function in each core arch module.
183 #[cfg(target_arch = "riscv32")]
185 crate::arch::riscv32::pause();
187 #[cfg(target_arch = "riscv64")]
189 crate::arch::riscv64::pause();
193 #[cfg(any(target_arch = "aarch64", all(target_arch = "arm", target_feature = "v6")))]
195 #[cfg(target_arch = "aarch64")]
197 // SAFETY: the `cfg` attr ensures that we only execute this on aarch64 targets.
198 unsafe { crate::arch::aarch64::__isb(crate::arch::aarch64::SY) };
200 #[cfg(target_arch = "arm")]
202 // SAFETY: the `cfg` attr ensures that we only execute this on arm targets
203 // with support for the v6 feature.
204 unsafe { crate::arch::arm::__yield() };
209 /// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
210 /// `black_box` could do.
212 /// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
213 /// use `dummy` in any possible valid way that Rust code is allowed to without introducing undefined
214 /// behavior in the calling code. This property makes `black_box` useful for writing code in which
215 /// certain optimizations are not desired, such as benchmarks.
217 /// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
218 /// extent to which it can block optimisations may vary depending upon the platform and code-gen
219 /// backend used. Programs cannot rely on `black_box` for *correctness* in any way.
221 /// [`std::convert::identity`]: crate::convert::identity
223 #[unstable(feature = "bench_black_box", issue = "64102")]
224 #[rustc_const_unstable(feature = "const_black_box", issue = "none")]
225 pub const fn black_box<T>(dummy: T) -> T {
226 crate::intrinsics::black_box(dummy)
229 /// An identity function that causes an `unused_must_use` warning to be
230 /// triggered if the given value is not used (returned, stored in a variable,
231 /// etc) by the caller.
233 /// This is primarily intended for use in macro-generated code, in which a
234 /// [`#[must_use]` attribute][must_use] either on a type or a function would not
237 /// [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
242 /// #![feature(hint_must_use)]
246 /// pub struct Error(/* ... */);
249 /// macro_rules! make_error {
250 /// ($($args:expr),*) => {
251 /// core::hint::must_use({
252 /// let error = $crate::make_error(core::format_args!($($args),*));
258 /// // Implementation detail of make_error! macro.
260 /// pub fn make_error(args: fmt::Arguments<'_>) -> Error {
264 /// fn demo() -> Option<Error> {
266 /// // Oops, meant to write `return Some(make_error!("..."));`
267 /// Some(make_error!("..."));
272 /// # // Make rustdoc not wrap the whole snippet in fn main, so that $crate::make_error works
276 /// In the above example, we'd like an `unused_must_use` lint to apply to the
277 /// value created by `make_error!`. However, neither `#[must_use]` on a struct
278 /// nor `#[must_use]` on a function is appropriate here, so the macro expands
279 /// using `core::hint::must_use` instead.
281 /// - We wouldn't want `#[must_use]` on the `struct Error` because that would
282 /// make the following unproblematic code trigger a warning:
287 /// fn f(arg: &str) -> Result<(), Error>
292 /// // Assert that `f` returns error if passed an empty string.
293 /// // A value of type `Error` is unused here but that's not a problem.
294 /// f("").unwrap_err();
298 /// - Using `#[must_use]` on `fn make_error` can't help because the return value
299 /// *is* used, as the right-hand side of a `let` statement. The `let`
300 /// statement looks useless but is in fact necessary for ensuring that
301 /// temporaries within the `format_args` expansion are not kept alive past the
302 /// creation of the `Error`, as keeping them alive past that point can cause
303 /// autotrait issues in async code:
306 /// # #![feature(hint_must_use)]
310 /// # macro_rules! make_error {
311 /// # ($($args:expr),*) => {
312 /// # core::hint::must_use({
313 /// # // If `let` isn't used, then `f()` produces a non-Send future.
314 /// # let error = make_error(core::format_args!($($args),*));
320 /// # fn make_error(args: core::fmt::Arguments<'_>) -> Error {
325 /// // Using `let` inside the make_error expansion causes temporaries like
326 /// // `unsync()` to drop at the semicolon of that `let` statement, which
327 /// // is prior to the await point. They would otherwise stay around until
328 /// // the semicolon on *this* statement, which is after the await point,
329 /// // and the enclosing Future would not implement Send.
330 /// log(make_error!("look: {:p}", unsync())).await;
333 /// async fn log(error: Error) {/* ... */}
335 /// // Returns something without a Sync impl.
336 /// fn unsync() -> *const () {
341 /// # fn assert_send(_: impl Send) {}
342 /// # assert_send(f());
345 #[unstable(feature = "hint_must_use", issue = "94745")]
346 #[rustc_const_unstable(feature = "hint_must_use", issue = "94745")]
347 #[must_use] // <-- :)
348 pub const fn must_use<T>(value: T) -> T {