Skip to main content

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