]> git.lizzy.rs Git - rust.git/blob - src/libcore/hint.rs
Auto merge of #65140 - petrochenkov:disapp, r=nikomatsakis
[rust.git] / src / libcore / 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 use crate::intrinsics;
6
7 /// Informs the compiler that this point in the code is not reachable, enabling
8 /// further optimizations.
9 ///
10 /// # Safety
11 ///
12 /// Reaching this function is completely *undefined behavior* (UB). In
13 /// particular, the compiler assumes that all UB must never happen, and
14 /// therefore will eliminate all branches that reach to a call to
15 /// `unreachable_unchecked()`.
16 ///
17 /// Like all instances of UB, if this assumption turns out to be wrong, i.e., the
18 /// `unreachable_unchecked()` call is actually reachable among all possible
19 /// control flow, the compiler will apply the wrong optimization strategy, and
20 /// may sometimes even corrupt seemingly unrelated code, causing
21 /// difficult-to-debug problems.
22 ///
23 /// Use this function only when you can prove that the code will never call it.
24 /// Otherwise, consider using the [`unreachable!`] macro, which does not allow
25 /// optimizations but will panic when executed.
26 ///
27 /// [`unreachable!`]: ../macro.unreachable.html
28 ///
29 /// # Example
30 ///
31 /// ```
32 /// fn div_1(a: u32, b: u32) -> u32 {
33 ///     use std::hint::unreachable_unchecked;
34 ///
35 ///     // `b.saturating_add(1)` is always positive (not zero),
36 ///     // hence `checked_div` will never return `None`.
37 ///     // Therefore, the else branch is unreachable.
38 ///     a.checked_div(b.saturating_add(1))
39 ///         .unwrap_or_else(|| unsafe { unreachable_unchecked() })
40 /// }
41 ///
42 /// assert_eq!(div_1(7, 0), 7);
43 /// assert_eq!(div_1(9, 1), 4);
44 /// assert_eq!(div_1(11, std::u32::MAX), 0);
45 /// ```
46 #[inline]
47 #[stable(feature = "unreachable", since = "1.27.0")]
48 pub unsafe fn unreachable_unchecked() -> ! {
49     intrinsics::unreachable()
50 }
51
52 /// Emits a machine instruction hinting to the processor that it is running in busy-wait
53 /// spin-loop ("spin lock").
54 ///
55 /// For a discussion of different locking strategies and their trade-offs, see
56 /// [`core::sync::atomic::spin_loop_hint`].
57 ///
58 /// **Note**: On platforms that do not support receiving spin-loop hints this function does not
59 /// do anything at all.
60 ///
61 /// [`core::sync::atomic::spin_loop_hint`]: ../sync/atomic/fn.spin_loop_hint.html
62 #[inline]
63 #[unstable(feature = "renamed_spin_loop", issue = "55002")]
64 pub fn spin_loop() {
65     #[cfg(
66         all(
67             any(target_arch = "x86", target_arch = "x86_64"),
68             target_feature = "sse2"
69         )
70     )] {
71         #[cfg(target_arch = "x86")] {
72             unsafe { crate::arch::x86::_mm_pause() };
73         }
74
75         #[cfg(target_arch = "x86_64")] {
76             unsafe { crate::arch::x86_64::_mm_pause() };
77         }
78     }
79
80     #[cfg(
81         any(
82             target_arch = "aarch64",
83             all(target_arch = "arm", target_feature = "v6")
84         )
85     )] {
86         #[cfg(target_arch = "aarch64")] {
87             unsafe { crate::arch::aarch64::__yield() };
88         }
89         #[cfg(target_arch = "arm")] {
90             unsafe { crate::arch::arm::__yield() };
91         }
92     }
93 }
94
95 /// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
96 /// `black_box` could do.
97 ///
98 /// [`std::convert::identity`]: https://doc.rust-lang.org/core/convert/fn.identity.html
99 ///
100 /// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
101 /// use `x` in any possible valid way that Rust code is allowed to without introducing undefined
102 /// behavior in the calling code. This property makes `black_box` useful for writing code in which
103 /// certain optimizations are not desired, such as benchmarks.
104 ///
105 /// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
106 /// extent to which it can block optimisations may vary depending upon the platform and code-gen
107 /// backend used. Programs cannot rely on `black_box` for *correctness* in any way.
108 #[inline]
109 #[unstable(feature = "test", issue = "50297")]
110 #[allow(unreachable_code)] // this makes #[cfg] a bit easier below.
111 pub fn black_box<T>(dummy: T) -> T {
112     // We need to "use" the argument in some way LLVM can't introspect, and on
113     // targets that support it we can typically leverage inline assembly to do
114     // this. LLVM's intepretation of inline assembly is that it's, well, a black
115     // box. This isn't the greatest implementation since it probably deoptimizes
116     // more than we want, but it's so far good enough.
117     #[cfg(not(any(
118         target_arch = "asmjs",
119         all(
120             target_arch = "wasm32",
121             target_os = "emscripten"
122         )
123     )))]
124     unsafe {
125         asm!("" : : "r"(&dummy));
126         return dummy;
127     }
128
129     // Not all platforms support inline assembly so try to do something without
130     // inline assembly which in theory still hinders at least some optimizations
131     // on those targets. This is the "best effort" scenario.
132     unsafe {
133         let ret = crate::ptr::read_volatile(&dummy);
134         crate::mem::forget(dummy);
135         ret
136     }
137 }