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