core/intrinsics/mod.rs
1//! Compiler intrinsics.
2//!
3//! The functions in this module are implementation details of `core` and should
4//! not be used outside of the standard library. We generally provide access to
5//! intrinsics via stable wrapper functions. Use these instead.
6//!
7//! These are the imports making intrinsics available to Rust code. The actual implementations live in the compiler.
8//! Some of these intrinsics are lowered to MIR in <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_mir_transform/src/lower_intrinsics.rs>.
9//! The remaining intrinsics are implemented for the LLVM backend in <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs>
10//! and <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_codegen_llvm/src/intrinsic.rs>,
11//! and for const evaluation in <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_const_eval/src/interpret/intrinsics.rs>.
12//!
13//! Intrinsics don't need a body. However, they optionally can have a body, which we call the
14//! "fallback body". This will be used by codegen backends that do not have a dedicated
15//! implementation of the intrinsic, making it easier to add new intrinsics for specific operations
16//! without having to implement them in each codegen backend. The fallback body obviously has to be
17//! a valid implementation of the documented specification of the intrinsic. In some cases, the
18//! fallback body will be *equivalent* to the specification. Note that this is a strong requirement:
19//! if the spec says "UB if input `x` is even", then a valid implementation can just ignore this and
20//! do whatever it wants in that case; an *equivalent* implementation needs to actually check this
21//! condition and trigger UB in that case (e.g. by using `hint::assert_unchecked()`). Similar, if
22//! the spec says "returns `x` or `y` non-deterministically", then an *equivalent* implementation
23//! must actually do non-deterministic choice and return either value (e.g. by invoking some other
24//! language operation that has the same non-determinism). Intrinsics with such a fallback body that
25//! is equivalent to the spec may be marked with `#[miri::intrinsic_fallback_is_spec]`; the fallback
26//! body will then also be used by Miri for UB checking. When in doubt, do not use this attribute or
27//! ask the Miri maintainers for advice.
28//!
29//! Intrinsics are, in general, language extensions. Therefore, t-lang should be involved whenever a
30//! new intrinsic is exposed to stable code. However, if an intrinsic is marked
31//! `#[miri::intrinsic_fallback_is_spec]` with a fallback body that only uses stable features (or if
32//! such a fallback body could be written, but for one reason or another the actual fallback body is
33//! different), and if it also does not make other promises that go beyond observable program
34//! behavior (such as steering the optimizer in a particular direction), then an intrinsic may be
35//! used without t-lang involvement.
36//!
37//! # Const intrinsics
38//!
39//! In order to make an intrinsic unstable usable at compile-time, copy the implementation from
40//! <https://github.com/rust-lang/miri/blob/master/src/intrinsics> to
41//! <https://github.com/rust-lang/rust/blob/HEAD/compiler/rustc_const_eval/src/interpret/intrinsics.rs>
42//! and make the intrinsic declaration below a `const fn`. This should be done in coordination with
43//! wg-const-eval.
44//!
45//! If an intrinsic is supposed to be used from a `const fn` with a `rustc_const_stable` attribute,
46//! `#[rustc_intrinsic_const_stable_indirect]` needs to be added to the intrinsic. Such a change
47//! requires T-lang approval, because it may bake a feature into the language that cannot be
48//! replicated in user code without compiler support. The same exception as above applies for
49//! `#[miri::intrinsic_fallback_is_spec]` intrinsics.
50//!
51//! # Volatiles
52//!
53//! The volatile intrinsics provide operations intended to act on I/O
54//! memory, which are guaranteed to not be reordered by the compiler
55//! across other volatile intrinsics. See [`read_volatile`][ptr::read_volatile]
56//! and [`write_volatile`][ptr::write_volatile].
57//!
58//! # Atomics
59//!
60//! The atomic intrinsics provide common atomic operations on machine
61//! words, with multiple possible memory orderings. See the
62//! [atomic types][atomic] docs for details.
63//!
64//! # Unwinding
65//!
66//! Rust intrinsics may, in general, unwind. If an intrinsic can never unwind, add the
67//! `#[rustc_nounwind]` attribute so that the compiler can make use of this fact.
68//!
69//! However, even for intrinsics that may unwind, rustc assumes that a Rust intrinsics will never
70//! initiate a foreign (non-Rust) unwind, and thus for panic=abort we can always assume that these
71//! intrinsics cannot unwind.
72
73#![unstable(
74 feature = "core_intrinsics",
75 reason = "intrinsics are unlikely to ever be stabilized, instead \
76 they should be used through stabilized interfaces \
77 in the rest of the standard library",
78 issue = "none"
79)]
80
81use crate::ffi::{VaArgSafe, VaList};
82use crate::marker::{ConstParamTy, DiscriminantKind, PointeeSized, Tuple};
83use crate::num::imp::libm;
84use crate::{mem, ptr};
85
86mod bounds;
87pub mod fallback;
88pub mod gpu;
89mod macros;
90pub mod mir;
91pub mod reflection;
92pub mod simd;
93
94use macros::intrinsic_dispatch_on_type;
95
96// These imports are used for simplifying intra-doc links
97#[allow(unused_imports)]
98#[cfg(all(target_has_atomic = "8", target_has_atomic = "32", target_has_atomic = "ptr"))]
99use crate::sync::atomic::{
100 self, AtomicBool, AtomicI32, AtomicIsize, AtomicPtr, AtomicU32, Ordering,
101};
102
103/// A type for atomic ordering parameters for intrinsics. This is a separate type from
104/// `atomic::Ordering` so that we can make it `ConstParamTy` and fix the values used here without a
105/// risk of leaking that to stable code.
106#[allow(missing_docs)]
107#[derive(Debug, ConstParamTy, PartialEq, Eq)]
108pub enum AtomicOrdering {
109 // These values must match the compiler's `AtomicOrdering` defined in
110 // `rustc_middle/src/ty/consts/int.rs`!
111 Relaxed = 0,
112 Release = 1,
113 Acquire = 2,
114 AcqRel = 3,
115 SeqCst = 4,
116}
117
118// N.B., these intrinsics take raw pointers because they mutate aliased
119// memory, which is not valid for either `&` or `&mut`.
120
121/// Stores a value if the current value is the same as the `old` value,
122/// with the returned `T` being the previous value and the returned `bool` being
123/// whether the exchange was successful.
124/// `T` must be an integer or pointer type.
125///
126/// # Safety
127///
128/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::compare_exchange`].
129/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
130///
131/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::compare_exchange`],
132/// where `P` is the pointee type of the pointer.
133/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
134///
135/// The stabilized version of this intrinsic is available on the
136/// [`atomic`] types via the `compare_exchange` method.
137/// For example, [`AtomicBool::compare_exchange`].
138///
139/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
140/// [`Atomic<T>::compare_exchange`]: AtomicI32::compare_exchange
141/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
142/// [`AtomicPtr<P>::compare_exchange`]: AtomicPtr::compare_exchange
143#[rustc_intrinsic]
144#[rustc_nounwind]
145pub const unsafe fn atomic_cxchg<
146 T: Copy,
147 const ORD_SUCC: AtomicOrdering,
148 const ORD_FAIL: AtomicOrdering,
149>(
150 dst: *mut T,
151 old: T,
152 src: T,
153) -> (T, bool);
154
155/// Stores a value if the current value is the same as the `old` value,
156/// with the returned `T` being the previous value and the returned `bool` being
157/// whether the exchange was successful.
158/// `T` must be an integer or pointer type. The comparison may spuriously fail.
159///
160/// # Safety
161///
162/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::compare_exchange_weak`].
163/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
164///
165/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::compare_exchange_weak`],
166/// where `P` is the pointee type of the pointer.
167/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
168///
169/// The stabilized version of this intrinsic is available on the
170/// [`atomic`] types via the `compare_exchange_weak` method.
171/// For example, [`AtomicBool::compare_exchange_weak`].
172///
173/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
174/// [`Atomic<T>::compare_exchange_weak`]: AtomicI32::compare_exchange_weak
175/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
176/// [`AtomicPtr<P>::compare_exchange_weak`]: AtomicPtr::compare_exchange_weak
177#[rustc_intrinsic]
178#[rustc_nounwind]
179pub const unsafe fn atomic_cxchgweak<
180 T: Copy,
181 const ORD_SUCC: AtomicOrdering,
182 const ORD_FAIL: AtomicOrdering,
183>(
184 _dst: *mut T,
185 _old: T,
186 _src: T,
187) -> (T, bool);
188
189/// Loads the current value of the pointer.
190/// `T` must be an integer or pointer type.
191///
192/// # Safety
193///
194/// * If `VOLATILE` is `true`, this is equivalent to [`Atomic<T>::load_volatile`].
195/// Refer to the documentation of that method for safety requirements.
196///
197/// * If `VOLATILE` is `false`, this is equivalent to [`Atomic<T>::from_ptr`] followed
198/// by [`Atomic<T>::load`]. Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
199///
200/// The stabilized version of this intrinsic is available on the
201/// [`atomic`] types via the `load` method. For example, [`AtomicBool::load`].
202///
203/// [`Atomic<T>::load_volatile`]: AtomicI32::load_volatile
204/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
205/// [`Atomic<T>::load`]: AtomicI32::load
206#[rustc_intrinsic]
207#[rustc_nounwind]
208pub const unsafe fn atomic_load<T: Copy, const ORD: AtomicOrdering, const VOLATILE: bool>(
209 src: *const T,
210) -> T;
211
212/// Stores the value at the specified memory location.
213/// `T` must be an integer or pointer type.
214///
215/// # Safety
216///
217/// * If `VOLATILE` is `true`, this is equivalent to [`Atomic<T>::store_volatile`].
218/// Refer to the documentation of that method for safety requirements.
219///
220/// * If `VOLATILE` is `false`, this is equivalent to [`Atomic<T>::from_ptr`] followed
221/// by [`Atomic<T>::store`]. Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
222///
223/// The stabilized version of this intrinsic is available on the
224/// [`atomic`] types via the `store` method. For example, [`AtomicBool::store`].
225///
226/// [`Atomic<T>::store_volatile`]: AtomicI32::store_volatile
227/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
228/// [`Atomic<T>::store`]: AtomicI32::store
229#[rustc_intrinsic]
230#[rustc_nounwind]
231pub const unsafe fn atomic_store<T: Copy, const ORD: AtomicOrdering, const VOLATILE: bool>(
232 dst: *mut T,
233 val: T,
234);
235
236/// Stores the value at the specified memory location, returning the old value.
237/// `T` must be an integer or pointer type.
238///
239/// # Safety
240///
241/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::swap`].
242/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
243///
244/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::swap`],
245/// where `P` is the pointee type of the pointer.
246/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
247///
248/// The stabilized version of this intrinsic is available on the
249/// [`atomic`] types via the `swap` method. For example, [`AtomicBool::swap`].
250///
251/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
252/// [`Atomic<T>::swap`]: AtomicI32::swap
253/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
254/// [`AtomicPtr<P>::swap`]: AtomicPtr::swap
255#[rustc_intrinsic]
256#[rustc_nounwind]
257pub const unsafe fn atomic_xchg<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
258
259/// Adds to the current value, returning the previous value.
260/// `T` must be an integer or pointer type.
261/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
262///
263/// # Safety
264///
265/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_add`].
266/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
267///
268/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::fetch_byte_add`],
269/// where `P` is the pointee type of the pointer.
270/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
271///
272/// The stabilized version of this intrinsic is available on the
273/// [`atomic`] types via the `fetch_add` method. For example, [`AtomicIsize::fetch_add`].
274///
275/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
276/// [`Atomic<T>::fetch_add`]: AtomicI32::fetch_add
277/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
278/// [`AtomicPtr<P>::fetch_byte_add`]: AtomicPtr::fetch_byte_add
279#[rustc_intrinsic]
280#[rustc_nounwind]
281pub const unsafe fn atomic_xadd<T: Copy, U: Copy, const ORD: AtomicOrdering>(
282 dst: *mut T,
283 src: U,
284) -> T;
285
286/// Subtract from the current value, returning the previous value.
287/// `T` must be an integer or pointer type.
288/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
289///
290/// # Safety
291///
292/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_sub`].
293/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
294///
295/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::fetch_byte_sub`],
296/// where `P` is the pointee type of the pointer.
297/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
298///
299/// The stabilized version of this intrinsic is available on the
300/// [`atomic`] types via the `fetch_sub` method. For example, [`AtomicIsize::fetch_sub`].
301///
302/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
303/// [`Atomic<T>::fetch_sub`]: AtomicI32::fetch_sub
304/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
305/// [`AtomicPtr<P>::fetch_byte_sub`]: AtomicPtr::fetch_byte_sub
306#[rustc_intrinsic]
307#[rustc_nounwind]
308pub const unsafe fn atomic_xsub<T: Copy, U: Copy, const ORD: AtomicOrdering>(
309 dst: *mut T,
310 src: U,
311) -> T;
312
313/// Bitwise and with the current value, returning the previous value.
314/// `T` must be an integer or pointer type.
315/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
316///
317/// # Safety
318///
319/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_and`].
320/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
321///
322/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::fetch_and`],
323/// where `P` is the pointee type of the pointer.
324/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
325///
326/// The stabilized version of this intrinsic is available on the
327/// [`atomic`] types via the `fetch_and` method. For example, [`AtomicBool::fetch_and`].
328///
329/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
330/// [`Atomic<T>::fetch_and`]: AtomicI32::fetch_and
331/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
332/// [`AtomicPtr<P>::fetch_and`]: AtomicPtr::fetch_and
333#[rustc_intrinsic]
334#[rustc_nounwind]
335pub const unsafe fn atomic_and<T: Copy, U: Copy, const ORD: AtomicOrdering>(
336 dst: *mut T,
337 src: U,
338) -> T;
339
340/// Bitwise nand with the current value, returning the previous value.
341/// `T` must be an integer or pointer type.
342/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
343///
344/// # Safety
345///
346/// This is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_nand`].
347/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
348///
349/// The stabilized version of this intrinsic is available on the
350/// [`atomic`] types via the `fetch_nand` method. For example, [`AtomicBool::fetch_nand`].
351///
352/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
353/// [`Atomic<T>::fetch_nand`]: AtomicI32::fetch_nand
354#[rustc_intrinsic]
355#[rustc_nounwind]
356pub const unsafe fn atomic_nand<T: Copy, U: Copy, const ORD: AtomicOrdering>(
357 dst: *mut T,
358 src: U,
359) -> T;
360
361/// Bitwise or with the current value, returning the previous value.
362/// `T` must be an integer or pointer type.
363/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
364///
365/// # Safety
366///
367/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_or`].
368/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
369///
370/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::fetch_or`],
371/// where `P` is the pointee type of the pointer.
372/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
373///
374/// The stabilized version of this intrinsic is available on the
375/// [`atomic`] types via the `fetch_or` method. For example, [`AtomicBool::fetch_or`].
376///
377/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
378/// [`Atomic<T>::fetch_or`]: AtomicI32::fetch_or
379/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
380/// [`AtomicPtr<P>::fetch_or`]: AtomicPtr::fetch_or
381#[rustc_intrinsic]
382#[rustc_nounwind]
383pub const unsafe fn atomic_or<T: Copy, U: Copy, const ORD: AtomicOrdering>(
384 dst: *mut T,
385 src: U,
386) -> T;
387
388/// Bitwise xor with the current value, returning the previous value.
389/// `T` must be an integer or pointer type.
390/// `U` must be the same as `T` if that is an integer type, or `usize` if `T` is a pointer type.
391///
392/// # Safety
393///
394/// * If `T` is an integer type, this is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_xor`].
395/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
396///
397/// * If `T` is a pointer type, this is equivalent to [`AtomicPtr<P>::from_ptr`] followed by [`AtomicPtr<P>::fetch_xor`],
398/// where `P` is the pointee type of the pointer.
399/// Refer to the documentation of [`AtomicPtr<P>::from_ptr`] for safety requirements.
400///
401/// The stabilized version of this intrinsic is available on the
402/// [`atomic`] types via the `fetch_xor` method. For example, [`AtomicBool::fetch_xor`].
403///
404/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
405/// [`Atomic<T>::fetch_xor`]: AtomicI32::fetch_xor
406/// [`AtomicPtr<P>::from_ptr`]: AtomicPtr::from_ptr
407/// [`AtomicPtr<P>::fetch_xor`]: AtomicPtr::fetch_xor
408#[rustc_intrinsic]
409#[rustc_nounwind]
410pub const unsafe fn atomic_xor<T: Copy, U: Copy, const ORD: AtomicOrdering>(
411 dst: *mut T,
412 src: U,
413) -> T;
414
415/// Maximum with the current value using a signed comparison.
416/// `T` must be a signed integer type.
417///
418/// # Safety
419///
420/// This is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_max`].
421/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
422///
423/// The stabilized version of this intrinsic is available on the
424/// [`atomic`] signed integer types via the `fetch_max` method. For example, [`AtomicI32::fetch_max`].
425///
426/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
427/// [`Atomic<T>::fetch_max`]: AtomicI32::fetch_max
428#[rustc_intrinsic]
429#[rustc_nounwind]
430pub const unsafe fn atomic_max<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
431
432/// Minimum with the current value using a signed comparison.
433/// `T` must be a signed integer type.
434///
435/// # Safety
436///
437/// This is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_min`].
438/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
439///
440/// The stabilized version of this intrinsic is available on the
441/// [`atomic`] signed integer types via the `fetch_min` method. For example, [`AtomicI32::fetch_min`].
442///
443/// [`Atomic<T>::from_ptr`]: AtomicI32::from_ptr
444/// [`Atomic<T>::fetch_min`]: AtomicI32::fetch_min
445#[rustc_intrinsic]
446#[rustc_nounwind]
447pub const unsafe fn atomic_min<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
448
449/// Minimum with the current value using an unsigned comparison.
450/// `T` must be an unsigned integer type.
451///
452/// # Safety
453///
454/// This is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_min`].
455/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
456///
457/// The stabilized version of this intrinsic is available on the
458/// [`atomic`] unsigned integer types via the `fetch_min` method. For example, [`AtomicU32::fetch_min`].
459///
460/// [`Atomic<T>::from_ptr`]: AtomicU32::from_ptr
461/// [`Atomic<T>::fetch_min`]: AtomicU32::fetch_min
462#[rustc_intrinsic]
463#[rustc_nounwind]
464pub const unsafe fn atomic_umin<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
465
466/// Maximum with the current value using an unsigned comparison.
467/// `T` must be an unsigned integer type.
468///
469/// # Safety
470///
471/// This is equivalent to [`Atomic<T>::from_ptr`] followed by [`Atomic<T>::fetch_max`].
472/// Refer to the documentation of [`Atomic<T>::from_ptr`] for safety requirements.
473///
474/// The stabilized version of this intrinsic is available on the
475/// [`atomic`] unsigned integer types via the `fetch_max` method. For example, [`AtomicU32::fetch_max`].
476///
477/// [`Atomic<T>::from_ptr`]: AtomicU32::from_ptr
478/// [`Atomic<T>::fetch_max`]: AtomicU32::fetch_max
479#[rustc_intrinsic]
480#[rustc_nounwind]
481pub const unsafe fn atomic_umax<T: Copy, const ORD: AtomicOrdering>(dst: *mut T, src: T) -> T;
482
483/// An atomic fence.
484///
485/// The stabilized version of this intrinsic is available in
486/// [`atomic::fence`].
487#[rustc_intrinsic]
488#[rustc_nounwind]
489pub const unsafe fn atomic_fence<const ORD: AtomicOrdering>();
490
491/// An atomic fence for synchronization within a single thread.
492///
493/// The stabilized version of this intrinsic is available in
494/// [`atomic::compiler_fence`].
495#[rustc_intrinsic]
496#[rustc_nounwind]
497pub const unsafe fn atomic_singlethreadfence<const ORD: AtomicOrdering>();
498
499/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
500/// for the given address if supported; otherwise, it is a no-op.
501/// Prefetches have no effect on the behavior of the program but can change its performance
502/// characteristics.
503///
504/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
505/// to (3) - extremely local keep in cache.
506///
507/// This intrinsic does not have a stable counterpart.
508#[rustc_intrinsic]
509#[rustc_nounwind]
510#[miri::intrinsic_fallback_is_spec]
511pub const fn prefetch_read_data<T, const LOCALITY: i32>(data: *const T) {
512 // This operation is a no-op, unless it is overridden by the backend.
513 let _ = data;
514}
515
516/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
517/// for the given address if supported; otherwise, it is a no-op.
518/// Prefetches have no effect on the behavior of the program but can change its performance
519/// characteristics.
520///
521/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
522/// to (3) - extremely local keep in cache.
523///
524/// This intrinsic does not have a stable counterpart.
525#[rustc_intrinsic]
526#[rustc_nounwind]
527#[miri::intrinsic_fallback_is_spec]
528pub const fn prefetch_write_data<T, const LOCALITY: i32>(data: *const T) {
529 // This operation is a no-op, unless it is overridden by the backend.
530 let _ = data;
531}
532
533/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
534/// for the given address if supported; otherwise, it is a no-op.
535/// Prefetches have no effect on the behavior of the program but can change its performance
536/// characteristics.
537///
538/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
539/// to (3) - extremely local keep in cache.
540///
541/// This intrinsic does not have a stable counterpart.
542#[rustc_intrinsic]
543#[rustc_nounwind]
544#[miri::intrinsic_fallback_is_spec]
545pub const fn prefetch_read_instruction<T, const LOCALITY: i32>(data: *const T) {
546 // This operation is a no-op, unless it is overridden by the backend.
547 let _ = data;
548}
549
550/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
551/// for the given address if supported; otherwise, it is a no-op.
552/// Prefetches have no effect on the behavior of the program but can change its performance
553/// characteristics.
554///
555/// The `LOCALITY` argument is a temporal locality specifier ranging from (0) - no locality,
556/// to (3) - extremely local keep in cache.
557///
558/// This intrinsic does not have a stable counterpart.
559#[rustc_intrinsic]
560#[rustc_nounwind]
561#[miri::intrinsic_fallback_is_spec]
562pub const fn prefetch_write_instruction<T, const LOCALITY: i32>(data: *const T) {
563 // This operation is a no-op, unless it is overridden by the backend.
564 let _ = data;
565}
566
567/// Executes a breakpoint trap, for inspection by a debugger.
568///
569/// The public version of this intrinsic is [`core::arch::breakpoint`].
570#[rustc_intrinsic]
571#[rustc_nounwind]
572pub fn breakpoint();
573
574/// Executes a breakpoint trap, for inspection by a debugger. This is allowed to resume.
575///
576/// The public version of this intrinsic is [`core::process::resumable_breakpoint`].
577#[rustc_intrinsic]
578#[rustc_nounwind]
579#[miri::intrinsic_fallback_is_spec]
580pub const fn resumable_breakpoint() {}
581
582/// A container for the string arguments passed to [`codeview_annotation`].
583#[unstable(feature = "codeview_annotation", issue = "163964")]
584pub trait CodeViewAnnotationArgs {
585 /// The string arguments to `codeview_annotation`.
586 const ARGS: &[&str];
587}
588
589/// Emits a call to [`llvm.codeview.annotation`](https://llvm.org/docs/LangRef.html#llvm-codeview-annotation-intrinsic)
590/// which results in [`CodeViewAnnotationArgs::ARGS`] being written to the
591/// PDB as an `S_ANNOTATION` record.
592///
593/// Works only with targets that use PDB debuginfo and with the LLVM backend.
594/// Is a no-op on other targets and backends.
595#[unstable(feature = "codeview_annotation", issue = "163964")]
596#[rustc_intrinsic]
597#[rustc_nounwind]
598#[miri::intrinsic_fallback_is_spec]
599pub fn codeview_annotation<T: CodeViewAnnotationArgs>() {
600 // const block to catch any errors in `T::ARGS`
601 const {
602 let _ignore = T::ARGS;
603 }
604}
605
606/// Magic intrinsic that derives its meaning from attributes
607/// attached to the function.
608///
609/// For example, dataflow uses this to inject static assertions so
610/// that `rustc_peek(potentially_uninitialized)` would actually
611/// double-check that dataflow did indeed compute that it is
612/// uninitialized at that point in the control flow.
613///
614/// This intrinsic should not be used outside of the compiler.
615#[rustc_nounwind]
616#[rustc_intrinsic]
617pub fn rustc_peek<T>(_: T) -> T;
618
619/// Ungracefully aborts the execution of the process.
620///
621/// This is the intrinsic for directly implementing [`core::process::abort_immediate`] which, on
622/// most platforms, will invoke an invalid instruction. On Unix, the process will probably
623/// terminate with a signal like `SIGABRT`, `SIGILL`, `SIGTRAP`, `SIGSEGV` or `SIGBUS`. The
624/// precise behavior is not guaranteed and not stable.
625///
626/// [`std::process::abort`](../../std/process/fn.abort.html) is to be preferred if possible,
627/// as its behavior is more user-friendly and more stable.
628///
629/// Note that, unlike most intrinsics, this is safe to call; it does not require an `unsafe` block.
630/// Therefore, implementations must not require the user to uphold any safety invariants.
631///
632/// The stabilized version of this intrinsic is [`core::process::abort_immediate`].
633#[rustc_nounwind]
634#[rustc_intrinsic]
635pub const fn abort_immediate() -> !;
636
637/// Informs the optimizer that this point in the code is not reachable,
638/// enabling further optimizations.
639///
640/// N.B., this is very different from the `unreachable!()` macro: Unlike the
641/// macro, which panics when it is executed, it is *undefined behavior* to
642/// reach code marked with this function.
643///
644/// The stabilized version of this intrinsic is [`core::hint::unreachable_unchecked`].
645#[rustc_intrinsic_const_stable_indirect]
646#[rustc_nounwind]
647#[rustc_intrinsic]
648pub const unsafe fn unreachable() -> !;
649
650/// Informs the optimizer that a condition is always true.
651/// If the condition is false, the behavior is undefined.
652///
653/// No code is generated for this intrinsic, but the optimizer will try
654/// to preserve it (and its condition) between passes, which may interfere
655/// with optimization of surrounding code and reduce performance. It should
656/// not be used if the invariant can be discovered by the optimizer on its
657/// own, or if it does not enable any significant optimizations.
658///
659/// The stabilized version of this intrinsic is [`core::hint::assert_unchecked`].
660#[rustc_intrinsic_const_stable_indirect]
661#[rustc_nounwind]
662#[unstable(feature = "core_intrinsics", issue = "none")]
663#[rustc_intrinsic]
664pub const unsafe fn assume(b: bool) {
665 if !b {
666 // SAFETY: the caller must guarantee the argument is never `false`
667 unsafe { unreachable() }
668 }
669}
670
671/// Hints to the compiler that current code path is cold.
672///
673/// Note that, unlike most intrinsics, this is safe to call;
674/// it does not require an `unsafe` block.
675/// Therefore, implementations must not require the user to uphold
676/// any safety invariants.
677///
678/// The stabilized version of this intrinsic is [`core::hint::cold_path`].
679#[rustc_intrinsic]
680#[rustc_nounwind]
681#[miri::intrinsic_fallback_is_spec]
682#[cold]
683pub const fn cold_path() {}
684
685/// Hints to the compiler that branch condition is likely to be true.
686/// Returns the value passed to it.
687///
688/// Any use other than with `if` statements will probably not have an effect.
689///
690/// Note that, unlike most intrinsics, this is safe to call;
691/// it does not require an `unsafe` block.
692/// Therefore, implementations must not require the user to uphold
693/// any safety invariants.
694///
695/// This intrinsic does not have a stable counterpart.
696#[unstable(feature = "core_intrinsics", issue = "none")]
697#[rustc_nounwind]
698#[inline(always)]
699pub const fn likely(b: bool) -> bool {
700 if b {
701 true
702 } else {
703 cold_path();
704 false
705 }
706}
707
708/// Hints to the compiler that branch condition is likely to be false.
709/// Returns the value passed to it.
710///
711/// Any use other than with `if` statements will probably not have an effect.
712///
713/// Note that, unlike most intrinsics, this is safe to call;
714/// it does not require an `unsafe` block.
715/// Therefore, implementations must not require the user to uphold
716/// any safety invariants.
717///
718/// This intrinsic does not have a stable counterpart.
719#[unstable(feature = "core_intrinsics", issue = "none")]
720#[rustc_nounwind]
721#[inline(always)]
722pub const fn unlikely(b: bool) -> bool {
723 if b {
724 cold_path();
725 true
726 } else {
727 false
728 }
729}
730
731/// Returns either `true_val` or `false_val` depending on condition `b` with a
732/// hint to the compiler that this condition is unlikely to be correctly
733/// predicted by a CPU's branch predictor (e.g. a binary search).
734///
735/// This is otherwise functionally equivalent to `if b { true_val } else { false_val }`.
736///
737/// Note that, unlike most intrinsics, this is safe to call;
738/// it does not require an `unsafe` block.
739/// Therefore, implementations must not require the user to uphold
740/// any safety invariants.
741///
742/// The public form of this intrinsic is [`core::hint::select_unpredictable`].
743/// However unlike the public form, the intrinsic will not drop the value that
744/// is not selected.
745#[unstable(feature = "core_intrinsics", issue = "none")]
746#[rustc_const_unstable(feature = "const_select_unpredictable", issue = "145938")]
747#[rustc_intrinsic]
748#[rustc_nounwind]
749#[miri::intrinsic_fallback_is_spec]
750#[inline]
751pub const fn select_unpredictable<T>(b: bool, true_val: T, false_val: T) -> T {
752 if b {
753 forget(false_val);
754 true_val
755 } else {
756 forget(true_val);
757 false_val
758 }
759}
760
761/// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited:
762/// This will statically either panic, or do nothing. It does not *guarantee* to ever panic,
763/// and should only be called if an assertion failure will imply language UB in the following code.
764///
765/// This intrinsic does not have a stable counterpart.
766#[rustc_intrinsic_const_stable_indirect]
767#[rustc_nounwind]
768#[rustc_intrinsic]
769pub const fn assert_inhabited<T>();
770
771/// A guard for unsafe functions that cannot ever be executed if `T` does not permit
772/// zero-initialization: This will statically either panic, or do nothing. It does not *guarantee*
773/// to ever panic, and should only be called if an assertion failure will imply language UB in the
774/// following code.
775///
776/// This intrinsic does not have a stable counterpart.
777#[rustc_intrinsic_const_stable_indirect]
778#[rustc_nounwind]
779#[rustc_intrinsic]
780pub const fn assert_zero_valid<T>();
781
782/// A guard for `std::mem::uninitialized`. This will statically either panic, or do nothing. It does
783/// not *guarantee* to ever panic, and should only be called if an assertion failure will imply
784/// language UB in the following code.
785///
786/// This intrinsic does not have a stable counterpart.
787#[rustc_intrinsic_const_stable_indirect]
788#[rustc_nounwind]
789#[rustc_intrinsic]
790pub const fn assert_mem_uninitialized_valid<T>();
791
792/// Gets a reference to a static `Location` indicating where it was called.
793///
794/// Note that, unlike most intrinsics, this is safe to call;
795/// it does not require an `unsafe` block.
796/// Therefore, implementations must not require the user to uphold
797/// any safety invariants.
798///
799/// Consider using [`core::panic::Location::caller`] instead.
800#[rustc_intrinsic_const_stable_indirect]
801#[rustc_nounwind]
802#[rustc_intrinsic]
803pub const fn caller_location() -> &'static crate::panic::Location<'static>;
804
805/// Moves a value out of scope without running drop glue.
806///
807/// This exists solely for [`crate::mem::forget_unsized`]; normal `forget` uses
808/// `ManuallyDrop` instead.
809///
810/// Note that, unlike most intrinsics, this is safe to call;
811/// it does not require an `unsafe` block.
812/// Therefore, implementations must not require the user to uphold
813/// any safety invariants.
814#[rustc_intrinsic_const_stable_indirect]
815#[rustc_nounwind]
816#[rustc_intrinsic]
817pub const fn forget<T: ?Sized>(_: T);
818
819/// Reinterprets the bits of a value of one type as another type.
820///
821/// Both types must have the same size. Compilation will fail if this is not guaranteed.
822///
823/// `transmute` is semantically equivalent to a bitwise move of one type
824/// into another. It copies the bits from the source value into the
825/// destination value, then forgets the original. Note that source and destination
826/// are passed by-value, which means if `Src` or `Dst` contain padding, that padding
827/// is *not* guaranteed to be preserved by `transmute`.
828///
829/// Both the argument and the result must be [valid](../../nomicon/what-unsafe-does.html) at
830/// their given type. Violating this condition leads to [undefined behavior][ub]. The compiler
831/// will generate code *assuming that you, the programmer, ensure that there will never be
832/// undefined behavior*. It is therefore your responsibility to guarantee that every value
833/// passed to `transmute` is valid at both types `Src` and `Dst`. Failing to uphold this condition
834/// may lead to unexpected and unstable compilation results. This makes `transmute` **incredibly
835/// unsafe**. `transmute` should be the absolute last resort.
836///
837/// Because `transmute` is a by-value operation, alignment of the *transmuted values
838/// themselves* is not a concern. As with any other function, the compiler already ensures
839/// both `Src` and `Dst` are properly aligned. However, when transmuting values that *point
840/// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper
841/// alignment of the pointed-to values.
842///
843/// The [nomicon](../../nomicon/transmutes.html) has additional documentation.
844///
845/// [ub]: ../../reference/behavior-considered-undefined.html
846///
847/// # Transmutation between pointers and integers
848///
849/// Special care has to be taken when transmuting between pointers and integers, e.g.
850/// transmuting between `*const ()` and `usize`.
851///
852/// Transmuting *pointers to integers* in a `const` context is [undefined behavior][ub], unless
853/// the pointer was originally created *from* an integer. (That includes this function
854/// specifically, integer-to-pointer casts, and helpers like [`dangling`][crate::ptr::dangling],
855/// but also semantically-equivalent conversions such as punning through `repr(C)` union
856/// fields.) Any attempt to use the resulting value for integer operations will abort
857/// const-evaluation. (And even outside `const`, such transmutation is touching on many
858/// unspecified aspects of the Rust memory model and should be avoided. See below for
859/// alternatives.)
860///
861/// Transmuting *integers to pointers* is a largely unspecified operation. It is likely *not*
862/// equivalent to an `as` cast. Doing non-zero-sized memory accesses with a pointer constructed
863/// this way is currently considered undefined behavior.
864///
865/// All this also applies when the integer is nested inside an array, tuple, struct, or enum.
866/// However, `MaybeUninit<usize>` is not considered an integer type for the purpose of this
867/// section. Transmuting `*const ()` to `MaybeUninit<usize>` is fine---but then calling
868/// `assume_init()` on that result is considered as completing the pointer-to-integer transmute
869/// and thus runs into the issues discussed above.
870///
871/// In particular, doing a pointer-to-integer-to-pointer roundtrip via `transmute` is *not* a
872/// lossless process. If you want to round-trip a pointer through an integer in a way that you
873/// can get back the original pointer, you need to use `as` casts, or replace the integer type
874/// by `MaybeUninit<$int>` (and never call `assume_init()`). If you are looking for a way to
875/// store data of arbitrary type, also use `MaybeUninit<T>` (that will also handle uninitialized
876/// memory due to padding). If you specifically need to store something that is "either an
877/// integer or a pointer", use `*mut ()`: integers can be converted to pointers and back without
878/// any loss (via `as` casts or via `transmute`).
879///
880/// # Examples
881///
882/// There are a few things that `transmute` is really useful for.
883///
884/// Turning a pointer into a function pointer. This is *not* portable to
885/// machines where function pointers and data pointers have different sizes.
886///
887/// ```
888/// fn foo() -> i32 {
889/// 0
890/// }
891/// // Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
892/// // This avoids an integer-to-pointer `transmute`, which can be problematic.
893/// // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
894/// let pointer = foo as fn() -> i32 as *const ();
895/// let function = unsafe {
896/// std::mem::transmute::<*const (), fn() -> i32>(pointer)
897/// };
898/// assert_eq!(function(), 0);
899/// ```
900///
901/// Extending a lifetime, or shortening an invariant lifetime. This is
902/// advanced, very unsafe Rust!
903///
904/// ```
905/// struct R<'a>(&'a i32);
906/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
907/// unsafe { std::mem::transmute::<R<'b>, R<'static>>(r) }
908/// }
909///
910/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
911/// -> &'b mut R<'c> {
912/// unsafe { std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r) }
913/// }
914/// ```
915///
916/// # Alternatives
917///
918/// Don't despair: many uses of `transmute` can be achieved through other means.
919/// Below are common applications of `transmute` which can be replaced with safer
920/// constructs.
921///
922/// Turning raw bytes (`[u8; SZ]`) into `u32`, `f64`, etc.:
923///
924/// ```
925/// # #![allow(unnecessary_transmutes)]
926/// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
927///
928/// let num = unsafe {
929/// std::mem::transmute::<[u8; 4], u32>(raw_bytes)
930/// };
931///
932/// // use `u32::from_ne_bytes` instead
933/// let num = u32::from_ne_bytes(raw_bytes);
934/// // or use `u32::from_le_bytes` or `u32::from_be_bytes` to specify the endianness
935/// let num = u32::from_le_bytes(raw_bytes);
936/// assert_eq!(num, 0x12345678);
937/// let num = u32::from_be_bytes(raw_bytes);
938/// assert_eq!(num, 0x78563412);
939/// ```
940///
941/// Turning a pointer into a `usize`:
942///
943/// ```no_run
944/// let ptr = &0;
945/// let ptr_num_transmute = unsafe {
946/// std::mem::transmute::<&i32, usize>(ptr)
947/// };
948///
949/// // Use an `as` cast instead
950/// let ptr_num_cast = ptr as *const i32 as usize;
951/// ```
952///
953/// Note that using `transmute` to turn a pointer to a `usize` is (as noted above) [undefined
954/// behavior][ub] in `const` contexts. Also outside of consts, this operation might not behave
955/// as expected -- this is touching on many unspecified aspects of the Rust memory model.
956/// Depending on what the code is doing, the following alternatives are preferable to
957/// pointer-to-integer transmutation:
958/// - If the code just wants to store data of arbitrary type in some buffer and needs to pick a
959/// type for that buffer, it can use [`MaybeUninit`][crate::mem::MaybeUninit].
960/// - If the code actually wants to work on the address the pointer points to, it can use `as`
961/// casts or [`ptr.addr()`][pointer::addr].
962///
963/// Turning a `*mut T` into a `&mut T`:
964///
965/// ```
966/// let ptr: *mut i32 = &mut 0;
967/// let ref_transmuted = unsafe {
968/// std::mem::transmute::<*mut i32, &mut i32>(ptr)
969/// };
970///
971/// // Use a reborrow instead
972/// let ref_casted = unsafe { &mut *ptr };
973/// ```
974///
975/// Turning a `&mut T` into a `&mut U`:
976///
977/// ```
978/// let ptr = &mut 0;
979/// let val_transmuted = unsafe {
980/// std::mem::transmute::<&mut i32, &mut u32>(ptr)
981/// };
982///
983/// // Now, put together `as` and reborrowing - note the chaining of `as`
984/// // `as` is not transitive
985/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
986/// ```
987///
988/// Turning a `&str` into a `&[u8]`:
989///
990/// ```
991/// // this is not a good way to do this.
992/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
993/// assert_eq!(slice, &[82, 117, 115, 116]);
994///
995/// // You could use `str::as_bytes`
996/// let slice = "Rust".as_bytes();
997/// assert_eq!(slice, &[82, 117, 115, 116]);
998///
999/// // Or, just use a byte string, if you have control over the string
1000/// // literal
1001/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
1002/// ```
1003///
1004/// Turning a `Vec<&T>` into a `Vec<Option<&T>>`.
1005///
1006/// To transmute the inner type of the contents of a container, you must make sure to not
1007/// violate any of the container's invariants. For `Vec`, this means that both the size
1008/// *and alignment* of the inner types have to match. Other containers might rely on the
1009/// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't
1010/// be possible at all without violating the container invariants.
1011///
1012/// ```
1013/// let store = [0, 1, 2, 3];
1014/// let v_orig = store.iter().collect::<Vec<&i32>>();
1015///
1016/// // clone the vector as we will reuse them later
1017/// let v_clone = v_orig.clone();
1018///
1019/// // Using transmute: this relies on the unspecified data layout of `Vec`, which is a
1020/// // bad idea and could cause Undefined Behavior.
1021/// // However, it is no-copy.
1022/// let v_transmuted = unsafe {
1023/// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(v_clone)
1024/// };
1025///
1026/// let v_clone = v_orig.clone();
1027///
1028/// // This is the suggested, safe way.
1029/// // It may copy the entire vector into a new one though, but also may not.
1030/// let v_collected = v_clone.into_iter()
1031/// .map(Some)
1032/// .collect::<Vec<Option<&i32>>>();
1033///
1034/// let v_clone = v_orig.clone();
1035///
1036/// // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the
1037/// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but
1038/// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`),
1039/// // this has all the same caveats. Besides the information provided above, also consult the
1040/// // [`from_raw_parts`] documentation.
1041/// let (ptr, len, capacity) = v_clone.into_raw_parts();
1042/// let v_from_raw = unsafe {
1043/// Vec::from_raw_parts(ptr.cast::<*mut Option<&i32>>(), len, capacity)
1044/// };
1045/// ```
1046///
1047/// [`from_raw_parts`]: ../../std/vec/struct.Vec.html#method.from_raw_parts
1048///
1049/// Implementing `split_at_mut`:
1050///
1051/// ```
1052/// use std::{slice, mem};
1053///
1054/// // There are multiple ways to do this, and there are multiple problems
1055/// // with the following (transmute) way.
1056/// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
1057/// -> (&mut [T], &mut [T]) {
1058/// let len = slice.len();
1059/// assert!(mid <= len);
1060/// unsafe {
1061/// let slice2 = mem::transmute::<&mut [T], &mut [T]>(slice);
1062/// // first: transmute is not type safe; all it checks is that T and
1063/// // U are of the same size. Second, right here, you have two
1064/// // mutable references pointing to the same memory.
1065/// (&mut slice[0..mid], &mut slice2[mid..len])
1066/// }
1067/// }
1068///
1069/// // This gets rid of the type safety problems; `&mut *` will *only* give
1070/// // you a `&mut T` from a `&mut T` or `*mut T`.
1071/// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
1072/// -> (&mut [T], &mut [T]) {
1073/// let len = slice.len();
1074/// assert!(mid <= len);
1075/// unsafe {
1076/// let slice2 = &mut *(slice as *mut [T]);
1077/// // however, you still have two mutable references pointing to
1078/// // the same memory.
1079/// (&mut slice[0..mid], &mut slice2[mid..len])
1080/// }
1081/// }
1082///
1083/// // This is how the standard library does it. This is the best method, if
1084/// // you need to do something like this
1085/// fn split_at_stdlib<T>(to_split: &mut [T], mid: usize)
1086/// -> (&mut [T], &mut [T]) {
1087/// let len = to_split.len();
1088/// assert!(mid <= len);
1089/// unsafe {
1090/// let ptr = to_split.as_mut_ptr();
1091/// let fst = slice::from_raw_parts_mut(ptr, mid);
1092/// let snd = slice::from_raw_parts_mut(ptr.add(mid), len - mid);
1093/// // The function now has three mutable references to overlapping memory:
1094/// // `to_split`, `fst`, and `snd`.
1095/// // `to_split` is never used after `let ptr = ...` so it can be treated as "dead".
1096/// // This leaves two "live" mutable slice references, `fst` and `snd`, with no overlap.
1097/// (fst, snd)
1098/// }
1099/// }
1100/// ```
1101#[stable(feature = "rust1", since = "1.0.0")]
1102#[rustc_allowed_through_unstable_modules(
1103 message = "import this function via the `mem` module instead",
1104 module = "mem"
1105)]
1106#[rustc_const_stable(feature = "const_transmute", since = "1.56.0")]
1107#[rustc_diagnostic_item = "transmute"]
1108#[rustc_nounwind]
1109#[rustc_intrinsic]
1110pub const unsafe fn transmute<Src, Dst>(src: Src) -> Dst;
1111
1112/// Like [`transmute`], but even less checked at compile-time: rather than
1113/// giving an error for `size_of::<Src>() != size_of::<Dst>()`, it's
1114/// **Undefined Behavior** at runtime.
1115///
1116/// Prefer normal `transmute` where possible, for the extra checking, since
1117/// both do exactly the same thing at runtime, if they both compile.
1118///
1119/// This is not expected to ever be exposed directly to users, rather it
1120/// may eventually be exposed through some more-constrained API.
1121#[rustc_intrinsic_const_stable_indirect]
1122#[rustc_nounwind]
1123#[rustc_intrinsic]
1124pub const unsafe fn transmute_unchecked<Src, Dst>(src: Src) -> Dst;
1125
1126/// Returns `true` if the actual type given as `T` requires drop
1127/// glue; returns `false` if the actual type provided for `T`
1128/// implements `Copy`.
1129///
1130/// If the actual type neither requires drop glue nor implements
1131/// `Copy`, then the return value of this function is unspecified.
1132///
1133/// Note that, unlike most intrinsics, this can only be called at compile-time
1134/// as backends do not have an implementation for it. The only caller (its
1135/// stable counterpart) wraps this intrinsic call in a `const` block so that
1136/// backends only see an evaluated constant.
1137///
1138/// The stabilized version of this intrinsic is [`mem::needs_drop`](crate::mem::needs_drop).
1139#[rustc_intrinsic_const_stable_indirect]
1140#[rustc_nounwind]
1141#[rustc_intrinsic]
1142#[rustc_comptime]
1143pub fn needs_drop<T: ?Sized>() -> bool;
1144
1145/// Calculates the offset from a pointer.
1146///
1147/// This is implemented as an intrinsic to avoid converting to and from an
1148/// integer, since the conversion would throw away aliasing information.
1149///
1150/// This can only be used with `Ptr` as a raw pointer type (`*mut` or `*const`)
1151/// to a `Sized` pointee and with `Delta` as `usize` or `isize`. Any other
1152/// instantiations may arbitrarily misbehave, and that's *not* a compiler bug.
1153///
1154/// # Safety
1155///
1156/// If the computed offset is non-zero, then both the starting and resulting pointer must be
1157/// either in bounds or at the end of an allocation. If either pointer is out
1158/// of bounds or arithmetic overflow occurs then this operation is undefined behavior.
1159///
1160/// The stabilized version of this intrinsic is [`pointer::offset`].
1161#[must_use = "returns a new pointer rather than modifying its argument"]
1162#[rustc_intrinsic_const_stable_indirect]
1163#[rustc_nounwind]
1164#[rustc_intrinsic]
1165pub const unsafe fn offset<Ptr: bounds::BuiltinDeref, Delta>(dst: Ptr, offset: Delta) -> Ptr;
1166
1167/// Calculates the offset from a pointer, potentially wrapping.
1168///
1169/// This is implemented as an intrinsic to avoid converting to and from an
1170/// integer, since the conversion inhibits certain optimizations.
1171///
1172/// # Safety
1173///
1174/// Unlike the `offset` intrinsic, this intrinsic does not restrict the
1175/// resulting pointer to point into or at the end of an allocated
1176/// object, and it wraps with two's complement arithmetic. The resulting
1177/// value is not necessarily valid to be used to actually access memory.
1178///
1179/// The stabilized version of this intrinsic is [`pointer::wrapping_offset`].
1180#[must_use = "returns a new pointer rather than modifying its argument"]
1181#[rustc_intrinsic_const_stable_indirect]
1182#[rustc_nounwind]
1183#[rustc_intrinsic]
1184pub const unsafe fn arith_offset<T>(dst: *const T, offset: isize) -> *const T;
1185
1186/// Projects to the `index`-th element of `slice_ptr`, as the same kind of pointer
1187/// as the slice was provided -- so `&mut [T] → &mut T`, `&[T] → &T`,
1188/// `*mut [T] → *mut T`, or `*const [T] → *const T` -- without a bounds check.
1189///
1190/// This is exposed via `<usize as SliceIndex>::get(_unchecked)(_mut)`,
1191/// and isn't intended to be used elsewhere.
1192///
1193/// Expands in MIR to `{&, &mut, &raw const, &raw mut} (*slice_ptr)[index]`,
1194/// depending on the types involved, so no backend support is needed.
1195///
1196/// # Safety
1197///
1198/// - `index < PtrMetadata(slice_ptr)`, so the indexing is in-bounds for the slice
1199/// - the resulting offsetting is in-bounds of the allocation, which is
1200/// always the case for references, but needs to be upheld manually for pointers
1201#[rustc_nounwind]
1202#[rustc_intrinsic]
1203pub const unsafe fn slice_get_unchecked<
1204 ItemPtr: bounds::ChangePointee<[T], Pointee = T, Output = SlicePtr>,
1205 SlicePtr,
1206 T,
1207>(
1208 slice_ptr: SlicePtr,
1209 index: usize,
1210) -> ItemPtr;
1211
1212/// Masks out bits of the pointer according to a mask.
1213///
1214/// Note that, unlike most intrinsics, this is safe to call;
1215/// it does not require an `unsafe` block.
1216/// Therefore, implementations must not require the user to uphold
1217/// any safety invariants.
1218///
1219/// Consider using [`pointer::mask`] instead.
1220#[rustc_nounwind]
1221#[rustc_intrinsic]
1222pub fn ptr_mask<T>(ptr: *const T, mask: usize) -> *const T;
1223
1224/// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with
1225/// a size of `count` * `size_of::<T>()` and an alignment of `align_of::<T>()`.
1226///
1227/// This intrinsic does not have a stable counterpart.
1228/// # Safety
1229///
1230/// The safety requirements are consistent with [`copy_nonoverlapping`]
1231/// while the read and write behaviors are volatile,
1232/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
1233///
1234/// [`copy_nonoverlapping`]: ptr::copy_nonoverlapping
1235#[rustc_intrinsic]
1236#[rustc_nounwind]
1237pub unsafe fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize);
1238/// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with
1239/// a size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
1240///
1241/// The volatile parameter is set to `true`, so it will not be optimized out
1242/// unless size is equal to zero.
1243///
1244/// This intrinsic does not have a stable counterpart.
1245#[rustc_intrinsic]
1246#[rustc_nounwind]
1247pub unsafe fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize);
1248/// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a
1249/// size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
1250///
1251/// This intrinsic does not have a stable counterpart.
1252/// # Safety
1253///
1254/// The safety requirements are consistent with [`write_bytes`] while the write behavior is volatile,
1255/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
1256///
1257/// [`write_bytes`]: ptr::write_bytes
1258#[rustc_intrinsic]
1259#[rustc_nounwind]
1260pub const unsafe fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize);
1261
1262/// Performs a volatile load from the `src` pointer.
1263///
1264/// The stabilized version of this intrinsic is [`core::ptr::read_volatile`].
1265#[rustc_intrinsic]
1266#[rustc_nounwind]
1267pub const unsafe fn volatile_load<T>(src: *const T) -> T;
1268/// Performs a volatile store to the `dst` pointer.
1269///
1270/// The stabilized version of this intrinsic is [`core::ptr::write_volatile`].
1271#[rustc_intrinsic]
1272#[rustc_nounwind]
1273pub const unsafe fn volatile_store<T>(dst: *mut T, val: T);
1274
1275/// Performs a volatile load from the `src` pointer
1276/// The pointer is not required to be aligned.
1277///
1278/// This intrinsic does not have a stable counterpart.
1279#[rustc_intrinsic]
1280#[rustc_nounwind]
1281#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_load"]
1282pub unsafe fn unaligned_volatile_load<T>(src: *const T) -> T;
1283/// Performs a volatile store to the `dst` pointer.
1284/// The pointer is not required to be aligned.
1285///
1286/// This intrinsic does not have a stable counterpart.
1287#[rustc_intrinsic]
1288#[rustc_nounwind]
1289#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_store"]
1290pub unsafe fn unaligned_volatile_store<T>(dst: *mut T, val: T);
1291
1292intrinsic_dispatch_on_type! {
1293 /// Returns the square root of a floating-point value.
1294 ///
1295 /// The stabilized versions of this intrinsic are available on the float primitives via the
1296 /// `sqrt` method. For example, [`f32::sqrt`](../../std/primitive.f32.html#method.sqrt).
1297 #[rustc_nounwind]
1298 #[rustc_intrinsic]
1299 pub fn sqrt<T: bounds::FloatPrimitive>(x: T) -> T;
1300
1301 f16 => { libm::sqrtf16(x) }
1302 f32 => { libm::sqrtf(x) }
1303 f64 => { libm::sqrt(x) }
1304 f128 => { libm::sqrtf128(x) }
1305}
1306
1307intrinsic_dispatch_on_type! {
1308 /// Raises a floating-point value to an integer power.
1309 ///
1310 /// The stabilized versions of this intrinsic are available on the float primitives via the
1311 /// `powi` method. For example, [`f32::powi`](../../std/primitive.f32.html#method.powi).
1312 #[rustc_nounwind]
1313 #[inline]
1314 #[rustc_intrinsic]
1315 pub fn powi<T: bounds::FloatPrimitive>(a: T, x: i32) -> T;
1316
1317 f16 => { powi(a as f32, x) as f16 }
1318 f32 => { libm::__powisf2(a, x) }
1319 f64 => { libm::__powidf2(a, x) }
1320 f128 => { libm::__powitf2(a, x) }
1321}
1322
1323intrinsic_dispatch_on_type! {
1324 /// Returns the sine of a floating-point value.
1325 ///
1326 /// The stabilized versions of this intrinsic are available on the float primitives via the
1327 /// `sin` method. For example, [`f32::sin`](../../std/primitive.f32.html#method.sin).
1328 #[rustc_nounwind]
1329 #[inline]
1330 #[rustc_intrinsic]
1331 pub fn sin<T: bounds::FloatPrimitive>(x: T) -> T;
1332
1333 f16 => { sin(x as f32) as f16 }
1334 f32 => {
1335 cfg_select! {
1336 all(target_env = "msvc", target_arch = "x86") => sin(x as f64) as f32,
1337 _ => libm::likely_available::sinf(x),
1338 }
1339 }
1340 f64 => { libm::likely_available::sin(x) }
1341 f128 => { libm::maybe_available::sinf128(x) }
1342}
1343
1344intrinsic_dispatch_on_type! {
1345 /// Returns the cosine of a floating-point value.
1346 ///
1347 /// The stabilized versions of this intrinsic are available on the float primitives via the
1348 /// `cos` method. For example, [`f32::cos`](../../std/primitive.f32.html#method.cos).
1349 #[rustc_nounwind]
1350 #[inline]
1351 #[rustc_intrinsic]
1352 pub fn cos<T: bounds::FloatPrimitive>(x: T) -> T;
1353
1354 f16 => { cos(x as f32) as f16 }
1355 f32 => {
1356 cfg_select! {
1357 all(target_env = "msvc", target_arch = "x86") => cos(x as f64) as f32,
1358 _ => libm::likely_available::cosf(x),
1359 }
1360 }
1361 f64 => { libm::likely_available::cos(x) }
1362 f128 => { libm::maybe_available::cosf128(x) }
1363}
1364
1365intrinsic_dispatch_on_type! {
1366 /// Raises a floating-point value to a power of the same type.
1367 ///
1368 /// The stabilized versions of this intrinsic are available on the float primitives via the
1369 /// `powf` method. For example, [`f32::powf`](../../std/primitive.f32.html#method.powf).
1370 #[rustc_nounwind]
1371 #[inline]
1372 #[rustc_intrinsic]
1373 pub fn powf<T: bounds::FloatPrimitive>(a: T, x: T) -> T;
1374
1375 f16 => { powf(a as f32, x as f32) as f16 }
1376 f32 => {
1377 cfg_select! {
1378 all(target_env = "msvc", target_arch = "x86") => powf(a as f64, x as f64) as f32,
1379 _ => libm::likely_available::powf(a, x),
1380 }
1381 }
1382 f64 => { libm::likely_available::pow(a, x) }
1383 f128 => { libm::maybe_available::powf128(a, x) }
1384}
1385
1386intrinsic_dispatch_on_type! {
1387 /// Returns the exponential of a floating-point value.
1388 ///
1389 /// The stabilized versions of this intrinsic are available on the float primitives via the
1390 /// `exp` method. For example, [`f32::exp`](../../std/primitive.f32.html#method.exp).
1391 #[rustc_nounwind]
1392 #[inline]
1393 #[rustc_intrinsic]
1394 pub fn exp<T: bounds::FloatPrimitive>(x: T) -> T;
1395
1396 f16 => { exp(x as f32) as f16 }
1397 f32 => {
1398 cfg_select! {
1399 all(target_env = "msvc", target_arch = "x86") => exp(x as f64) as f32,
1400 _ => libm::likely_available::expf(x),
1401 }
1402 }
1403 f64 => { libm::likely_available::exp(x) }
1404 f128 => { libm::maybe_available::expf128(x) }
1405}
1406
1407intrinsic_dispatch_on_type! {
1408 /// Returns 2 raised to the power of a floating-point value.
1409 ///
1410 /// The stabilized versions of this intrinsic are available on the float primitives via the
1411 /// `exp2` method. For example, [`f32::exp2`](../../std/primitive.f32.html#method.exp2).
1412 #[rustc_nounwind]
1413 #[inline]
1414 #[rustc_intrinsic]
1415 pub fn exp2<T: bounds::FloatPrimitive>(x: T) -> T;
1416
1417 f16 => { exp2(x as f32) as f16 }
1418 f32 => {
1419 cfg_select! {
1420 all(target_env = "msvc", target_arch = "x86") => exp2(x as f64) as f32,
1421 _ => libm::likely_available::exp2f(x),
1422 }
1423 }
1424 f64 => { libm::likely_available::exp2(x) }
1425 f128 => { libm::maybe_available::exp2f128(x) }
1426}
1427
1428intrinsic_dispatch_on_type! {
1429 /// Returns the natural logarithm of a floating-point value.
1430 ///
1431 /// The stabilized versions of this intrinsic are available on the float primitives via the
1432 /// `ln` method. For example, [`f32::ln`](../../std/primitive.f32.html#method.ln).
1433 #[rustc_nounwind]
1434 #[inline]
1435 #[rustc_intrinsic]
1436 pub fn log<T: bounds::FloatPrimitive>(x: T) -> T;
1437
1438 f16 => { log(x as f32) as f16 }
1439 f32 => {
1440 cfg_select! {
1441 all(target_env = "msvc", target_arch = "x86") => log(x as f64) as f32,
1442 _ => libm::likely_available::logf(x),
1443 }
1444 }
1445 f64 => { libm::likely_available::log(x) }
1446 f128 => { libm::maybe_available::logf128(x) }
1447}
1448
1449intrinsic_dispatch_on_type! {
1450 /// Returns the base 10 logarithm of a floating-point value.
1451 ///
1452 /// The stabilized versions of this intrinsic are available on the float primitives via the
1453 /// `log10` method. For example, [`f32::log10`](../../std/primitive.f32.html#method.log10).
1454 #[rustc_nounwind]
1455 #[inline]
1456 #[rustc_intrinsic]
1457 pub fn log10<T: bounds::FloatPrimitive>(x: T) -> T;
1458
1459 f16 => { log10(x as f32) as f16 }
1460 f32 => {
1461 cfg_select! {
1462 all(target_env = "msvc", target_arch = "x86") => log10(x as f64) as f32,
1463 _ => libm::likely_available::log10f(x),
1464 }
1465 }
1466 f64 => { libm::likely_available::log10(x) }
1467 f128 => { libm::maybe_available::log10f128(x) }
1468}
1469
1470intrinsic_dispatch_on_type! {
1471 /// Returns the base 2 logarithm of a floating-point value.
1472 ///
1473 /// The stabilized versions of this intrinsic are available on the float primitives via the
1474 /// `log2` method. For example, [`f32::log2`](../../std/primitive.f32.html#method.log2).
1475 #[rustc_nounwind]
1476 #[inline]
1477 #[rustc_intrinsic]
1478 pub fn log2<T: bounds::FloatPrimitive>(x: T) -> T;
1479
1480 f16 => { log2(x as f32) as f16 }
1481 f32 => {
1482 cfg_select! {
1483 all(target_env = "msvc", target_arch = "x86") => log2(x as f64) as f32,
1484 _ => libm::likely_available::log2f(x),
1485 }
1486 }
1487 f64 => { libm::likely_available::log2(x) }
1488 f128 => { libm::maybe_available::log2f128(x) }
1489}
1490
1491intrinsic_dispatch_on_type! {
1492 /// Returns `a * b + c` without rounding the intermediate result.
1493 ///
1494 /// The stabilized versions of this intrinsic are available on the float primitives via the
1495 /// `mul_add` method. For example,
1496 /// [`f32::mul_add`](../../std/primitive.f32.html#method.mul_add).
1497 #[rustc_nounwind]
1498 #[inline]
1499 #[rustc_intrinsic_const_stable_indirect]
1500 #[rustc_intrinsic]
1501 // The fallback bodies call into `libm`, which is not available at compile time. This is fine
1502 // because const-eval implements this intrinsic itself and never runs the fallback body.
1503 #[rustc_do_not_const_check]
1504 pub const fn fma<T: bounds::FloatPrimitive>(a: T, b: T, c: T) -> T;
1505
1506 f16 => { libm::fmaf16(a, b, c) }
1507 f32 => { libm::fmaf(a, b, c) }
1508 f64 => { libm::fma(a, b, c) }
1509 f128 => { libm::fmaf128(a, b, c) }
1510}
1511
1512/// Returns `a * b + c`, non-deterministically executing either a fused multiply-add or two
1513/// operations with rounding of the intermediate result.
1514///
1515/// The operation is fused if the code generator determines that target
1516/// instruction set has support for a fused operation, and that the fused
1517/// operation is more efficient than the equivalent, separate pair of mul
1518/// and add instructions. It is unspecified whether or not a fused operation
1519/// is selected, and that may depend on optimization level and context, for
1520/// example.
1521///
1522/// The stabilized versions of this intrinsic are available on the float primitives via the
1523/// `mul_add_relaxed` method. For example,
1524/// [`f32::mul_add_relaxed`](../../std/primitive.f32.html#method.mul_add_relaxed).
1525#[inline]
1526#[rustc_intrinsic_const_stable_indirect]
1527#[rustc_intrinsic]
1528#[rustc_nounwind]
1529#[rustc_do_not_const_check]
1530pub const fn fmuladd<T: bounds::FloatPrimitive>(a: T, b: T, c: T) -> T {
1531 a * b + c
1532}
1533
1534intrinsic_dispatch_on_type! {
1535 /// Returns the largest integer less than or equal to a floating-point value.
1536 ///
1537 /// The stabilized versions of this intrinsic are available on the float primitives via the
1538 /// `floor` method. For example, [`f32::floor`](../../std/primitive.f32.html#method.floor).
1539 #[rustc_nounwind]
1540 #[inline]
1541 #[rustc_intrinsic_const_stable_indirect]
1542 #[rustc_intrinsic]
1543 // The fallback bodies call into `libm`, which is not available at compile time. This is fine
1544 // because const-eval implements this intrinsic itself and never runs the fallback body.
1545 #[rustc_do_not_const_check]
1546 pub const fn floor<T: bounds::FloatPrimitive>(x: T) -> T;
1547
1548 f16 => { libm::floorf16(x) }
1549 f32 => { libm::floorf(x) }
1550 f64 => { libm::floor(x) }
1551 f128 => { libm::floorf128(x) }
1552}
1553
1554intrinsic_dispatch_on_type! {
1555 /// Returns the smallest integer greater than or equal to a floating-point value.
1556 ///
1557 /// The stabilized versions of this intrinsic are available on the float primitives via the
1558 /// `ceil` method. For example, [`f32::ceil`](../../std/primitive.f32.html#method.ceil).
1559 #[rustc_nounwind]
1560 #[inline]
1561 #[rustc_intrinsic_const_stable_indirect]
1562 #[rustc_intrinsic]
1563 // The fallback bodies call into `libm`, which is not available at compile time. This is fine
1564 // because const-eval implements this intrinsic itself and never runs the fallback body.
1565 #[rustc_do_not_const_check]
1566 pub const fn ceil<T: bounds::FloatPrimitive>(x: T) -> T;
1567
1568 f16 => { libm::ceilf16(x) }
1569 f32 => { libm::ceilf(x) }
1570 f64 => { libm::ceil(x) }
1571 f128 => { libm::ceilf128(x) }
1572}
1573
1574intrinsic_dispatch_on_type! {
1575 /// Returns the integer part of a floating-point value.
1576 ///
1577 /// The stabilized versions of this intrinsic are available on the float primitives via the
1578 /// `trunc` method. For example, [`f32::trunc`](../../std/primitive.f32.html#method.trunc).
1579 #[rustc_nounwind]
1580 #[inline]
1581 #[rustc_intrinsic_const_stable_indirect]
1582 #[rustc_intrinsic]
1583 // The fallback bodies call into `libm`, which is not available at compile time. This is fine
1584 // because const-eval implements this intrinsic itself and never runs the fallback body.
1585 #[rustc_do_not_const_check]
1586 pub const fn trunc<T: bounds::FloatPrimitive>(x: T) -> T;
1587
1588 f16 => { libm::truncf16(x) }
1589 f32 => { libm::truncf(x) }
1590 f64 => { libm::trunc(x) }
1591 f128 => { libm::truncf128(x) }
1592}
1593
1594intrinsic_dispatch_on_type! {
1595 /// Returns the nearest integer to a floating-point value. Rounds half-way cases to the number
1596 /// with an even least significant digit.
1597 ///
1598 /// The stabilized versions of this intrinsic are available on the float primitives via the
1599 /// `round_ties_even` method. For example,
1600 /// [`f32::round_ties_even`](../../std/primitive.f32.html#method.round_ties_even).
1601 #[rustc_nounwind]
1602 #[inline]
1603 #[rustc_intrinsic_const_stable_indirect]
1604 #[rustc_intrinsic]
1605 // The fallback bodies call into `libm`, which is not available at compile time. This is fine
1606 // because const-eval implements this intrinsic itself and never runs the fallback body.
1607 #[rustc_do_not_const_check]
1608 pub const fn round_ties_even<T: bounds::FloatPrimitive>(x: T) -> T;
1609
1610 f16 => { libm::roundevenf16(x) }
1611 f32 => { libm::roundevenf(x) }
1612 f64 => { libm::roundeven(x) }
1613 f128 => { libm::roundevenf128(x) }
1614}
1615
1616intrinsic_dispatch_on_type! {
1617 /// Returns the nearest integer to a floating-point value. Rounds half-way cases away from
1618 /// zero.
1619 ///
1620 /// The stabilized versions of this intrinsic are available on the float primitives via the
1621 /// `round` method. For example, [`f32::round`](../../std/primitive.f32.html#method.round).
1622 #[rustc_nounwind]
1623 #[inline]
1624 #[rustc_intrinsic_const_stable_indirect]
1625 #[rustc_intrinsic]
1626 // The fallback bodies call into `libm`, which is not available at compile time. This is fine
1627 // because const-eval implements this intrinsic itself and never runs the fallback body.
1628 #[rustc_do_not_const_check]
1629 pub const fn round<T: bounds::FloatPrimitive>(x: T) -> T;
1630
1631 f16 => { libm::roundf16(x) }
1632 f32 => { libm::roundf(x) }
1633 f64 => { libm::round(x) }
1634 f128 => { libm::roundf128(x) }
1635}
1636
1637/// Float addition that allows optimizations based on algebraic rules.
1638/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1639///
1640/// This intrinsic does not have a stable counterpart.
1641#[rustc_intrinsic]
1642#[rustc_nounwind]
1643pub unsafe fn fadd_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1644
1645/// Float subtraction that allows optimizations based on algebraic rules.
1646/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1647///
1648/// This intrinsic does not have a stable counterpart.
1649#[rustc_intrinsic]
1650#[rustc_nounwind]
1651pub unsafe fn fsub_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1652
1653/// Float multiplication that allows optimizations based on algebraic rules.
1654/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1655///
1656/// This intrinsic does not have a stable counterpart.
1657#[rustc_intrinsic]
1658#[rustc_nounwind]
1659pub unsafe fn fmul_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1660
1661/// Float division that allows optimizations based on algebraic rules.
1662/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1663///
1664/// This intrinsic does not have a stable counterpart.
1665#[rustc_intrinsic]
1666#[rustc_nounwind]
1667pub unsafe fn fdiv_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1668
1669/// Float remainder that allows optimizations based on algebraic rules.
1670/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1671///
1672/// This intrinsic does not have a stable counterpart.
1673#[rustc_intrinsic]
1674#[rustc_nounwind]
1675pub unsafe fn frem_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1676
1677/// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range
1678/// (<https://github.com/rust-lang/rust/issues/10184>)
1679///
1680/// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`].
1681#[rustc_intrinsic]
1682#[rustc_nounwind]
1683pub unsafe fn float_to_int_unchecked<Float: bounds::FloatPrimitive, Int: Copy>(value: Float)
1684-> Int;
1685
1686/// Float addition that allows optimizations based on algebraic rules.
1687///
1688/// Stabilized as [`f16::algebraic_add`], [`f32::algebraic_add`], [`f64::algebraic_add`] and [`f128::algebraic_add`].
1689#[rustc_intrinsic_const_stable_indirect]
1690#[rustc_nounwind]
1691#[rustc_intrinsic]
1692pub const fn fadd_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1693
1694/// Float subtraction that allows optimizations based on algebraic rules.
1695///
1696/// Stabilized as [`f16::algebraic_sub`], [`f32::algebraic_sub`], [`f64::algebraic_sub`] and [`f128::algebraic_sub`].
1697#[rustc_intrinsic_const_stable_indirect]
1698#[rustc_nounwind]
1699#[rustc_intrinsic]
1700pub const fn fsub_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1701
1702/// Float multiplication that allows optimizations based on algebraic rules.
1703///
1704/// Stabilized as [`f16::algebraic_mul`], [`f32::algebraic_mul`], [`f64::algebraic_mul`] and [`f128::algebraic_mul`].
1705#[rustc_intrinsic_const_stable_indirect]
1706#[rustc_nounwind]
1707#[rustc_intrinsic]
1708pub const fn fmul_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1709
1710/// Float division that allows optimizations based on algebraic rules.
1711///
1712/// Stabilized as [`f16::algebraic_div`], [`f32::algebraic_div`], [`f64::algebraic_div`] and [`f128::algebraic_div`].
1713#[rustc_intrinsic_const_stable_indirect]
1714#[rustc_nounwind]
1715#[rustc_intrinsic]
1716pub const fn fdiv_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1717
1718/// Float remainder that allows optimizations based on algebraic rules.
1719///
1720/// Stabilized as [`f16::algebraic_rem`], [`f32::algebraic_rem`], [`f64::algebraic_rem`] and [`f128::algebraic_rem`].
1721#[rustc_intrinsic_const_stable_indirect]
1722#[rustc_nounwind]
1723#[rustc_intrinsic]
1724pub const fn frem_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1725
1726/// Integer `min`imum, signed or unsigned depending on `T`.
1727///
1728/// Allowed only on `uN`, `iN`, `usize`, and `isize`.
1729/// (Not on `bool` nor on `char`.)
1730///
1731/// Stabilized as [`u16::min`] and [`i64::min`] and similar.
1732#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1733#[rustc_nounwind]
1734#[rustc_intrinsic]
1735#[miri::intrinsic_fallback_is_spec]
1736pub const fn integer_min<T: [const] bounds::IntegerPrimitive>(a: T, b: T) -> T {
1737 if a < b { a } else { b }
1738}
1739
1740/// Integer `max`imum, signed or unsigned depending on `T`.
1741///
1742/// Allowed only on `uN`, `iN`, `usize`, and `isize`.
1743/// (Not on `bool` nor on `char`.)
1744///
1745/// Stabilized as [`u16::max`] and [`i64::max`] and similar.
1746#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1747#[rustc_nounwind]
1748#[rustc_intrinsic]
1749#[miri::intrinsic_fallback_is_spec]
1750pub const fn integer_max<T: [const] bounds::IntegerPrimitive>(a: T, b: T) -> T {
1751 if a < b { b } else { a }
1752}
1753
1754/// Returns the number of bits set in an integer type `T`
1755///
1756/// Note that, unlike most intrinsics, this is safe to call;
1757/// it does not require an `unsafe` block.
1758/// Therefore, implementations must not require the user to uphold
1759/// any safety invariants.
1760///
1761/// The stabilized versions of this intrinsic are available on the integer
1762/// primitives via the `count_ones` method. For example,
1763/// [`u32::count_ones`]
1764#[rustc_intrinsic_const_stable_indirect]
1765#[rustc_nounwind]
1766#[rustc_intrinsic]
1767pub const fn ctpop<T: Copy>(x: T) -> u32;
1768
1769/// Returns the number of leading unset bits (zeroes) in an integer type `T`.
1770///
1771/// Note that, unlike most intrinsics, this is safe to call;
1772/// it does not require an `unsafe` block.
1773/// Therefore, implementations must not require the user to uphold
1774/// any safety invariants.
1775///
1776/// The stabilized versions of this intrinsic are available on the integer
1777/// primitives via the `leading_zeros` method. For example,
1778/// [`u32::leading_zeros`]
1779///
1780/// # Examples
1781///
1782/// ```
1783/// #![feature(core_intrinsics)]
1784/// # #![allow(internal_features)]
1785///
1786/// use std::intrinsics::ctlz;
1787///
1788/// let x = 0b0001_1100_u8;
1789/// let num_leading = ctlz(x);
1790/// assert_eq!(num_leading, 3);
1791/// ```
1792///
1793/// An `x` with value `0` will return the bit width of `T`.
1794///
1795/// ```
1796/// #![feature(core_intrinsics)]
1797/// # #![allow(internal_features)]
1798///
1799/// use std::intrinsics::ctlz;
1800///
1801/// let x = 0u16;
1802/// let num_leading = ctlz(x);
1803/// assert_eq!(num_leading, 16);
1804/// ```
1805#[rustc_intrinsic_const_stable_indirect]
1806#[rustc_nounwind]
1807#[rustc_intrinsic]
1808pub const fn ctlz<T: Copy>(x: T) -> u32;
1809
1810/// Like `ctlz`, but extra-unsafe as it returns `undef` when
1811/// given an `x` with value `0`.
1812///
1813/// This intrinsic does not have a stable counterpart.
1814///
1815/// # Examples
1816///
1817/// ```
1818/// #![feature(core_intrinsics)]
1819/// # #![allow(internal_features)]
1820///
1821/// use std::intrinsics::ctlz_nonzero;
1822///
1823/// let x = 0b0001_1100_u8;
1824/// let num_leading = unsafe { ctlz_nonzero(x) };
1825/// assert_eq!(num_leading, 3);
1826/// ```
1827#[rustc_intrinsic_const_stable_indirect]
1828#[rustc_nounwind]
1829#[rustc_intrinsic]
1830pub const unsafe fn ctlz_nonzero<T: Copy>(x: T) -> u32;
1831
1832/// Returns the number of trailing unset bits (zeroes) in an integer type `T`.
1833///
1834/// Note that, unlike most intrinsics, this is safe to call;
1835/// it does not require an `unsafe` block.
1836/// Therefore, implementations must not require the user to uphold
1837/// any safety invariants.
1838///
1839/// The stabilized versions of this intrinsic are available on the integer
1840/// primitives via the `trailing_zeros` method. For example,
1841/// [`u32::trailing_zeros`]
1842///
1843/// # Examples
1844///
1845/// ```
1846/// #![feature(core_intrinsics)]
1847/// # #![allow(internal_features)]
1848///
1849/// use std::intrinsics::cttz;
1850///
1851/// let x = 0b0011_1000_u8;
1852/// let num_trailing = cttz(x);
1853/// assert_eq!(num_trailing, 3);
1854/// ```
1855///
1856/// An `x` with value `0` will return the bit width of `T`:
1857///
1858/// ```
1859/// #![feature(core_intrinsics)]
1860/// # #![allow(internal_features)]
1861///
1862/// use std::intrinsics::cttz;
1863///
1864/// let x = 0u16;
1865/// let num_trailing = cttz(x);
1866/// assert_eq!(num_trailing, 16);
1867/// ```
1868#[rustc_intrinsic_const_stable_indirect]
1869#[rustc_nounwind]
1870#[rustc_intrinsic]
1871pub const fn cttz<T: Copy>(x: T) -> u32;
1872
1873/// Like `cttz`, but extra-unsafe as it returns `undef` when
1874/// given an `x` with value `0`.
1875///
1876/// This intrinsic does not have a stable counterpart.
1877///
1878/// # Examples
1879///
1880/// ```
1881/// #![feature(core_intrinsics)]
1882/// # #![allow(internal_features)]
1883///
1884/// use std::intrinsics::cttz_nonzero;
1885///
1886/// let x = 0b0011_1000_u8;
1887/// let num_trailing = unsafe { cttz_nonzero(x) };
1888/// assert_eq!(num_trailing, 3);
1889/// ```
1890#[rustc_intrinsic_const_stable_indirect]
1891#[rustc_nounwind]
1892#[rustc_intrinsic]
1893pub const unsafe fn cttz_nonzero<T: Copy>(x: T) -> u32;
1894
1895/// Reverses the bytes in an integer type `T`.
1896///
1897/// Note that, unlike most intrinsics, this is safe to call;
1898/// it does not require an `unsafe` block.
1899/// Therefore, implementations must not require the user to uphold
1900/// any safety invariants.
1901///
1902/// The stabilized versions of this intrinsic are available on the integer
1903/// primitives via the `swap_bytes` method. For example,
1904/// [`u32::swap_bytes`]
1905#[rustc_intrinsic_const_stable_indirect]
1906#[rustc_nounwind]
1907#[rustc_intrinsic]
1908pub const fn bswap<T: Copy>(x: T) -> T;
1909
1910/// Reverses the bits in an integer type `T`.
1911///
1912/// Note that, unlike most intrinsics, this is safe to call;
1913/// it does not require an `unsafe` block.
1914/// Therefore, implementations must not require the user to uphold
1915/// any safety invariants.
1916///
1917/// The stabilized versions of this intrinsic are available on the integer
1918/// primitives via the `reverse_bits` method. For example,
1919/// [`u32::reverse_bits`]
1920#[rustc_intrinsic_const_stable_indirect]
1921#[rustc_nounwind]
1922#[rustc_intrinsic]
1923pub const fn bitreverse<T: Copy>(x: T) -> T;
1924
1925/// Does a three-way comparison between the two arguments,
1926/// which must be of character or integer (signed or unsigned) type.
1927///
1928/// This was originally added because it greatly simplified the MIR in `cmp`
1929/// implementations, and then LLVM 20 added a backend intrinsic for it too.
1930///
1931/// The stabilized version of this intrinsic is [`Ord::cmp`].
1932#[rustc_intrinsic_const_stable_indirect]
1933#[rustc_nounwind]
1934#[rustc_intrinsic]
1935pub const fn three_way_compare<T: Copy>(lhs: T, rhss: T) -> crate::cmp::Ordering;
1936
1937/// Combine two values which have no bits in common.
1938///
1939/// This allows the backend to implement it as `a + b` *or* `a | b`,
1940/// depending which is easier to implement on a specific target.
1941///
1942/// # Safety
1943///
1944/// Requires that `(a & b) == 0`, or equivalently that `(a | b) == (a + b)`.
1945///
1946/// Otherwise it's immediate UB.
1947#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1948#[rustc_nounwind]
1949#[rustc_intrinsic]
1950#[track_caller]
1951#[miri::intrinsic_fallback_is_spec] // the fallbacks all `assume` to tell Miri
1952pub const unsafe fn disjoint_bitor<T: [const] fallback::DisjointBitOr>(a: T, b: T) -> T {
1953 // SAFETY: same preconditions as this function.
1954 unsafe { fallback::DisjointBitOr::disjoint_bitor(a, b) }
1955}
1956
1957/// Performs checked integer addition.
1958///
1959/// Note that, unlike most intrinsics, this is safe to call;
1960/// it does not require an `unsafe` block.
1961/// Therefore, implementations must not require the user to uphold
1962/// any safety invariants.
1963///
1964/// The stabilized versions of this intrinsic are available on the integer
1965/// primitives via the `overflowing_add` method. For example,
1966/// [`u32::overflowing_add`]
1967#[rustc_intrinsic_const_stable_indirect]
1968#[rustc_nounwind]
1969#[rustc_intrinsic]
1970pub const fn add_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1971
1972/// Performs checked integer subtraction
1973///
1974/// Note that, unlike most intrinsics, this is safe to call;
1975/// it does not require an `unsafe` block.
1976/// Therefore, implementations must not require the user to uphold
1977/// any safety invariants.
1978///
1979/// The stabilized versions of this intrinsic are available on the integer
1980/// primitives via the `overflowing_sub` method. For example,
1981/// [`u32::overflowing_sub`]
1982#[rustc_intrinsic_const_stable_indirect]
1983#[rustc_nounwind]
1984#[rustc_intrinsic]
1985pub const fn sub_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1986
1987/// Performs checked integer multiplication
1988///
1989/// Note that, unlike most intrinsics, this is safe to call;
1990/// it does not require an `unsafe` block.
1991/// Therefore, implementations must not require the user to uphold
1992/// any safety invariants.
1993///
1994/// The stabilized versions of this intrinsic are available on the integer
1995/// primitives via the `overflowing_mul` method. For example,
1996/// [`u32::overflowing_mul`]
1997#[rustc_intrinsic_const_stable_indirect]
1998#[rustc_nounwind]
1999#[rustc_intrinsic]
2000pub const fn mul_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
2001
2002/// Performs full-width multiplication and addition with a carry:
2003/// `multiplier * multiplicand + addend + carry`.
2004///
2005/// This is possible without any overflow. For `uN`:
2006/// MAX * MAX + MAX + MAX
2007/// => (2ⁿ-1) × (2ⁿ-1) + (2ⁿ-1) + (2ⁿ-1)
2008/// => (2²ⁿ - 2ⁿ⁺¹ + 1) + (2ⁿ⁺¹ - 2)
2009/// => 2²ⁿ - 1
2010///
2011/// For `iN`, the upper bound is MIN * MIN + MAX + MAX => 2²ⁿ⁻² + 2ⁿ - 2,
2012/// and the lower bound is MAX * MIN + MIN + MIN => -2²ⁿ⁻² - 2ⁿ + 2ⁿ⁺¹.
2013///
2014/// This currently supports unsigned integers *only*, no signed ones.
2015/// The stabilized versions of this intrinsic are available on integers.
2016#[unstable(feature = "core_intrinsics", issue = "none")]
2017#[rustc_const_unstable(feature = "const_carrying_mul_add", issue = "152015")]
2018#[rustc_nounwind]
2019#[rustc_intrinsic]
2020#[miri::intrinsic_fallback_is_spec]
2021pub const fn carrying_mul_add<T: [const] fallback::CarryingMulAdd<Unsigned = U>, U>(
2022 multiplier: T,
2023 multiplicand: T,
2024 addend: T,
2025 carry: T,
2026) -> (U, T) {
2027 multiplier.carrying_mul_add(multiplicand, addend, carry)
2028}
2029
2030/// Performs an exact division, resulting in undefined behavior where
2031/// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`
2032///
2033/// This intrinsic does not have a stable counterpart.
2034#[rustc_intrinsic_const_stable_indirect]
2035#[rustc_nounwind]
2036#[rustc_intrinsic]
2037pub const unsafe fn exact_div<T: Copy>(x: T, y: T) -> T;
2038
2039/// Performs an unchecked division, resulting in undefined behavior
2040/// where `y == 0` or `x == T::MIN && y == -1`
2041///
2042/// Safe wrappers for this intrinsic are available on the integer
2043/// primitives via the `checked_div` method. For example,
2044/// [`u32::checked_div`]
2045#[rustc_intrinsic_const_stable_indirect]
2046#[rustc_nounwind]
2047#[rustc_intrinsic]
2048pub const unsafe fn unchecked_div<T: Copy>(x: T, y: T) -> T;
2049/// Returns the remainder of an unchecked division, resulting in
2050/// undefined behavior when `y == 0` or `x == T::MIN && y == -1`
2051///
2052/// Safe wrappers for this intrinsic are available on the integer
2053/// primitives via the `checked_rem` method. For example,
2054/// [`u32::checked_rem`]
2055#[rustc_intrinsic_const_stable_indirect]
2056#[rustc_nounwind]
2057#[rustc_intrinsic]
2058pub const unsafe fn unchecked_rem<T: Copy>(x: T, y: T) -> T;
2059
2060/// Performs an unchecked left shift, resulting in undefined behavior when
2061/// `y < 0` or `y >= N`, where N is the width of T in bits.
2062///
2063/// Safe wrappers for this intrinsic are available on the integer
2064/// primitives via the `checked_shl` method. For example,
2065/// [`u32::checked_shl`]
2066#[rustc_intrinsic_const_stable_indirect]
2067#[rustc_nounwind]
2068#[rustc_intrinsic]
2069pub const unsafe fn unchecked_shl<T: Copy, U: Copy>(x: T, y: U) -> T;
2070/// Performs an unchecked right shift, resulting in undefined behavior when
2071/// `y < 0` or `y >= N`, where N is the width of T in bits.
2072///
2073/// Safe wrappers for this intrinsic are available on the integer
2074/// primitives via the `checked_shr` method. For example,
2075/// [`u32::checked_shr`]
2076#[rustc_intrinsic_const_stable_indirect]
2077#[rustc_nounwind]
2078#[rustc_intrinsic]
2079pub const unsafe fn unchecked_shr<T: Copy, U: Copy>(x: T, y: U) -> T;
2080
2081/// Returns the result of an unchecked addition, resulting in
2082/// undefined behavior when `x + y > T::MAX` or `x + y < T::MIN`.
2083///
2084/// The stable counterpart of this intrinsic is `unchecked_add` on the various
2085/// integer types, such as [`u16::unchecked_add`] and [`i64::unchecked_add`].
2086#[rustc_intrinsic_const_stable_indirect]
2087#[rustc_nounwind]
2088#[rustc_intrinsic]
2089pub const unsafe fn unchecked_add<T: Copy>(x: T, y: T) -> T;
2090
2091/// Returns the result of an unchecked subtraction, resulting in
2092/// undefined behavior when `x - y > T::MAX` or `x - y < T::MIN`.
2093///
2094/// The stable counterpart of this intrinsic is `unchecked_sub` on the various
2095/// integer types, such as [`u16::unchecked_sub`] and [`i64::unchecked_sub`].
2096#[rustc_intrinsic_const_stable_indirect]
2097#[rustc_nounwind]
2098#[rustc_intrinsic]
2099pub const unsafe fn unchecked_sub<T: Copy>(x: T, y: T) -> T;
2100
2101/// Returns the result of an unchecked multiplication, resulting in
2102/// undefined behavior when `x * y > T::MAX` or `x * y < T::MIN`.
2103///
2104/// The stable counterpart of this intrinsic is `unchecked_mul` on the various
2105/// integer types, such as [`u16::unchecked_mul`] and [`i64::unchecked_mul`].
2106#[rustc_intrinsic_const_stable_indirect]
2107#[rustc_nounwind]
2108#[rustc_intrinsic]
2109pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
2110
2111/// Performs rotate left.
2112///
2113/// Note that, unlike most intrinsics, this is safe to call;
2114/// it does not require an `unsafe` block.
2115/// Therefore, implementations must not require the user to uphold
2116/// any safety invariants.
2117///
2118/// The stabilized versions of this intrinsic are available on the integer
2119/// primitives via the `rotate_left` method. For example,
2120/// [`u32::rotate_left`]
2121#[rustc_intrinsic_const_stable_indirect]
2122#[rustc_nounwind]
2123#[rustc_intrinsic]
2124#[rustc_allow_const_fn_unstable(const_trait_impl)]
2125#[miri::intrinsic_fallback_is_spec]
2126pub const fn rotate_left<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
2127 // Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2128 // SAFETY: we modulo `shift` so that the result is definitely less than the size of
2129 // `T` in bits.
2130 unsafe { unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>() as u32 * 8)) }
2131}
2132
2133/// Performs rotate right.
2134///
2135/// Note that, unlike most intrinsics, this is safe to call;
2136/// it does not require an `unsafe` block.
2137/// Therefore, implementations must not require the user to uphold
2138/// any safety invariants.
2139///
2140/// The stabilized versions of this intrinsic are available on the integer
2141/// primitives via the `rotate_right` method. For example,
2142/// [`u32::rotate_right`]
2143#[rustc_intrinsic_const_stable_indirect]
2144#[rustc_nounwind]
2145#[rustc_intrinsic]
2146#[rustc_allow_const_fn_unstable(const_trait_impl)]
2147#[miri::intrinsic_fallback_is_spec]
2148pub const fn rotate_right<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
2149 // Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2150 // SAFETY: we modulo `shift` so that the result is definitely less than the size of
2151 // `T` in bits.
2152 unsafe { unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>() as u32 * 8)) }
2153}
2154
2155/// Wrapping (modular) addition. Computes `a + b`,
2156/// wrapping around at the boundary of the type.
2157///
2158/// Note that, unlike most intrinsics, this is safe to call;
2159/// it does not require an `unsafe` block.
2160/// Therefore, implementations must not require the user to uphold
2161/// any safety invariants.
2162///
2163/// The stabilized versions of this intrinsic are available on the integer
2164/// primitives via the `wrapping_add` method. For example,
2165/// [`u32::wrapping_add`]
2166#[rustc_intrinsic_const_stable_indirect]
2167#[rustc_nounwind]
2168#[rustc_intrinsic]
2169pub const fn wrapping_add<T: Copy>(a: T, b: T) -> T;
2170/// Wrapping (modular) subtraction. Computes `a - b`,
2171/// wrapping around at the boundary of the type.
2172///
2173/// Note that, unlike most intrinsics, this is safe to call;
2174/// it does not require an `unsafe` block.
2175/// Therefore, implementations must not require the user to uphold
2176/// any safety invariants.
2177///
2178/// The stabilized versions of this intrinsic are available on the integer
2179/// primitives via the `wrapping_sub` method. For example,
2180/// [`u32::wrapping_sub`]
2181#[rustc_intrinsic_const_stable_indirect]
2182#[rustc_nounwind]
2183#[rustc_intrinsic]
2184pub const fn wrapping_sub<T: Copy>(a: T, b: T) -> T;
2185/// Wrapping (modular) multiplication. Computes `a *
2186/// b`, wrapping around at the boundary of the type.
2187///
2188/// Note that, unlike most intrinsics, this is safe to call;
2189/// it does not require an `unsafe` block.
2190/// Therefore, implementations must not require the user to uphold
2191/// any safety invariants.
2192///
2193/// The stabilized versions of this intrinsic are available on the integer
2194/// primitives via the `wrapping_mul` method. For example,
2195/// [`u32::wrapping_mul`]
2196#[rustc_intrinsic_const_stable_indirect]
2197#[rustc_nounwind]
2198#[rustc_intrinsic]
2199pub const fn wrapping_mul<T: Copy>(a: T, b: T) -> T;
2200
2201/// Computes `a + b`, saturating at numeric bounds.
2202///
2203/// Note that, unlike most intrinsics, this is safe to call;
2204/// it does not require an `unsafe` block.
2205/// Therefore, implementations must not require the user to uphold
2206/// any safety invariants.
2207///
2208/// The stabilized versions of this intrinsic are available on the integer
2209/// primitives via the `saturating_add` method. For example,
2210/// [`u32::saturating_add`]
2211#[rustc_intrinsic_const_stable_indirect]
2212#[rustc_nounwind]
2213#[rustc_intrinsic]
2214pub const fn saturating_add<T: Copy>(a: T, b: T) -> T;
2215/// Computes `a - b`, saturating at numeric bounds.
2216///
2217/// Note that, unlike most intrinsics, this is safe to call;
2218/// it does not require an `unsafe` block.
2219/// Therefore, implementations must not require the user to uphold
2220/// any safety invariants.
2221///
2222/// The stabilized versions of this intrinsic are available on the integer
2223/// primitives via the `saturating_sub` method. For example,
2224/// [`u32::saturating_sub`]
2225#[rustc_intrinsic_const_stable_indirect]
2226#[rustc_nounwind]
2227#[rustc_intrinsic]
2228pub const fn saturating_sub<T: Copy>(a: T, b: T) -> T;
2229
2230/// Funnel Shift left.
2231///
2232/// Concatenates `a` and `b` (with `a` in the most significant half),
2233/// creating an integer twice as wide. Then shift this integer left
2234/// by `shift`), and extract the most significant half. If `a` and `b`
2235/// are the same, this is equivalent to a rotate left operation.
2236///
2237/// It is undefined behavior if `shift` is greater than or equal to the
2238/// bit size of `T`.
2239///
2240/// Safe versions of this intrinsic are available on the integer primitives
2241/// via the `funnel_shl` method. For example, [`u32::funnel_shl`].
2242#[rustc_intrinsic_const_stable_indirect]
2243#[rustc_intrinsic]
2244#[rustc_nounwind]
2245#[track_caller]
2246#[rustc_allow_const_fn_unstable(const_trait_impl, core_intrinsics_fallbacks)]
2247#[miri::intrinsic_fallback_is_spec]
2248pub const unsafe fn unchecked_funnel_shl<T: [const] fallback::FunnelShift>(
2249 a: T,
2250 b: T,
2251 shift: u32,
2252) -> T {
2253 // SAFETY: caller ensures that `shift` is in-range
2254 unsafe { a.unchecked_funnel_shl(b, shift) }
2255}
2256
2257/// Funnel Shift right.
2258///
2259/// Concatenates `a` and `b` (with `a` in the most significant half),
2260/// creating an integer twice as wide. Then shift this integer right
2261/// by `shift` (taken modulo the bit size of `T`), and extract the
2262/// least significant half. If `a` and `b` are the same, this is equivalent
2263/// to a rotate right operation.
2264///
2265/// It is undefined behavior if `shift` is greater than or equal to the
2266/// bit size of `T`.
2267///
2268/// Safer versions of this intrinsic are available on the integer primitives
2269/// via the `funnel_shr` method. For example, [`u32::funnel_shr`]
2270#[rustc_intrinsic_const_stable_indirect]
2271#[rustc_intrinsic]
2272#[rustc_nounwind]
2273#[track_caller]
2274#[rustc_allow_const_fn_unstable(const_trait_impl, core_intrinsics_fallbacks)]
2275#[miri::intrinsic_fallback_is_spec]
2276pub const unsafe fn unchecked_funnel_shr<T: [const] fallback::FunnelShift>(
2277 a: T,
2278 b: T,
2279 shift: u32,
2280) -> T {
2281 // SAFETY: caller ensures that `shift` is in-range
2282 unsafe { a.unchecked_funnel_shr(b, shift) }
2283}
2284
2285/// Carryless multiply.
2286///
2287/// Safe versions of this intrinsic are available on the integer primitives
2288/// via the `carryless_mul` method. For example, [`u32::carryless_mul`].
2289#[rustc_intrinsic]
2290#[rustc_nounwind]
2291#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
2292#[unstable(feature = "uint_carryless_mul", issue = "152080")]
2293#[miri::intrinsic_fallback_is_spec]
2294pub const fn carryless_mul<T: [const] fallback::CarrylessMul>(a: T, b: T) -> T {
2295 a.carryless_mul(b)
2296}
2297
2298/// This is an implementation detail of [`crate::ptr::read`] and should
2299/// not be used anywhere else. See its comments for why this exists.
2300///
2301/// This intrinsic can *only* be called where the pointer is a local without
2302/// projections (`read_via_copy(ptr)`, not `read_via_copy(*ptr)`) so that it
2303/// trivially obeys runtime-MIR rules about derefs in operands.
2304#[rustc_intrinsic_const_stable_indirect]
2305#[rustc_nounwind]
2306#[rustc_intrinsic]
2307pub const unsafe fn read_via_copy<T>(ptr: *const T) -> T;
2308
2309/// This is an implementation detail of [`crate::ptr::write`] and should
2310/// not be used anywhere else. See its comments for why this exists.
2311///
2312/// This intrinsic can *only* be called where the pointer is a local without
2313/// projections (`write_via_move(ptr, x)`, not `write_via_move(*ptr, x)`) so
2314/// that it trivially obeys runtime-MIR rules about derefs in operands.
2315#[rustc_intrinsic_const_stable_indirect]
2316#[rustc_nounwind]
2317#[rustc_intrinsic]
2318pub const unsafe fn write_via_move<T>(ptr: *mut T, value: T);
2319
2320/// Returns the value of the discriminant for the variant in 'v';
2321/// if `T` has no discriminant, returns `0`.
2322///
2323/// Note that, unlike most intrinsics, this is safe to call;
2324/// it does not require an `unsafe` block.
2325/// Therefore, implementations must not require the user to uphold
2326/// any safety invariants.
2327///
2328/// The stabilized version of this intrinsic is [`core::mem::discriminant`].
2329#[rustc_intrinsic_const_stable_indirect]
2330#[rustc_nounwind]
2331#[rustc_intrinsic]
2332pub const fn discriminant_value<T>(v: &T) -> <T as DiscriminantKind>::Discriminant;
2333
2334/// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the
2335/// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs.
2336/// Returns `true` if unwinding occurred and `catch_fn` was called; returns `false` otherwise.
2337///
2338/// `catch_fn` must not unwind.
2339///
2340/// The third argument is a function called if an unwind occurs (both Rust `panic` and foreign
2341/// unwinds). This function takes the data pointer and a pointer to the target- and
2342/// runtime-specific exception object that was caught.
2343///
2344/// Note that in the case of a foreign unwinding operation, the exception object data may not be
2345/// safely usable from Rust, and should not be directly exposed via the standard library. To
2346/// prevent unsafe access, the library implementation may either abort the process or present an
2347/// opaque error type to the user.
2348///
2349/// For more information, see the compiler's source, as well as the documentation for the stable
2350/// version of this intrinsic, `std::panic::catch_unwind`.
2351#[rustc_intrinsic]
2352#[rustc_nounwind]
2353pub unsafe fn catch_unwind<Data: ptr::Thin>(
2354 _try_fn: unsafe fn(*mut Data),
2355 _data: *mut Data,
2356 _catch_fn: unsafe fn(*mut Data, *mut u8),
2357) -> bool;
2358
2359/// Emits a `nontemporal` store, which gives a hint to the CPU that the data should not be held
2360/// in cache. Except for performance, this is fully equivalent to `ptr.write(val)`.
2361///
2362/// Not all architectures provide such an operation. For instance, x86 does not: while `MOVNT`
2363/// exists, that operation is *not* equivalent to `ptr.write(val)` (`MOVNT` writes can be reordered
2364/// in ways that are not allowed for regular writes).
2365#[rustc_intrinsic]
2366#[rustc_nounwind]
2367pub unsafe fn nontemporal_store<T>(ptr: *mut T, val: T);
2368
2369/// See documentation of `<*const T>::offset_from` for details.
2370#[rustc_intrinsic_const_stable_indirect]
2371#[rustc_nounwind]
2372#[rustc_intrinsic]
2373pub const unsafe fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
2374
2375/// See documentation of `<*const T>::offset_from_unsigned` for details.
2376#[rustc_nounwind]
2377#[rustc_intrinsic]
2378#[rustc_intrinsic_const_stable_indirect]
2379pub const unsafe fn ptr_offset_from_unsigned<T>(ptr: *const T, base: *const T) -> usize;
2380
2381/// See documentation of `<*const T>::guaranteed_eq` for details.
2382/// Returns `2` if the result is unknown.
2383/// Returns `1` if the pointers are guaranteed equal.
2384/// Returns `0` if the pointers are guaranteed inequal.
2385#[rustc_intrinsic]
2386#[rustc_nounwind]
2387#[rustc_do_not_const_check]
2388#[inline]
2389#[miri::intrinsic_fallback_is_spec]
2390pub const fn ptr_guaranteed_cmp<T>(ptr: *const T, other: *const T) -> u8 {
2391 (ptr == other) as u8
2392}
2393
2394/// Determines whether the raw bytes of the two values are equal.
2395///
2396/// This is particularly handy for arrays, since it allows things like just
2397/// comparing `i96`s instead of forcing `alloca`s for `[6 x i16]`.
2398///
2399/// Above some backend-decided threshold this will emit calls to `memcmp`,
2400/// like slice equality does, instead of causing massive code size.
2401///
2402/// Since this works by comparing the underlying bytes, the actual `T` is
2403/// not particularly important. It will be used for its size and alignment,
2404/// but any validity restrictions will be ignored, not enforced.
2405///
2406/// # Safety
2407///
2408/// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized.
2409/// Note that this is a stricter criterion than just the *values* being
2410/// fully-initialized: if `T` has padding, it's UB to call this intrinsic.
2411///
2412/// At compile-time, it is furthermore UB to call this if any of the bytes
2413/// in `*a` or `*b` have provenance.
2414///
2415/// (The implementation is allowed to branch on the results of comparisons,
2416/// which is UB if any of their inputs are `undef`.)
2417#[rustc_nounwind]
2418#[rustc_intrinsic]
2419pub const unsafe fn raw_eq<T>(a: &T, b: &T) -> bool;
2420
2421/// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)`
2422/// as unsigned bytes, returning negative if `left` is less, zero if all the
2423/// bytes match, or positive if `left` is greater.
2424///
2425/// This underlies things like `<[u8]>::cmp`, and will usually lower to `memcmp`.
2426///
2427/// # Safety
2428///
2429/// `left` and `right` must each be [valid] for reads of `bytes` bytes.
2430///
2431/// Note that this applies to the whole range, not just until the first byte
2432/// that differs. That allows optimizations that can read in large chunks.
2433///
2434/// [valid]: crate::ptr#safety
2435#[rustc_nounwind]
2436#[rustc_intrinsic]
2437#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2438pub const unsafe fn compare_bytes(left: *const u8, right: *const u8, bytes: usize) -> i32;
2439
2440/// See documentation of [`std::hint::black_box`] for details.
2441///
2442/// [`std::hint::black_box`]: crate::hint::black_box
2443#[rustc_nounwind]
2444#[rustc_intrinsic]
2445#[rustc_intrinsic_const_stable_indirect]
2446pub const fn black_box<T>(dummy: T) -> T;
2447
2448/// Selects which function to call depending on the context.
2449///
2450/// If this function is evaluated at compile-time, then a call to this
2451/// intrinsic will be replaced with a call to `called_in_const`. It gets
2452/// replaced with a call to `called_at_rt` otherwise.
2453///
2454/// This function is safe to call, but note the stability concerns below.
2455///
2456/// # Type Requirements
2457///
2458/// The two functions must be both function items. They cannot be function
2459/// pointers or closures. The first function must be a `const fn`.
2460///
2461/// `arg` will be the tupled arguments that will be passed to either one of
2462/// the two functions, therefore, both functions must accept the same type of
2463/// arguments. Both functions must return RET.
2464///
2465/// # Stability concerns
2466///
2467/// Rust has not yet decided that `const fn` are allowed to tell whether
2468/// they run at compile-time or at runtime. Therefore, when using this
2469/// intrinsic anywhere that can be reached from stable, it is crucial that
2470/// the end-to-end behavior of the stable `const fn` is the same for both
2471/// modes of execution. (Here, Undefined Behavior is considered "the same"
2472/// as any other behavior, so if the function exhibits UB at runtime then
2473/// it may do whatever it wants at compile-time.)
2474///
2475/// Here is an example of how this could cause a problem:
2476/// ```no_run
2477/// #![feature(const_eval_select)]
2478/// #![feature(core_intrinsics)]
2479/// # #![allow(internal_features)]
2480/// use std::intrinsics::const_eval_select;
2481///
2482/// // Standard library
2483/// pub const fn inconsistent() -> i32 {
2484/// fn runtime() -> i32 { 1 }
2485/// const fn compiletime() -> i32 { 2 }
2486///
2487/// // ⚠ This code violates the required equivalence of `compiletime`
2488/// // and `runtime`.
2489/// const_eval_select((), compiletime, runtime)
2490/// }
2491///
2492/// // User Crate
2493/// const X: i32 = inconsistent();
2494/// let x = inconsistent();
2495/// assert_eq!(x, X);
2496/// ```
2497///
2498/// Currently such an assertion would always succeed; until Rust decides
2499/// otherwise, that principle should not be violated.
2500#[rustc_const_unstable(feature = "const_eval_select", issue = "124625")]
2501#[rustc_intrinsic]
2502pub const fn const_eval_select<ARG: Tuple, F, G, RET>(
2503 _arg: ARG,
2504 _called_in_const: F,
2505 _called_at_rt: G,
2506) -> RET
2507where
2508 G: FnOnce<ARG, Output = RET>,
2509 F: const FnOnce<ARG, Output = RET>;
2510
2511/// A macro to make it easier to invoke const_eval_select. Use as follows:
2512/// ```rust,ignore (just a macro example)
2513/// const_eval_select!(
2514/// @capture { arg1: i32 = some_expr, arg2: T = other_expr } -> U:
2515/// if const #[attributes_for_const_arm] {
2516/// // Compile-time code goes here.
2517/// } else #[attributes_for_runtime_arm] {
2518/// // Run-time code goes here.
2519/// }
2520/// )
2521/// ```
2522/// The `@capture` block declares which surrounding variables / expressions can be
2523/// used inside the `if const`.
2524/// Note that the two arms of this `if` really each become their own function, which is why the
2525/// macro supports setting attributes for those functions. Both functions are marked as `#[inline]`.
2526///
2527/// See [`const_eval_select()`] for the rules and requirements around that intrinsic.
2528pub(crate) macro const_eval_select {
2529 (
2530 @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? :
2531 if const
2532 $(#[$compiletime_attr:meta])* $compiletime:block
2533 else
2534 $(#[$runtime_attr:meta])* $runtime:block
2535 ) => {{
2536 #[inline]
2537 $(#[$runtime_attr])*
2538 fn runtime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2539 $runtime
2540 }
2541
2542 #[inline]
2543 $(#[$compiletime_attr])*
2544 const fn compiletime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2545 // Don't warn if one of the arguments is unused.
2546 $(let _ = $arg;)*
2547
2548 $compiletime
2549 }
2550
2551 const_eval_select(($($val,)*), compiletime, runtime)
2552 }},
2553 // We support leaving away the `val` expressions for *all* arguments
2554 // (but not for *some* arguments, that's too tricky).
2555 (
2556 @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty),* $(,)? } $( -> $ret:ty )? :
2557 if const
2558 $(#[$compiletime_attr:meta])* $compiletime:block
2559 else
2560 $(#[$runtime_attr:meta])* $runtime:block
2561 ) => {
2562 $crate::intrinsics::const_eval_select!(
2563 @capture$([$($binders)*])? { $($arg : $ty = $arg),* } $(-> $ret)? :
2564 if const
2565 $(#[$compiletime_attr])* $compiletime
2566 else
2567 $(#[$runtime_attr])* $runtime
2568 )
2569 },
2570}
2571
2572/// Returns whether the argument's value is statically known at
2573/// compile-time.
2574///
2575/// This is useful when there is a way of writing the code that will
2576/// be *faster* when some variables have known values, but *slower*
2577/// in the general case: an `if is_val_statically_known(var)` can be used
2578/// to select between these two variants. The `if` will be optimized away
2579/// and only the desired branch remains.
2580///
2581/// Formally speaking, this function non-deterministically returns `true`
2582/// or `false`, and the caller has to ensure sound behavior for both cases.
2583/// In other words, the following code has *Undefined Behavior*:
2584///
2585/// ```no_run
2586/// #![feature(core_intrinsics)]
2587/// # #![allow(internal_features)]
2588/// use std::hint::unreachable_unchecked;
2589/// use std::intrinsics::is_val_statically_known;
2590///
2591/// if !is_val_statically_known(0) { unsafe { unreachable_unchecked(); } }
2592/// ```
2593///
2594/// This also means that the following code's behavior is unspecified; it
2595/// may panic, or it may not:
2596///
2597/// ```no_run
2598/// #![feature(core_intrinsics)]
2599/// # #![allow(internal_features)]
2600/// use std::intrinsics::is_val_statically_known;
2601///
2602/// assert_eq!(is_val_statically_known(0), is_val_statically_known(0));
2603/// ```
2604///
2605/// Unsafe code may not rely on `is_val_statically_known` returning any
2606/// particular value, ever. However, the compiler will generally make it
2607/// return `true` only if the value of the argument is actually known.
2608///
2609/// # Type Requirements
2610///
2611/// `T` must be either a `bool`, a `char`, a primitive numeric type (e.g. `f32`,
2612/// but not `NonZeroISize`), or any thin pointer (e.g. `*mut String`).
2613/// Any other argument types *may* cause a compiler error.
2614///
2615/// ## Pointers
2616///
2617/// When the input is a pointer, only the pointer itself is
2618/// ever considered. The pointee has no effect. Currently, these functions
2619/// behave identically:
2620///
2621/// ```
2622/// #![feature(core_intrinsics)]
2623/// # #![allow(internal_features)]
2624/// use std::intrinsics::is_val_statically_known;
2625///
2626/// fn foo(x: &i32) -> bool {
2627/// is_val_statically_known(x)
2628/// }
2629///
2630/// fn bar(x: &i32) -> bool {
2631/// is_val_statically_known(
2632/// (x as *const i32).addr()
2633/// )
2634/// }
2635/// # _ = foo(&5_i32);
2636/// # _ = bar(&5_i32);
2637/// ```
2638#[rustc_const_stable_indirect]
2639#[rustc_nounwind]
2640#[unstable(feature = "core_intrinsics", issue = "none")]
2641#[rustc_intrinsic]
2642pub const fn is_val_statically_known<T: Copy>(_arg: T) -> bool {
2643 false
2644}
2645
2646/// Non-overlapping *typed* swap of a single value.
2647///
2648/// The codegen backends will replace this with a better implementation when
2649/// `T` is a simple type that can be loaded and stored as an immediate.
2650///
2651/// The stabilized form of this intrinsic is [`crate::mem::swap`].
2652///
2653/// # Safety
2654/// Behavior is undefined if any of the following conditions are violated:
2655///
2656/// * Both `x` and `y` must be [valid] for both reads and writes.
2657///
2658/// * Both `x` and `y` must be properly aligned.
2659///
2660/// * The region of memory beginning at `x` must *not* overlap with the region of memory
2661/// beginning at `y`.
2662///
2663/// * The memory pointed by `x` and `y` must both contain values of type `T`.
2664///
2665/// [valid]: crate::ptr#safety
2666#[rustc_nounwind]
2667#[inline]
2668#[rustc_intrinsic]
2669#[rustc_intrinsic_const_stable_indirect]
2670pub const unsafe fn typed_swap_nonoverlapping<T>(x: *mut T, y: *mut T) {
2671 // SAFETY: The caller provided single non-overlapping items behind
2672 // pointers, so swapping them with `count: 1` is fine.
2673 unsafe { ptr::swap_nonoverlapping(x, y, 1) };
2674}
2675
2676/// Returns whether we should perform some UB-checking at runtime. This eventually evaluates to
2677/// `cfg!(ub_checks)`, but behaves different from `cfg!` when mixing crates built with different
2678/// flags: if the crate has UB checks enabled or carries the `#[rustc_preserve_ub_checks]`
2679/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2680/// a crate that does not delay evaluation further); otherwise it can happen any time.
2681///
2682/// The common case here is a user program built with ub_checks linked against the distributed
2683/// sysroot which is built without ub_checks but with `#[rustc_preserve_ub_checks]`.
2684/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2685/// `#[inline]`), gating assertions on `ub_checks()` rather than `cfg!(ub_checks)` means that
2686/// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the
2687/// user has UB checks disabled, the checks will still get optimized out. This intrinsic is
2688/// primarily used by [`crate::ub_checks::assert_unsafe_precondition`].
2689///
2690/// # Consteval
2691///
2692/// In consteval, this function currently returns `true`. This is because the value of the `ub_checks`
2693/// configuration can differ across crates, but we need this function to always return the same
2694/// value in consteval in order to avoid unsoundness.
2695#[rustc_intrinsic_const_stable_indirect] // just for UB checks
2696#[inline(always)]
2697#[rustc_intrinsic]
2698pub const fn ub_checks() -> bool {
2699 cfg!(ub_checks)
2700}
2701
2702/// Returns whether we should perform some overflow-checking at runtime. This eventually evaluates to
2703/// `cfg!(overflow_checks)`, but behaves different from `cfg!` when mixing crates built with different
2704/// flags: if the crate has overflow checks enabled or carries the `#[rustc_inherit_overflow_checks]`
2705/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2706/// a crate that does not delay evaluation further); otherwise it can happen any time.
2707///
2708/// The common case here is a user program built with overflow_checks linked against the distributed
2709/// sysroot which is built without overflow_checks but with `#[rustc_inherit_overflow_checks]`.
2710/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2711/// `#[inline]`), gating assertions on `overflow_checks()` rather than `cfg!(overflow_checks)` means that
2712/// assertions are enabled whenever the *user crate* has overflow checks enabled. However if the
2713/// user has overflow checks disabled, the checks will still get optimized out.
2714///
2715/// # Consteval
2716///
2717/// In consteval, this function currently returns `true`. This is because the value of the `overflow_checks`
2718/// configuration can differ across crates, but we need this function to always return the same
2719/// value in consteval in order to avoid unsoundness.
2720#[inline(always)]
2721#[rustc_intrinsic]
2722pub const fn overflow_checks() -> bool {
2723 cfg!(debug_assertions)
2724}
2725
2726/// Allocates a block of memory at compile time.
2727/// At runtime, just returns a null pointer.
2728///
2729/// # Safety
2730///
2731/// - The `align` argument must be a power of two.
2732/// - At compile time, a compile error occurs if this constraint is violated.
2733/// - At runtime, it is not checked.
2734#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2735#[rustc_nounwind]
2736#[rustc_intrinsic]
2737#[miri::intrinsic_fallback_is_spec]
2738pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 {
2739 // const eval overrides this function, but runtime code for now just returns null pointers.
2740 // See <https://github.com/rust-lang/rust/issues/93935>.
2741 crate::ptr::null_mut()
2742}
2743
2744/// Deallocates a memory which allocated by `intrinsics::const_allocate` at compile time.
2745/// At runtime, it does nothing.
2746///
2747/// # Safety
2748///
2749/// - The `align` argument must be a power of two.
2750/// - At compile time, a compile error occurs if this constraint is violated.
2751/// - At runtime, it is not checked.
2752/// - If the `ptr` is created in an another const, this intrinsic doesn't deallocate it.
2753/// - If the `ptr` is pointing to a local variable, this intrinsic doesn't deallocate it.
2754#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2755#[unstable(feature = "core_intrinsics", issue = "none")]
2756#[rustc_nounwind]
2757#[rustc_intrinsic]
2758#[miri::intrinsic_fallback_is_spec]
2759pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {
2760 // Runtime NOP
2761}
2762
2763/// Convert the allocation this pointer points to into immutable global memory.
2764/// The pointer must point to the beginning of a heap allocation.
2765/// This operation only makes sense during compile time. At runtime, it does nothing.
2766#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2767#[rustc_nounwind]
2768#[rustc_intrinsic]
2769#[miri::intrinsic_fallback_is_spec]
2770pub const unsafe fn const_make_global(ptr: *mut u8) -> *const u8 {
2771 // const eval overrides this function; at runtime, it is a NOP.
2772 ptr
2773}
2774
2775/// Check if the pre-condition `cond` has been met.
2776///
2777/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2778/// returns false.
2779///
2780/// Note that this function is a no-op during constant evaluation.
2781#[unstable(feature = "contracts_internals", issue = "128044")]
2782// Calls to this function get inserted by an AST expansion pass, which uses the equivalent of
2783// `#[allow_internal_unstable]` to allow using `contracts_internals` functions. Const-checking
2784// doesn't honor `#[allow_internal_unstable]`, so for the const feature gate we use the user-facing
2785// `contracts` feature rather than the perma-unstable `contracts_internals`
2786#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2787#[lang = "contract_check_requires"]
2788#[rustc_intrinsic]
2789pub const fn contract_check_requires<C: Fn() -> bool + Copy>(cond: C) {
2790 const_eval_select!(
2791 @capture[C: Fn() -> bool + Copy] { cond: C } :
2792 if const {
2793 // Do nothing
2794 } else {
2795 if !cond() {
2796 // Emit no unwind panic in case this was a safety requirement.
2797 crate::panicking::panic_nounwind("failed requires check");
2798 }
2799 }
2800 )
2801}
2802
2803/// Check if the post-condition `cond` has been met.
2804///
2805/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2806/// returns false.
2807///
2808/// If `cond` is `None`, then no postcondition checking is performed.
2809///
2810/// Note that this function is a no-op during constant evaluation.
2811#[unstable(feature = "contracts_internals", issue = "128044")]
2812// Similar to `contract_check_requires`, we need to use the user-facing
2813// `contracts` feature rather than the perma-unstable `contracts_internals`.
2814// Const-checking doesn't honor allow_internal_unstable logic used by contract expansion.
2815#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2816#[lang = "contract_check_ensures"]
2817#[rustc_intrinsic]
2818pub const fn contract_check_ensures<C: Fn(&Ret) -> bool + Copy, Ret>(
2819 cond: Option<C>,
2820 ret: Ret,
2821) -> Ret {
2822 const_eval_select!(
2823 @capture[C: Fn(&Ret) -> bool + Copy, Ret] { cond: Option<C>, ret: Ret } -> Ret :
2824 if const {
2825 // Do nothing
2826 ret
2827 } else {
2828 if let crate::option::Option::Some(cond) = cond && !cond(&ret) {
2829 // Emit no unwind panic in case this was a safety requirement.
2830 crate::panicking::panic_nounwind("failed ensures check");
2831 }
2832 ret
2833 }
2834 )
2835}
2836
2837/// The intrinsic will return the size stored in that vtable.
2838///
2839/// # Safety
2840///
2841/// `ptr` must point to a vtable.
2842#[rustc_nounwind]
2843#[unstable(feature = "core_intrinsics", issue = "none")]
2844#[rustc_intrinsic]
2845pub unsafe fn vtable_size(ptr: *const ()) -> usize;
2846
2847/// The intrinsic will return the alignment stored in that vtable.
2848///
2849/// # Safety
2850///
2851/// `ptr` must point to a vtable.
2852#[rustc_nounwind]
2853#[unstable(feature = "core_intrinsics", issue = "none")]
2854#[rustc_intrinsic]
2855pub unsafe fn vtable_align(ptr: *const ()) -> usize;
2856
2857/// The size of a type in bytes.
2858///
2859/// Note that, unlike most intrinsics, this is safe to call;
2860/// it does not require an `unsafe` block.
2861/// Therefore, implementations must not require the user to uphold
2862/// any safety invariants.
2863///
2864/// More specifically, this is the offset in bytes between successive
2865/// items of the same type, including alignment padding.
2866///
2867/// Note that, unlike most intrinsics, this can only be called at compile-time
2868/// as backends do not have an implementation for it. The only caller (its
2869/// stable counterpart) wraps this intrinsic call in a `const` block so that
2870/// backends only see an evaluated constant.
2871///
2872/// The stabilized version of this intrinsic is [`core::mem::size_of`].
2873#[rustc_nounwind]
2874#[unstable(feature = "core_intrinsics", issue = "none")]
2875#[rustc_intrinsic_const_stable_indirect]
2876#[rustc_intrinsic]
2877#[rustc_comptime]
2878pub fn size_of<T>() -> usize;
2879
2880/// The minimum alignment of a type.
2881///
2882/// Note that, unlike most intrinsics, this is safe to call;
2883/// it does not require an `unsafe` block.
2884/// Therefore, implementations must not require the user to uphold
2885/// any safety invariants.
2886///
2887/// Note that, unlike most intrinsics, this can only be called at compile-time
2888/// as backends do not have an implementation for it. The only caller (its
2889/// stable counterpart) wraps this intrinsic call in a `const` block so that
2890/// backends only see an evaluated constant.
2891///
2892/// The stabilized version of this intrinsic is [`core::mem::align_of`].
2893#[rustc_nounwind]
2894#[unstable(feature = "core_intrinsics", issue = "none")]
2895#[rustc_intrinsic_const_stable_indirect]
2896#[rustc_intrinsic]
2897#[rustc_comptime]
2898pub fn align_of<T>() -> usize;
2899
2900/// The offset of a field inside a type.
2901///
2902/// Note that, unlike most intrinsics, this is safe to call;
2903/// it does not require an `unsafe` block.
2904/// Therefore, implementations must not require the user to uphold
2905/// any safety invariants.
2906///
2907/// This intrinsic can only be evaluated at compile-time, and should only appear in
2908/// constants or inline const blocks.
2909///
2910/// The stabilized version of this intrinsic is [`core::mem::offset_of`].
2911/// This intrinsic is also a lang item so `offset_of!` can desugar to calls to it.
2912#[rustc_nounwind]
2913#[unstable(feature = "core_intrinsics", issue = "none")]
2914#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")]
2915#[rustc_intrinsic_const_stable_indirect]
2916#[rustc_intrinsic]
2917#[lang = "offset_of"]
2918#[rustc_comptime]
2919pub fn offset_of<T: PointeeSized>(variant: u32, field: u32) -> usize;
2920
2921/// The offset of a field queried by its field representing type.
2922///
2923/// Returns the offset of the field represented by `F`. This function essentially does the same as
2924/// the [`offset_of`] intrinsic, but expects the field to be represented by a generic rather than
2925/// the variant and field indices. This also is a safe intrinsic and can only be evaluated at
2926/// compile-time, so it should only appear in constants or inline const blocks.
2927///
2928/// There should be no need to call this intrinsic manually, as its value is used to define
2929/// [`Field::OFFSET`](crate::field::Field::OFFSET), which is publicly accessible.
2930#[rustc_intrinsic]
2931#[unstable(feature = "field_projections", issue = "145383")]
2932#[rustc_const_unstable(feature = "field_projections", issue = "145383")]
2933#[rustc_comptime]
2934pub fn field_offset<F: crate::field::Field>() -> usize;
2935
2936/// Returns the number of variants of the type `T` cast to a `usize`;
2937/// if `T` has no variants, returns `0`. Uninhabited variants will be counted.
2938///
2939/// Note that, unlike most intrinsics, this can only be called at compile-time
2940/// as backends do not have an implementation for it. The only caller (its
2941/// stable counterpart) wraps this intrinsic call in a `const` block so that
2942/// backends only see an evaluated constant.
2943///
2944/// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`].
2945#[rustc_nounwind]
2946#[unstable(feature = "core_intrinsics", issue = "none")]
2947#[rustc_intrinsic]
2948#[rustc_comptime]
2949pub fn variant_count<T>() -> usize;
2950
2951/// The size of the referenced value in bytes.
2952///
2953/// The stabilized version of this intrinsic is [`core::mem::size_of_val`].
2954///
2955/// # Safety
2956///
2957/// See [`crate::mem::size_of_val_raw`] for safety conditions.
2958#[rustc_nounwind]
2959#[unstable(feature = "core_intrinsics", issue = "none")]
2960#[rustc_intrinsic]
2961#[rustc_intrinsic_const_stable_indirect]
2962pub const unsafe fn size_of_val<T: ?Sized>(ptr: *const T) -> usize;
2963
2964/// The required alignment of the referenced value.
2965///
2966/// The stabilized version of this intrinsic is [`core::mem::align_of_val`].
2967///
2968/// # Safety
2969///
2970/// See [`crate::mem::align_of_val_raw`] for safety conditions.
2971#[rustc_nounwind]
2972#[unstable(feature = "core_intrinsics", issue = "none")]
2973#[rustc_intrinsic]
2974#[rustc_intrinsic_const_stable_indirect]
2975pub const unsafe fn align_of_val<T: ?Sized>(ptr: *const T) -> usize;
2976
2977/// Gets a static string slice containing the name of a type.
2978///
2979/// Note that, unlike most intrinsics, this can only be called at compile-time
2980/// as backends do not have an implementation for it. The only caller (its
2981/// stable counterpart) wraps this intrinsic call in a `const` block so that
2982/// backends only see an evaluated constant.
2983///
2984/// The stabilized version of this intrinsic is [`core::any::type_name`].
2985#[rustc_nounwind]
2986#[unstable(feature = "core_intrinsics", issue = "none")]
2987#[rustc_intrinsic]
2988#[rustc_comptime]
2989pub fn type_name<T: ?Sized>() -> &'static str;
2990
2991/// Gets the actual field `TypeId` of the [`FieldRepresentingType`]'s `TypeId`.
2992///
2993/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::type_id`].
2994///
2995/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType
2996#[rustc_intrinsic]
2997#[unstable(feature = "core_intrinsics", issue = "none")]
2998#[rustc_comptime]
2999pub fn field_representing_type_actual_type_id(
3000 _frt_type_id: crate::any::TypeId,
3001) -> crate::any::TypeId;
3002
3003/// Gets the name of the field represented by the [`FieldRepresentingType`]'s `TypeId`.
3004///
3005/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::name`].
3006///
3007/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType
3008#[rustc_intrinsic]
3009#[unstable(feature = "core_intrinsics", issue = "none")]
3010#[rustc_comptime]
3011pub fn field_representing_type_name(_frt_type_id: crate::any::TypeId) -> &'static str;
3012
3013/// Gets the name of the field represented by the [`FieldRepresentingType`]'s `TypeId`.
3014///
3015/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::name`].
3016///
3017/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType
3018#[rustc_intrinsic]
3019#[unstable(feature = "core_intrinsics", issue = "none")]
3020#[rustc_comptime]
3021pub fn field_representing_type_offset(_frt_type_id: crate::any::TypeId) -> usize;
3022
3023/// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`.
3024///
3025/// This is used to implement functions like `slice::from_raw_parts_mut` and
3026/// `ptr::from_raw_parts` in a way compatible with the compiler being able to
3027/// change the possible layouts of pointers.
3028#[rustc_nounwind]
3029#[unstable(feature = "core_intrinsics", issue = "none")]
3030#[rustc_intrinsic_const_stable_indirect]
3031#[rustc_intrinsic]
3032pub const fn aggregate_raw_ptr<P: bounds::BuiltinDeref, D, M>(data: D, meta: M) -> P
3033where
3034 <P as bounds::BuiltinDeref>::Pointee: ptr::Pointee<Metadata = M>;
3035
3036/// Lowers in MIR to `Rvalue::UnaryOp` with `UnOp::PtrMetadata`.
3037///
3038/// This is used to implement functions like `ptr::metadata`.
3039#[rustc_nounwind]
3040#[unstable(feature = "core_intrinsics", issue = "none")]
3041#[rustc_intrinsic_const_stable_indirect]
3042#[rustc_intrinsic]
3043pub const fn ptr_metadata<P: ptr::Pointee<Metadata = M> + PointeeSized, M>(ptr: *const P) -> M;
3044
3045/// This is an accidentally-stable alias to [`ptr::copy_nonoverlapping`]; use that instead.
3046// Note (intentionally not in the doc comment): `ptr::copy_nonoverlapping` adds some extra
3047// debug assertions; if you are writing compiler tests or code inside the standard library
3048// that wants to avoid those debug assertions, directly call this intrinsic instead.
3049#[stable(feature = "rust1", since = "1.0.0")]
3050#[rustc_allowed_through_unstable_modules(
3051 message = "import this function via the `ptr` module instead",
3052 module = "ptr"
3053)]
3054#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
3055#[rustc_nounwind]
3056#[rustc_intrinsic]
3057pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
3058
3059/// This is an accidentally-stable alias to [`ptr::copy`]; use that instead.
3060// Note (intentionally not in the doc comment): `ptr::copy` adds some extra
3061// debug assertions; if you are writing compiler tests or code inside the standard library
3062// that wants to avoid those debug assertions, directly call this intrinsic instead.
3063#[stable(feature = "rust1", since = "1.0.0")]
3064#[rustc_allowed_through_unstable_modules(
3065 message = "import this function via the `ptr` module instead",
3066 module = "ptr"
3067)]
3068#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
3069#[rustc_nounwind]
3070#[rustc_intrinsic]
3071pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize);
3072
3073/// This is an accidentally-stable alias to [`ptr::write_bytes`]; use that instead.
3074// Note (intentionally not in the doc comment): `ptr::write_bytes` adds some extra
3075// debug assertions; if you are writing compiler tests or code inside the standard library
3076// that wants to avoid those debug assertions, directly call this intrinsic instead.
3077#[stable(feature = "rust1", since = "1.0.0")]
3078#[rustc_allowed_through_unstable_modules(
3079 message = "import this function via the `ptr` module instead",
3080 module = "ptr"
3081)]
3082#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
3083#[rustc_nounwind]
3084#[rustc_intrinsic]
3085pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
3086
3087/// Returns the minimum of two `f16` values, ignoring NaN.
3088///
3089/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3090/// zeros deterministically. In particular:
3091/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3092/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3093/// and `-0.0`), either input may be returned non-deterministically.
3094///
3095/// Note that, unlike most intrinsics, this is safe to call;
3096/// it does not require an `unsafe` block.
3097/// Therefore, implementations must not require the user to uphold
3098/// any safety invariants.
3099///
3100/// The stabilized version of this intrinsic is [`f16::min`].
3101#[rustc_nounwind]
3102#[rustc_intrinsic]
3103pub const fn minimum_number_nsz_f16(x: f16, y: f16) -> f16 {
3104 if x.is_nan() || y <= x {
3105 y
3106 } else {
3107 // Either y > x or y is a NaN.
3108 x
3109 }
3110}
3111
3112/// Returns the minimum of two `f32` values, ignoring NaN.
3113///
3114/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3115/// zeros deterministically. In particular:
3116/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3117/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3118/// and `-0.0`), either input may be returned non-deterministically.
3119///
3120/// Note that, unlike most intrinsics, this is safe to call;
3121/// it does not require an `unsafe` block.
3122/// Therefore, implementations must not require the user to uphold
3123/// any safety invariants.
3124///
3125/// The stabilized version of this intrinsic is [`f32::min`].
3126#[rustc_nounwind]
3127#[rustc_intrinsic_const_stable_indirect]
3128#[rustc_intrinsic]
3129pub const fn minimum_number_nsz_f32(x: f32, y: f32) -> f32 {
3130 if x.is_nan() || y <= x {
3131 y
3132 } else {
3133 // Either y > x or y is a NaN.
3134 x
3135 }
3136}
3137
3138/// Returns the minimum of two `f64` values, ignoring NaN.
3139///
3140/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3141/// zeros deterministically. In particular:
3142/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3143/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3144/// and `-0.0`), either input may be returned non-deterministically.
3145///
3146/// Note that, unlike most intrinsics, this is safe to call;
3147/// it does not require an `unsafe` block.
3148/// Therefore, implementations must not require the user to uphold
3149/// any safety invariants.
3150///
3151/// The stabilized version of this intrinsic is [`f64::min`].
3152#[rustc_nounwind]
3153#[rustc_intrinsic_const_stable_indirect]
3154#[rustc_intrinsic]
3155pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 {
3156 if x.is_nan() || y <= x {
3157 y
3158 } else {
3159 // Either y > x or y is a NaN.
3160 x
3161 }
3162}
3163
3164/// Returns the minimum of two `f128` values, ignoring NaN.
3165///
3166/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3167/// zeros deterministically. In particular:
3168/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3169/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3170/// and `-0.0`), either input may be returned non-deterministically.
3171///
3172/// Note that, unlike most intrinsics, this is safe to call;
3173/// it does not require an `unsafe` block.
3174/// Therefore, implementations must not require the user to uphold
3175/// any safety invariants.
3176///
3177/// The stabilized version of this intrinsic is [`f128::min`].
3178#[rustc_nounwind]
3179#[rustc_intrinsic]
3180pub const fn minimum_number_nsz_f128(x: f128, y: f128) -> f128 {
3181 if x.is_nan() || y <= x {
3182 y
3183 } else {
3184 // Either y > x or y is a NaN.
3185 x
3186 }
3187}
3188
3189/// Returns the minimum of two `f16` values, propagating NaN.
3190///
3191/// This behaves like IEEE 754-2019 minimum. In particular:
3192/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3193/// For this operation, -0.0 is considered to be strictly less than +0.0.
3194///
3195/// Note that, unlike most intrinsics, this is safe to call;
3196/// it does not require an `unsafe` block.
3197/// Therefore, implementations must not require the user to uphold
3198/// any safety invariants.
3199#[rustc_nounwind]
3200#[rustc_intrinsic]
3201pub const fn minimumf16(x: f16, y: f16) -> f16 {
3202 if x < y {
3203 x
3204 } else if y < x {
3205 y
3206 } else if x == y {
3207 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3208 } else {
3209 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3210 x + y
3211 }
3212}
3213
3214/// Returns the minimum of two `f32` values, propagating NaN.
3215///
3216/// This behaves like IEEE 754-2019 minimum. In particular:
3217/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3218/// For this operation, -0.0 is considered to be strictly less than +0.0.
3219///
3220/// Note that, unlike most intrinsics, this is safe to call;
3221/// it does not require an `unsafe` block.
3222/// Therefore, implementations must not require the user to uphold
3223/// any safety invariants.
3224#[rustc_nounwind]
3225#[rustc_intrinsic]
3226pub const fn minimumf32(x: f32, y: f32) -> f32 {
3227 if x < y {
3228 x
3229 } else if y < x {
3230 y
3231 } else if x == y {
3232 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3233 } else {
3234 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3235 x + y
3236 }
3237}
3238
3239/// Returns the minimum of two `f64` values, propagating NaN.
3240///
3241/// This behaves like IEEE 754-2019 minimum. In particular:
3242/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3243/// For this operation, -0.0 is considered to be strictly less than +0.0.
3244///
3245/// Note that, unlike most intrinsics, this is safe to call;
3246/// it does not require an `unsafe` block.
3247/// Therefore, implementations must not require the user to uphold
3248/// any safety invariants.
3249#[rustc_nounwind]
3250#[rustc_intrinsic]
3251pub const fn minimumf64(x: f64, y: f64) -> f64 {
3252 if x < y {
3253 x
3254 } else if y < x {
3255 y
3256 } else if x == y {
3257 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3258 } else {
3259 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3260 x + y
3261 }
3262}
3263
3264/// Returns the minimum of two `f128` values, propagating NaN.
3265///
3266/// This behaves like IEEE 754-2019 minimum. In particular:
3267/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3268/// For this operation, -0.0 is considered to be strictly less than +0.0.
3269///
3270/// Note that, unlike most intrinsics, this is safe to call;
3271/// it does not require an `unsafe` block.
3272/// Therefore, implementations must not require the user to uphold
3273/// any safety invariants.
3274#[rustc_nounwind]
3275#[rustc_intrinsic]
3276pub const fn minimumf128(x: f128, y: f128) -> f128 {
3277 if x < y {
3278 x
3279 } else if y < x {
3280 y
3281 } else if x == y {
3282 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3283 } else {
3284 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3285 x + y
3286 }
3287}
3288
3289/// Returns the maximum of two `f16` values, ignoring NaN.
3290///
3291/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3292/// zeros deterministically. In particular:
3293/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3294/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3295/// and `-0.0`), either input may be returned non-deterministically.
3296///
3297/// Note that, unlike most intrinsics, this is safe to call;
3298/// it does not require an `unsafe` block.
3299/// Therefore, implementations must not require the user to uphold
3300/// any safety invariants.
3301///
3302/// The stabilized version of this intrinsic is [`f16::max`].
3303#[rustc_nounwind]
3304#[rustc_intrinsic]
3305pub const fn maximum_number_nsz_f16(x: f16, y: f16) -> f16 {
3306 if x.is_nan() || y >= x {
3307 y
3308 } else {
3309 // Either y < x or y is a NaN.
3310 x
3311 }
3312}
3313
3314/// Returns the maximum of two `f32` values, ignoring NaN.
3315///
3316/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3317/// zeros deterministically. In particular:
3318/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3319/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3320/// and `-0.0`), either input may be returned non-deterministically.
3321///
3322/// Note that, unlike most intrinsics, this is safe to call;
3323/// it does not require an `unsafe` block.
3324/// Therefore, implementations must not require the user to uphold
3325/// any safety invariants.
3326///
3327/// The stabilized version of this intrinsic is [`f32::max`].
3328#[rustc_nounwind]
3329#[rustc_intrinsic_const_stable_indirect]
3330#[rustc_intrinsic]
3331pub const fn maximum_number_nsz_f32(x: f32, y: f32) -> f32 {
3332 if x.is_nan() || y >= x {
3333 y
3334 } else {
3335 // Either y < x or y is a NaN.
3336 x
3337 }
3338}
3339
3340/// Returns the maximum of two `f64` values, ignoring NaN.
3341///
3342/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3343/// zeros deterministically. In particular:
3344/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3345/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3346/// and `-0.0`), either input may be returned non-deterministically.
3347///
3348/// Note that, unlike most intrinsics, this is safe to call;
3349/// it does not require an `unsafe` block.
3350/// Therefore, implementations must not require the user to uphold
3351/// any safety invariants.
3352///
3353/// The stabilized version of this intrinsic is [`f64::max`].
3354#[rustc_nounwind]
3355#[rustc_intrinsic_const_stable_indirect]
3356#[rustc_intrinsic]
3357pub const fn maximum_number_nsz_f64(x: f64, y: f64) -> f64 {
3358 if x.is_nan() || y >= x {
3359 y
3360 } else {
3361 // Either y < x or y is a NaN.
3362 x
3363 }
3364}
3365
3366/// Returns the maximum of two `f128` values, ignoring NaN.
3367///
3368/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3369/// zeros deterministically. In particular:
3370/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3371/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3372/// and `-0.0`), either input may be returned non-deterministically.
3373///
3374/// Note that, unlike most intrinsics, this is safe to call;
3375/// it does not require an `unsafe` block.
3376/// Therefore, implementations must not require the user to uphold
3377/// any safety invariants.
3378///
3379/// The stabilized version of this intrinsic is [`f128::max`].
3380#[rustc_nounwind]
3381#[rustc_intrinsic]
3382pub const fn maximum_number_nsz_f128(x: f128, y: f128) -> f128 {
3383 if x.is_nan() || y >= x {
3384 y
3385 } else {
3386 // Either y < x or y is a NaN.
3387 x
3388 }
3389}
3390
3391/// Returns the maximum of two `f16` values, propagating NaN.
3392///
3393/// This behaves like IEEE 754-2019 maximum. In particular:
3394/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3395/// For this operation, -0.0 is considered to be strictly less than +0.0.
3396///
3397/// Note that, unlike most intrinsics, this is safe to call;
3398/// it does not require an `unsafe` block.
3399/// Therefore, implementations must not require the user to uphold
3400/// any safety invariants.
3401#[rustc_nounwind]
3402#[rustc_intrinsic]
3403pub const fn maximumf16(x: f16, y: f16) -> f16 {
3404 if x > y {
3405 x
3406 } else if y > x {
3407 y
3408 } else if x == y {
3409 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3410 } else {
3411 x + y
3412 }
3413}
3414
3415/// Returns the maximum of two `f32` values, propagating NaN.
3416///
3417/// This behaves like IEEE 754-2019 maximum. In particular:
3418/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3419/// For this operation, -0.0 is considered to be strictly less than +0.0.
3420///
3421/// Note that, unlike most intrinsics, this is safe to call;
3422/// it does not require an `unsafe` block.
3423/// Therefore, implementations must not require the user to uphold
3424/// any safety invariants.
3425#[rustc_nounwind]
3426#[rustc_intrinsic]
3427pub const fn maximumf32(x: f32, y: f32) -> f32 {
3428 if x > y {
3429 x
3430 } else if y > x {
3431 y
3432 } else if x == y {
3433 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3434 } else {
3435 x + y
3436 }
3437}
3438
3439/// Returns the maximum of two `f64` values, propagating NaN.
3440///
3441/// This behaves like IEEE 754-2019 maximum. In particular:
3442/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3443/// For this operation, -0.0 is considered to be strictly less than +0.0.
3444///
3445/// Note that, unlike most intrinsics, this is safe to call;
3446/// it does not require an `unsafe` block.
3447/// Therefore, implementations must not require the user to uphold
3448/// any safety invariants.
3449#[rustc_nounwind]
3450#[rustc_intrinsic]
3451pub const fn maximumf64(x: f64, y: f64) -> f64 {
3452 if x > y {
3453 x
3454 } else if y > x {
3455 y
3456 } else if x == y {
3457 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3458 } else {
3459 x + y
3460 }
3461}
3462
3463/// Returns the maximum of two `f128` values, propagating NaN.
3464///
3465/// This behaves like IEEE 754-2019 maximum. In particular:
3466/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3467/// For this operation, -0.0 is considered to be strictly less than +0.0.
3468///
3469/// Note that, unlike most intrinsics, this is safe to call;
3470/// it does not require an `unsafe` block.
3471/// Therefore, implementations must not require the user to uphold
3472/// any safety invariants.
3473#[rustc_nounwind]
3474#[rustc_intrinsic]
3475pub const fn maximumf128(x: f128, y: f128) -> f128 {
3476 if x > y {
3477 x
3478 } else if y > x {
3479 y
3480 } else if x == y {
3481 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3482 } else {
3483 x + y
3484 }
3485}
3486
3487/// Returns the absolute value of a floating-point value.
3488///
3489/// The stabilized versions of this intrinsic are available on the float
3490/// primitives via the `abs` method. For example, [`f32::abs`].
3491#[rustc_nounwind]
3492#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")]
3493#[rustc_intrinsic_const_stable_indirect]
3494#[rustc_intrinsic]
3495#[miri::intrinsic_fallback_is_spec]
3496#[rustc_do_not_const_check] // use built-in impl to avoid const-checks in the fallback body.
3497pub const fn fabs<T: bounds::FloatPrimitive>(x: T) -> T {
3498 T::from_bits(x.to_bits() & !T::SIGN_MASK)
3499}
3500
3501/// Copies the sign from `y` to `x` for `f16` values.
3502///
3503/// The stabilized version of this intrinsic is
3504/// [`f16::copysign`](../../std/primitive.f16.html#method.copysign)
3505#[inline]
3506#[rustc_nounwind]
3507#[rustc_intrinsic]
3508pub const fn copysignf16(x: f16, y: f16) -> f16 {
3509 f16::from_bits((x.to_bits() & !f16::SIGN_MASK) | (y.to_bits() & f16::SIGN_MASK))
3510}
3511
3512/// Copies the sign from `y` to `x` for `f32` values.
3513///
3514/// The stabilized version of this intrinsic is
3515/// [`f32::copysign`](../../std/primitive.f32.html#method.copysign)
3516#[inline]
3517#[rustc_nounwind]
3518#[rustc_intrinsic_const_stable_indirect]
3519#[rustc_intrinsic]
3520pub const fn copysignf32(x: f32, y: f32) -> f32 {
3521 f32::from_bits((x.to_bits() & !f32::SIGN_MASK) | (y.to_bits() & f32::SIGN_MASK))
3522}
3523/// Copies the sign from `y` to `x` for `f64` values.
3524///
3525/// The stabilized version of this intrinsic is
3526/// [`f64::copysign`](../../std/primitive.f64.html#method.copysign)
3527#[inline]
3528#[rustc_nounwind]
3529#[rustc_intrinsic_const_stable_indirect]
3530#[rustc_intrinsic]
3531pub const fn copysignf64(x: f64, y: f64) -> f64 {
3532 f64::from_bits((x.to_bits() & !f64::SIGN_MASK) | (y.to_bits() & f64::SIGN_MASK))
3533}
3534
3535/// Copies the sign from `y` to `x` for `f128` values.
3536///
3537/// The stabilized version of this intrinsic is
3538/// [`f128::copysign`](../../std/primitive.f128.html#method.copysign)
3539#[inline]
3540#[rustc_nounwind]
3541#[rustc_intrinsic]
3542pub const fn copysignf128(x: f128, y: f128) -> f128 {
3543 f128::from_bits((x.to_bits() & !f128::SIGN_MASK) | (y.to_bits() & f128::SIGN_MASK))
3544}
3545
3546/// Generates the LLVM body for the automatic differentiation of `f` using Enzyme,
3547/// with `df` as the derivative function and `args` as its arguments.
3548///
3549/// Used internally as the body of `df` when expanding the `#[autodiff_forward]`
3550/// and `#[autodiff_reverse]` attribute macros.
3551///
3552/// Type Parameters:
3553/// - `F`: The original function to differentiate. Must be a function item.
3554/// - `G`: The derivative function. Must be a function item.
3555/// - `T`: A tuple of arguments passed to `df`.
3556/// - `R`: The return type of the derivative function.
3557///
3558/// This shows where the `autodiff` intrinsic is used during macro expansion:
3559///
3560/// ```rust,ignore (macro example)
3561/// #[autodiff_forward(df1, Dual, Const, Dual)]
3562/// pub fn f1(x: &[f64], y: f64) -> f64 {
3563/// unimplemented!()
3564/// }
3565/// ```
3566///
3567/// expands to:
3568///
3569/// ```rust,ignore (macro example)
3570/// #[rustc_autodiff]
3571/// #[inline(never)]
3572/// pub fn f1(x: &[f64], y: f64) -> f64 {
3573/// ::core::panicking::panic("not implemented")
3574/// }
3575/// #[rustc_autodiff(Forward, 1, Dual, Const, Dual)]
3576/// pub fn df1(x: &[f64], bx_0: &[f64], y: f64) -> (f64, f64) {
3577/// ::core::intrinsics::autodiff(f1::<>, df1::<>, (x, bx_0, y))
3578/// }
3579/// ```
3580#[rustc_nounwind]
3581#[rustc_intrinsic]
3582pub const fn autodiff<F, G, T: crate::marker::Tuple, R>(f: F, df: G, args: T) -> R;
3583
3584/// Generates the LLVM body of a wrapper function to offload a kernel `f`.
3585///
3586/// Type Parameters:
3587/// - `F`: The kernel to offload. Must be a function item.
3588/// - `T`: A tuple of arguments passed to `f`.
3589/// - `R`: The return type of the kernel.
3590///
3591/// Arguments:
3592/// - `f`: The kernel function to offload.
3593/// - `workgroup_dim`: A 3D size specifying the number of workgroups to launch.
3594/// - `thread_dim`: A 3D size specifying the number of threads per workgroup.
3595/// - `dyn_cache`: The amount of dynamic shared memory to request for the kernel.
3596/// - `device_id`: The device to offload to. Use `-1` to select the default device.
3597/// - `args`: A tuple of arguments forwarded to `f`.
3598///
3599/// Example usage (pseudocode):
3600///
3601/// ```rust,ignore (pseudocode)
3602/// fn kernel(x: *mut [f64; 128]) {
3603/// core::intrinsics::offload(kernel_1, [256, 1, 1], [32, 1, 1], 0, -1, (x,))
3604/// }
3605///
3606/// #[cfg(target_os = "linux")]
3607/// extern "C" {
3608/// pub fn kernel_1(array_b: *mut [f64; 128]);
3609/// }
3610///
3611/// #[cfg(not(target_os = "linux"))]
3612/// #[rustc_offload_kernel]
3613/// extern "gpu-kernel" fn kernel_1(x: *mut [f64; 128]) {
3614/// unsafe { (*x)[0] = 21.0 };
3615/// }
3616/// ```
3617///
3618/// For reference, see the Clang documentation on offloading:
3619/// <https://clang.llvm.org/docs/OffloadingDesign.html>.
3620#[rustc_nounwind]
3621#[rustc_intrinsic]
3622pub const fn offload<F, T: crate::marker::Tuple, R>(
3623 f: F,
3624 workgroup_dim: [u32; 3],
3625 thread_dim: [u32; 3],
3626 dyn_cache: u32,
3627 device_id: i32,
3628 args: T,
3629) -> R;
3630
3631/// Returns the number of offload devices available on the system.
3632///
3633/// Use this to discover which `device_id` values are valid to pass to
3634/// [`offload`]. Devices are numbered from `0` to the returned value minus one.
3635///
3636/// Returns `0` if no offloading devices are present.
3637#[rustc_nounwind]
3638#[rustc_intrinsic]
3639pub const fn offload_get_num_devices() -> i32;
3640
3641/// Inform Miri that a given pointer definitely has a certain alignment.
3642#[cfg(miri)]
3643#[rustc_allow_const_fn_unstable(const_eval_select)]
3644pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize) {
3645 unsafe extern "Rust" {
3646 /// Miri-provided extern function to promise that a given pointer is properly aligned for
3647 /// "symbolic" alignment checks. Will fail if the pointer is not actually aligned or `align` is
3648 /// not a power of two. Has no effect when alignment checks are concrete (which is the default).
3649 fn miri_promise_symbolic_alignment(ptr: *const (), align: usize);
3650 }
3651
3652 const_eval_select!(
3653 @capture { ptr: *const (), align: usize}:
3654 if const {
3655 // Do nothing.
3656 } else {
3657 // SAFETY: this call is always safe.
3658 unsafe {
3659 miri_promise_symbolic_alignment(ptr, align);
3660 }
3661 }
3662 )
3663}
3664
3665/// Loads an argument of type `T` from the `va_list` `ap` and increment the
3666/// argument `ap` points to.
3667///
3668/// # Safety
3669///
3670/// This function is only sound to call when:
3671///
3672/// - there is a next variable argument available.
3673/// - the next argument's type must be ABI-compatible with the type `T`.
3674/// - the next argument must have a properly initialized value of type `T`.
3675///
3676/// Calling this function with an incompatible type, an invalid value, or when there
3677/// are no more variable arguments, is unsound.
3678///
3679#[rustc_intrinsic]
3680#[rustc_nounwind]
3681pub const unsafe fn va_arg<T: VaArgSafe>(ap: &mut VaList<'_>) -> T;
3682
3683/// Duplicates a variable argument list. The returned list is initially at the same position as
3684/// the one in `src`, but can be advanced independently.
3685///
3686/// Codegen backends should not have custom behavior for this intrinsic, they should always use
3687/// this fallback implementation. This intrinsic *does not* map to the LLVM `va_copy` intrinsic.
3688///
3689/// This intrinsic exists only as a hook for Miri and constant evaluation, and is used to detect UB
3690/// when a variable argument list is used incorrectly.
3691#[rustc_intrinsic]
3692#[rustc_nounwind]
3693pub const fn va_copy<'f>(src: &VaList<'f>) -> VaList<'f> {
3694 // This fallback body exploits the fact that our codegen backends all just use
3695 // a plain memcpy to duplicate VaList. This assumption is wrong for Miri.
3696 assert!(!cfg!(miri), "fallback body is incorrect under Miri");
3697
3698 src.duplicate()
3699}
3700
3701/// Destroy the variable argument list `ap` after initialization with `va_start` (part of the
3702/// desugaring of `...`) or `va_copy`.
3703///
3704/// Code generation backends should not provide a custom implementation for this intrinsic. This
3705/// intrinsic *does not* map to the LLVM `va_end` intrinsic.
3706///
3707/// This function is a no-op on all current targets, but used as a hook for const evaluation to
3708/// detect UB when a variable argument list is used incorrectly.
3709///
3710/// # Safety
3711///
3712/// `ap` must not be used to access variable arguments after this call.
3713///
3714#[rustc_intrinsic]
3715#[rustc_nounwind]
3716pub const unsafe fn va_end(ap: &mut VaList<'_>) {
3717 /* deliberately does nothing */
3718}
3719
3720/// Returns the return address of the caller function (after inlining) in a best-effort manner or a null pointer if it is not supported on the current backend.
3721/// Returning an accurate value is a quality-of-implementation concern, but no hard guarantees are
3722/// made about the return value: formally, the intrinsic non-deterministically returns
3723/// an arbitrary pointer without provenance.
3724///
3725/// Note that unlike most intrinsics, this is safe to call. This is because it only finds the return address of the immediate caller, which is guaranteed to be possible.
3726/// Other forms of the corresponding gcc or llvm intrinsic (which can have wildly unpredictable results or even crash at runtime) are not exposed.
3727#[rustc_intrinsic]
3728#[rustc_nounwind]
3729pub fn return_address() -> *const () {
3730 core::ptr::null()
3731}