Skip to main content

core/intrinsics/
mod.rs

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