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