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