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