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