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