]> git.lizzy.rs Git - rust.git/blob - library/core/src/hint.rs
Rollup merge of #102613 - TaKO8Ki:fix-part-of-101739, r=compiler-errors
[rust.git] / library / core / src / 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 //! Hints may be compile time or runtime.
5
6 use crate::intrinsics;
7
8 /// Informs the compiler that the site which is calling this function is not
9 /// reachable, possibly enabling further optimizations.
10 ///
11 /// # Safety
12 ///
13 /// Reaching this function is *Undefined Behavior*.
14 ///
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()`.
18 ///
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.
24 ///
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.
29 ///
30 /// # Examples
31 ///
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.
36 /// ```
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)
42 /// }
43 ///
44 /// /// # Safety
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()
55 ///         }
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.
61 ///         acc / divisor
62 ///     })
63 /// }
64 ///
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)
70 /// };
71 /// assert_eq!(result, 12);
72 ///
73 /// ```
74 ///
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.
80 ///
81 /// ```
82 /// fn div_1(a: u32, b: u32) -> u32 {
83 ///     use std::hint::unreachable_unchecked;
84 ///
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() })
90 /// }
91 ///
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);
95 /// ```
96 #[inline]
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() }
104 }
105
106 /// Emits a machine instruction to signal the processor that it is running in
107 /// a busy-wait spin-loop ("spin lock").
108 ///
109 /// Upon receiving the spin-loop signal the processor can optimize its behavior by,
110 /// for example, saving power or switching hyper-threads.
111 ///
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.
115 ///
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
120 /// syscall is made.
121 ///
122 /// **Note**: On platforms that do not support receiving spin-loop hints this
123 /// function does not do anything at all.
124 ///
125 /// # Examples
126 ///
127 /// ```
128 /// use std::sync::atomic::{AtomicBool, Ordering};
129 /// use std::sync::Arc;
130 /// use std::{hint, thread};
131 ///
132 /// // A shared atomic value that threads will use to coordinate
133 /// let live = Arc::new(AtomicBool::new(false));
134 ///
135 /// // In a background thread we'll eventually set the value
136 /// let bg_work = {
137 ///     let live = live.clone();
138 ///     thread::spawn(move || {
139 ///         // Do some work, then make the value live
140 ///         do_some_work();
141 ///         live.store(true, Ordering::Release);
142 ///     })
143 /// };
144 ///
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();
150 /// }
151 ///
152 /// // The value is now set
153 /// # fn do_some_work() {}
154 /// do_some_work();
155 /// bg_work.join()?;
156 /// # Ok::<(), Box<dyn core::any::Any + Send + 'static>>(())
157 /// ```
158 ///
159 /// [`thread::yield_now`]: ../../std/thread/fn.yield_now.html
160 #[inline]
161 #[stable(feature = "renamed_spin_loop", since = "1.49.0")]
162 pub fn spin_loop() {
163     #[cfg(target_arch = "x86")]
164     {
165         // SAFETY: the `cfg` attr ensures that we only execute this on x86 targets.
166         unsafe { crate::arch::x86::_mm_pause() };
167     }
168
169     #[cfg(target_arch = "x86_64")]
170     {
171         // SAFETY: the `cfg` attr ensures that we only execute this on x86_64 targets.
172         unsafe { crate::arch::x86_64::_mm_pause() };
173     }
174
175     // RISC-V platform spin loop hint implementation
176     {
177         // RISC-V RV32 and RV64 share the same PAUSE instruction, but they are located in different
178         // modules in `core::arch`.
179         // In this case, here we call `pause` function in each core arch module.
180         #[cfg(target_arch = "riscv32")]
181         {
182             crate::arch::riscv32::pause();
183         }
184         #[cfg(target_arch = "riscv64")]
185         {
186             crate::arch::riscv64::pause();
187         }
188     }
189
190     #[cfg(any(target_arch = "aarch64", all(target_arch = "arm", target_feature = "v6")))]
191     {
192         #[cfg(target_arch = "aarch64")]
193         {
194             // SAFETY: the `cfg` attr ensures that we only execute this on aarch64 targets.
195             unsafe { crate::arch::aarch64::__isb(crate::arch::aarch64::SY) };
196         }
197         #[cfg(target_arch = "arm")]
198         {
199             // SAFETY: the `cfg` attr ensures that we only execute this on arm targets
200             // with support for the v6 feature.
201             unsafe { crate::arch::arm::__yield() };
202         }
203     }
204 }
205
206 /// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
207 /// `black_box` could do.
208 ///
209 /// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
210 /// use `dummy` in any possible valid way that Rust code is allowed to without introducing undefined
211 /// behavior in the calling code. This property makes `black_box` useful for writing code in which
212 /// certain optimizations are not desired, such as benchmarks.
213 ///
214 /// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
215 /// extent to which it can block optimisations may vary depending upon the platform and code-gen
216 /// backend used. Programs cannot rely on `black_box` for *correctness* in any way.
217 ///
218 /// [`std::convert::identity`]: crate::convert::identity
219 #[inline]
220 #[stable(feature = "bench_black_box", since = "CURRENT_RUSTC_VERSION")]
221 #[rustc_const_unstable(feature = "const_black_box", issue = "none")]
222 pub const fn black_box<T>(dummy: T) -> T {
223     crate::intrinsics::black_box(dummy)
224 }
225
226 /// An identity function that causes an `unused_must_use` warning to be
227 /// triggered if the given value is not used (returned, stored in a variable,
228 /// etc) by the caller.
229 ///
230 /// This is primarily intended for use in macro-generated code, in which a
231 /// [`#[must_use]` attribute][must_use] either on a type or a function would not
232 /// be convenient.
233 ///
234 /// [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
235 ///
236 /// # Example
237 ///
238 /// ```
239 /// #![feature(hint_must_use)]
240 ///
241 /// use core::fmt;
242 ///
243 /// pub struct Error(/* ... */);
244 ///
245 /// #[macro_export]
246 /// macro_rules! make_error {
247 ///     ($($args:expr),*) => {
248 ///         core::hint::must_use({
249 ///             let error = $crate::make_error(core::format_args!($($args),*));
250 ///             error
251 ///         })
252 ///     };
253 /// }
254 ///
255 /// // Implementation detail of make_error! macro.
256 /// #[doc(hidden)]
257 /// pub fn make_error(args: fmt::Arguments<'_>) -> Error {
258 ///     Error(/* ... */)
259 /// }
260 ///
261 /// fn demo() -> Option<Error> {
262 ///     if true {
263 ///         // Oops, meant to write `return Some(make_error!("..."));`
264 ///         Some(make_error!("..."));
265 ///     }
266 ///     None
267 /// }
268 /// #
269 /// # // Make rustdoc not wrap the whole snippet in fn main, so that $crate::make_error works
270 /// # fn main() {}
271 /// ```
272 ///
273 /// In the above example, we'd like an `unused_must_use` lint to apply to the
274 /// value created by `make_error!`. However, neither `#[must_use]` on a struct
275 /// nor `#[must_use]` on a function is appropriate here, so the macro expands
276 /// using `core::hint::must_use` instead.
277 ///
278 /// - We wouldn't want `#[must_use]` on the `struct Error` because that would
279 ///   make the following unproblematic code trigger a warning:
280 ///
281 ///   ```
282 ///   # struct Error;
283 ///   #
284 ///   fn f(arg: &str) -> Result<(), Error>
285 ///   # { Ok(()) }
286 ///
287 ///   #[test]
288 ///   fn t() {
289 ///       // Assert that `f` returns error if passed an empty string.
290 ///       // A value of type `Error` is unused here but that's not a problem.
291 ///       f("").unwrap_err();
292 ///   }
293 ///   ```
294 ///
295 /// - Using `#[must_use]` on `fn make_error` can't help because the return value
296 ///   *is* used, as the right-hand side of a `let` statement. The `let`
297 ///   statement looks useless but is in fact necessary for ensuring that
298 ///   temporaries within the `format_args` expansion are not kept alive past the
299 ///   creation of the `Error`, as keeping them alive past that point can cause
300 ///   autotrait issues in async code:
301 ///
302 ///   ```
303 ///   # #![feature(hint_must_use)]
304 ///   #
305 ///   # struct Error;
306 ///   #
307 ///   # macro_rules! make_error {
308 ///   #     ($($args:expr),*) => {
309 ///   #         core::hint::must_use({
310 ///   #             // If `let` isn't used, then `f()` produces a non-Send future.
311 ///   #             let error = make_error(core::format_args!($($args),*));
312 ///   #             error
313 ///   #         })
314 ///   #     };
315 ///   # }
316 ///   #
317 ///   # fn make_error(args: core::fmt::Arguments<'_>) -> Error {
318 ///   #     Error
319 ///   # }
320 ///   #
321 ///   async fn f() {
322 ///       // Using `let` inside the make_error expansion causes temporaries like
323 ///       // `unsync()` to drop at the semicolon of that `let` statement, which
324 ///       // is prior to the await point. They would otherwise stay around until
325 ///       // the semicolon on *this* statement, which is after the await point,
326 ///       // and the enclosing Future would not implement Send.
327 ///       log(make_error!("look: {:p}", unsync())).await;
328 ///   }
329 ///
330 ///   async fn log(error: Error) {/* ... */}
331 ///
332 ///   // Returns something without a Sync impl.
333 ///   fn unsync() -> *const () {
334 ///       0 as *const ()
335 ///   }
336 ///   #
337 ///   # fn test() {
338 ///   #     fn assert_send(_: impl Send) {}
339 ///   #     assert_send(f());
340 ///   # }
341 ///   ```
342 #[unstable(feature = "hint_must_use", issue = "94745")]
343 #[rustc_const_unstable(feature = "hint_must_use", issue = "94745")]
344 #[must_use] // <-- :)
345 pub const fn must_use<T>(value: T) -> T {
346     value
347 }