Skip to main content

core/intrinsics/
mod.rs

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