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