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 = "import this function via `std::mem` instead"]
866#[rustc_const_stable(feature = "const_transmute", since = "1.56.0")]
867#[rustc_diagnostic_item = "transmute"]
868#[rustc_nounwind]
869#[rustc_intrinsic]
870pub const unsafe fn transmute<Src, Dst>(src: Src) -> Dst;
871
872/// Like [`transmute`], but even less checked at compile-time: rather than
873/// giving an error for `size_of::<Src>() != size_of::<Dst>()`, it's
874/// **Undefined Behavior** at runtime.
875///
876/// Prefer normal `transmute` where possible, for the extra checking, since
877/// both do exactly the same thing at runtime, if they both compile.
878///
879/// This is not expected to ever be exposed directly to users, rather it
880/// may eventually be exposed through some more-constrained API.
881#[rustc_intrinsic_const_stable_indirect]
882#[rustc_nounwind]
883#[rustc_intrinsic]
884pub const unsafe fn transmute_unchecked<Src, Dst>(src: Src) -> Dst;
885
886/// Returns `true` if the actual type given as `T` requires drop
887/// glue; returns `false` if the actual type provided for `T`
888/// implements `Copy`.
889///
890/// If the actual type neither requires drop glue nor implements
891/// `Copy`, then the return value of this function is unspecified.
892///
893/// Note that, unlike most intrinsics, this can only be called at compile-time
894/// as backends do not have an implementation for it. The only caller (its
895/// stable counterpart) wraps this intrinsic call in a `const` block so that
896/// backends only see an evaluated constant.
897///
898/// The stabilized version of this intrinsic is [`mem::needs_drop`](crate::mem::needs_drop).
899#[rustc_intrinsic_const_stable_indirect]
900#[rustc_nounwind]
901#[rustc_intrinsic]
902#[rustc_comptime]
903pub fn needs_drop<T: ?Sized>() -> bool;
904
905/// Calculates the offset from a pointer.
906///
907/// This is implemented as an intrinsic to avoid converting to and from an
908/// integer, since the conversion would throw away aliasing information.
909///
910/// This can only be used with `Ptr` as a raw pointer type (`*mut` or `*const`)
911/// to a `Sized` pointee and with `Delta` as `usize` or `isize`. Any other
912/// instantiations may arbitrarily misbehave, and that's *not* a compiler bug.
913///
914/// # Safety
915///
916/// If the computed offset is non-zero, then both the starting and resulting pointer must be
917/// either in bounds or at the end of an allocation. If either pointer is out
918/// of bounds or arithmetic overflow occurs then this operation is undefined behavior.
919///
920/// The stabilized version of this intrinsic is [`pointer::offset`].
921#[must_use = "returns a new pointer rather than modifying its argument"]
922#[rustc_intrinsic_const_stable_indirect]
923#[rustc_nounwind]
924#[rustc_intrinsic]
925pub const unsafe fn offset<Ptr: bounds::BuiltinDeref, Delta>(dst: Ptr, offset: Delta) -> Ptr;
926
927/// Calculates the offset from a pointer, potentially wrapping.
928///
929/// This is implemented as an intrinsic to avoid converting to and from an
930/// integer, since the conversion inhibits certain optimizations.
931///
932/// # Safety
933///
934/// Unlike the `offset` intrinsic, this intrinsic does not restrict the
935/// resulting pointer to point into or at the end of an allocated
936/// object, and it wraps with two's complement arithmetic. The resulting
937/// value is not necessarily valid to be used to actually access memory.
938///
939/// The stabilized version of this intrinsic is [`pointer::wrapping_offset`].
940#[must_use = "returns a new pointer rather than modifying its argument"]
941#[rustc_intrinsic_const_stable_indirect]
942#[rustc_nounwind]
943#[rustc_intrinsic]
944pub const unsafe fn arith_offset<T>(dst: *const T, offset: isize) -> *const T;
945
946/// Projects to the `index`-th element of `slice_ptr`, as the same kind of pointer
947/// as the slice was provided -- so `&mut [T] → &mut T`, `&[T] → &T`,
948/// `*mut [T] → *mut T`, or `*const [T] → *const T` -- without a bounds check.
949///
950/// This is exposed via `<usize as SliceIndex>::get(_unchecked)(_mut)`,
951/// and isn't intended to be used elsewhere.
952///
953/// Expands in MIR to `{&, &mut, &raw const, &raw mut} (*slice_ptr)[index]`,
954/// depending on the types involved, so no backend support is needed.
955///
956/// # Safety
957///
958/// - `index < PtrMetadata(slice_ptr)`, so the indexing is in-bounds for the slice
959/// - the resulting offsetting is in-bounds of the allocation, which is
960/// always the case for references, but needs to be upheld manually for pointers
961#[rustc_nounwind]
962#[rustc_intrinsic]
963pub const unsafe fn slice_get_unchecked<
964 ItemPtr: bounds::ChangePointee<[T], Pointee = T, Output = SlicePtr>,
965 SlicePtr,
966 T,
967>(
968 slice_ptr: SlicePtr,
969 index: usize,
970) -> ItemPtr;
971
972/// Masks out bits of the pointer according to a mask.
973///
974/// Note that, unlike most intrinsics, this is safe to call;
975/// it does not require an `unsafe` block.
976/// Therefore, implementations must not require the user to uphold
977/// any safety invariants.
978///
979/// Consider using [`pointer::mask`] instead.
980#[rustc_nounwind]
981#[rustc_intrinsic]
982pub fn ptr_mask<T>(ptr: *const T, mask: usize) -> *const T;
983
984/// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with
985/// a size of `count` * `size_of::<T>()` and an alignment of `align_of::<T>()`.
986///
987/// This intrinsic does not have a stable counterpart.
988/// # Safety
989///
990/// The safety requirements are consistent with [`copy_nonoverlapping`]
991/// while the read and write behaviors are volatile,
992/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
993///
994/// [`copy_nonoverlapping`]: ptr::copy_nonoverlapping
995#[rustc_intrinsic]
996#[rustc_nounwind]
997pub unsafe fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize);
998/// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with
999/// a size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
1000///
1001/// The volatile parameter is set to `true`, so it will not be optimized out
1002/// unless size is equal to zero.
1003///
1004/// This intrinsic does not have a stable counterpart.
1005#[rustc_intrinsic]
1006#[rustc_nounwind]
1007pub unsafe fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize);
1008/// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a
1009/// size of `count * size_of::<T>()` and an alignment of `align_of::<T>()`.
1010///
1011/// This intrinsic does not have a stable counterpart.
1012/// # Safety
1013///
1014/// The safety requirements are consistent with [`write_bytes`] while the write behavior is volatile,
1015/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero.
1016///
1017/// [`write_bytes`]: ptr::write_bytes
1018#[rustc_intrinsic]
1019#[rustc_nounwind]
1020pub const unsafe fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize);
1021
1022/// Performs a volatile load from the `src` pointer.
1023///
1024/// The stabilized version of this intrinsic is [`core::ptr::read_volatile`].
1025#[rustc_intrinsic]
1026#[rustc_nounwind]
1027pub const unsafe fn volatile_load<T>(src: *const T) -> T;
1028/// Performs a volatile store to the `dst` pointer.
1029///
1030/// The stabilized version of this intrinsic is [`core::ptr::write_volatile`].
1031#[rustc_intrinsic]
1032#[rustc_nounwind]
1033pub const unsafe fn volatile_store<T>(dst: *mut T, val: T);
1034
1035/// Performs a volatile load from the `src` pointer
1036/// The pointer is not required to be aligned.
1037///
1038/// This intrinsic does not have a stable counterpart.
1039#[rustc_intrinsic]
1040#[rustc_nounwind]
1041#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_load"]
1042pub unsafe fn unaligned_volatile_load<T>(src: *const T) -> T;
1043/// Performs a volatile store to the `dst` pointer.
1044/// The pointer is not required to be aligned.
1045///
1046/// This intrinsic does not have a stable counterpart.
1047#[rustc_intrinsic]
1048#[rustc_nounwind]
1049#[rustc_diagnostic_item = "intrinsics_unaligned_volatile_store"]
1050pub unsafe fn unaligned_volatile_store<T>(dst: *mut T, val: T);
1051
1052/// Returns the square root of an `f16`
1053///
1054/// The stabilized version of this intrinsic is
1055/// [`f16::sqrt`](../../std/primitive.f16.html#method.sqrt)
1056#[inline]
1057#[rustc_intrinsic]
1058#[rustc_nounwind]
1059pub fn sqrtf16(x: f16) -> f16 {
1060 sqrtf32(x as f32) as f16
1061}
1062/// Returns the square root of an `f32`
1063///
1064/// The stabilized version of this intrinsic is
1065/// [`f32::sqrt`](../../std/primitive.f32.html#method.sqrt)
1066#[rustc_intrinsic]
1067#[rustc_nounwind]
1068pub fn sqrtf32(x: f32) -> f32;
1069/// Returns the square root of an `f64`
1070///
1071/// The stabilized version of this intrinsic is
1072/// [`f64::sqrt`](../../std/primitive.f64.html#method.sqrt)
1073#[rustc_intrinsic]
1074#[rustc_nounwind]
1075pub fn sqrtf64(x: f64) -> f64;
1076/// Returns the square root of an `f128`
1077///
1078/// The stabilized version of this intrinsic is
1079/// [`f128::sqrt`](../../std/primitive.f128.html#method.sqrt)
1080#[rustc_intrinsic]
1081#[rustc_nounwind]
1082pub fn sqrtf128(x: f128) -> f128;
1083
1084/// Raises an `f16` to an integer power.
1085///
1086/// The stabilized version of this intrinsic is
1087/// [`f16::powi`](../../std/primitive.f16.html#method.powi)
1088#[inline]
1089#[rustc_intrinsic]
1090#[rustc_nounwind]
1091pub fn powif16(a: f16, x: i32) -> f16 {
1092 powif32(a as f32, x) as f16
1093}
1094/// Raises an `f32` to an integer power.
1095///
1096/// The stabilized version of this intrinsic is
1097/// [`f32::powi`](../../std/primitive.f32.html#method.powi)
1098#[rustc_intrinsic]
1099#[rustc_nounwind]
1100pub fn powif32(a: f32, x: i32) -> f32;
1101/// Raises an `f64` to an integer power.
1102///
1103/// The stabilized version of this intrinsic is
1104/// [`f64::powi`](../../std/primitive.f64.html#method.powi)
1105#[rustc_intrinsic]
1106#[rustc_nounwind]
1107pub fn powif64(a: f64, x: i32) -> f64;
1108/// Raises an `f128` to an integer power.
1109///
1110/// The stabilized version of this intrinsic is
1111/// [`f128::powi`](../../std/primitive.f128.html#method.powi)
1112#[rustc_intrinsic]
1113#[rustc_nounwind]
1114pub fn powif128(a: f128, x: i32) -> f128;
1115
1116intrinsic_dispatch_on_type! {
1117 /// Returns the sine of a floating-point value.
1118 ///
1119 /// The stabilized versions of this intrinsic are available on the float primitives via the
1120 /// `sin` method. For example, [`f32::sin`](../../std/primitive.f32.html#method.sin).
1121 #[rustc_nounwind]
1122 #[inline]
1123 #[rustc_intrinsic]
1124 pub fn sin<T: bounds::FloatPrimitive>(x: T) -> T;
1125
1126 f16 => { sin(x as f32) as f16 }
1127 f32 => {
1128 cfg_select! {
1129 all(target_env = "msvc", target_arch = "x86") => sin(x as f64) as f32,
1130 _ => libm::likely_available::sinf(x),
1131 }
1132 }
1133 f64 => { libm::likely_available::sin(x) }
1134 f128 => { libm::maybe_available::sinf128(x) }
1135}
1136
1137intrinsic_dispatch_on_type! {
1138 /// Returns the cosine of a floating-point value.
1139 ///
1140 /// The stabilized versions of this intrinsic are available on the float primitives via the
1141 /// `cos` method. For example, [`f32::cos`](../../std/primitive.f32.html#method.cos).
1142 #[rustc_nounwind]
1143 #[inline]
1144 #[rustc_intrinsic]
1145 pub fn cos<T: bounds::FloatPrimitive>(x: T) -> T;
1146
1147 f16 => { cos(x as f32) as f16 }
1148 f32 => {
1149 cfg_select! {
1150 all(target_env = "msvc", target_arch = "x86") => cos(x as f64) as f32,
1151 _ => libm::likely_available::cosf(x),
1152 }
1153 }
1154 f64 => { libm::likely_available::cos(x) }
1155 f128 => { libm::maybe_available::cosf128(x) }
1156}
1157
1158/// Raises an `f16` to an `f16` power.
1159///
1160/// The stabilized version of this intrinsic is
1161/// [`f16::powf`](../../std/primitive.f16.html#method.powf)
1162#[inline]
1163#[rustc_intrinsic]
1164#[rustc_nounwind]
1165pub fn powf16(a: f16, x: f16) -> f16 {
1166 powf32(a as f32, x as f32) as f16
1167}
1168/// Raises an `f32` to an `f32` power.
1169///
1170/// The stabilized version of this intrinsic is
1171/// [`f32::powf`](../../std/primitive.f32.html#method.powf)
1172#[inline]
1173#[rustc_intrinsic]
1174#[rustc_nounwind]
1175pub fn powf32(a: f32, x: f32) -> f32 {
1176 cfg_select! {
1177 all(target_env = "msvc", target_arch = "x86") => powf64(a as f64, x as f64) as f32,
1178 _ => libm::likely_available::powf(a, x),
1179 }
1180}
1181/// Raises an `f64` to an `f64` power.
1182///
1183/// The stabilized version of this intrinsic is
1184/// [`f64::powf`](../../std/primitive.f64.html#method.powf)
1185#[inline]
1186#[rustc_intrinsic]
1187#[rustc_nounwind]
1188pub fn powf64(a: f64, x: f64) -> f64 {
1189 libm::likely_available::pow(a, x)
1190}
1191/// Raises an `f128` to an `f128` power.
1192///
1193/// The stabilized version of this intrinsic is
1194/// [`f128::powf`](../../std/primitive.f128.html#method.powf)
1195#[inline]
1196#[rustc_intrinsic]
1197#[rustc_nounwind]
1198pub fn powf128(a: f128, x: f128) -> f128 {
1199 libm::maybe_available::powf128(a, x)
1200}
1201
1202intrinsic_dispatch_on_type! {
1203 /// Returns the exponential of a floating-point value.
1204 ///
1205 /// The stabilized versions of this intrinsic are available on the float primitives via the
1206 /// `exp` method. For example, [`f32::exp`](../../std/primitive.f32.html#method.exp).
1207 #[rustc_nounwind]
1208 #[inline]
1209 #[rustc_intrinsic]
1210 pub fn exp<T: bounds::FloatPrimitive>(x: T) -> T;
1211
1212 f16 => { exp(x as f32) as f16 }
1213 f32 => {
1214 cfg_select! {
1215 all(target_env = "msvc", target_arch = "x86") => exp(x as f64) as f32,
1216 _ => libm::likely_available::expf(x),
1217 }
1218 }
1219 f64 => { libm::likely_available::exp(x) }
1220 f128 => { libm::maybe_available::expf128(x) }
1221}
1222
1223intrinsic_dispatch_on_type! {
1224 /// Returns 2 raised to the power of a floating-point value.
1225 ///
1226 /// The stabilized versions of this intrinsic are available on the float primitives via the
1227 /// `exp2` method. For example, [`f32::exp2`](../../std/primitive.f32.html#method.exp2).
1228 #[rustc_nounwind]
1229 #[inline]
1230 #[rustc_intrinsic]
1231 pub fn exp2<T: bounds::FloatPrimitive>(x: T) -> T;
1232
1233 f16 => { exp2(x as f32) as f16 }
1234 f32 => {
1235 cfg_select! {
1236 all(target_env = "msvc", target_arch = "x86") => exp2(x as f64) as f32,
1237 _ => libm::likely_available::exp2f(x),
1238 }
1239 }
1240 f64 => { libm::likely_available::exp2(x) }
1241 f128 => { libm::maybe_available::exp2f128(x) }
1242}
1243
1244intrinsic_dispatch_on_type! {
1245 /// Returns the natural logarithm of a floating-point value.
1246 ///
1247 /// The stabilized versions of this intrinsic are available on the float primitives via the
1248 /// `ln` method. For example, [`f32::ln`](../../std/primitive.f32.html#method.ln).
1249 #[rustc_nounwind]
1250 #[inline]
1251 #[rustc_intrinsic]
1252 pub fn log<T: bounds::FloatPrimitive>(x: T) -> T;
1253
1254 f16 => { log(x as f32) as f16 }
1255 f32 => {
1256 cfg_select! {
1257 all(target_env = "msvc", target_arch = "x86") => log(x as f64) as f32,
1258 _ => libm::likely_available::logf(x),
1259 }
1260 }
1261 f64 => { libm::likely_available::log(x) }
1262 f128 => { libm::maybe_available::logf128(x) }
1263}
1264
1265intrinsic_dispatch_on_type! {
1266 /// Returns the base 10 logarithm of a floating-point value.
1267 ///
1268 /// The stabilized versions of this intrinsic are available on the float primitives via the
1269 /// `log10` method. For example, [`f32::log10`](../../std/primitive.f32.html#method.log10).
1270 #[rustc_nounwind]
1271 #[inline]
1272 #[rustc_intrinsic]
1273 pub fn log10<T: bounds::FloatPrimitive>(x: T) -> T;
1274
1275 f16 => { log10(x as f32) as f16 }
1276 f32 => {
1277 cfg_select! {
1278 all(target_env = "msvc", target_arch = "x86") => log10(x as f64) as f32,
1279 _ => libm::likely_available::log10f(x),
1280 }
1281 }
1282 f64 => { libm::likely_available::log10(x) }
1283 f128 => { libm::maybe_available::log10f128(x) }
1284}
1285
1286intrinsic_dispatch_on_type! {
1287 /// Returns the base 2 logarithm of a floating-point value.
1288 ///
1289 /// The stabilized versions of this intrinsic are available on the float primitives via the
1290 /// `log2` method. For example, [`f32::log2`](../../std/primitive.f32.html#method.log2).
1291 #[rustc_nounwind]
1292 #[inline]
1293 #[rustc_intrinsic]
1294 pub fn log2<T: bounds::FloatPrimitive>(x: T) -> T;
1295
1296 f16 => { log2(x as f32) as f16 }
1297 f32 => {
1298 cfg_select! {
1299 all(target_env = "msvc", target_arch = "x86") => log2(x as f64) as f32,
1300 _ => libm::likely_available::log2f(x),
1301 }
1302 }
1303 f64 => { libm::likely_available::log2(x) }
1304 f128 => { libm::maybe_available::log2f128(x) }
1305}
1306
1307/// Returns `a * b + c` without rounding the intermediate result for `f16` values.
1308///
1309/// The stabilized version of this intrinsic is
1310/// [`f16::mul_add`](../../std/primitive.f16.html#method.mul_add)
1311#[rustc_intrinsic_const_stable_indirect]
1312#[inline]
1313#[rustc_intrinsic]
1314#[rustc_nounwind]
1315pub const fn fmaf16(a: f16, b: f16, c: f16) -> f16 {
1316 // NOTE: f32 does not have sufficient precision, so use f64 instead.
1317 // see also https://github.com/llvm/llvm-project/issues/128450#issuecomment-2727540179.
1318 fmaf64(a as f64, b as f64, c as f64) as f16
1319}
1320/// Returns `a * b + c` without rounding the intermediate result for `f32` values.
1321///
1322/// The stabilized version of this intrinsic is
1323/// [`f32::mul_add`](../../std/primitive.f32.html#method.mul_add)
1324#[rustc_intrinsic_const_stable_indirect]
1325#[rustc_intrinsic]
1326#[rustc_nounwind]
1327pub const fn fmaf32(a: f32, b: f32, c: f32) -> f32;
1328/// Returns `a * b + c` without rounding the intermediate result for `f64` values.
1329///
1330/// The stabilized version of this intrinsic is
1331/// [`f64::mul_add`](../../std/primitive.f64.html#method.mul_add)
1332#[rustc_intrinsic_const_stable_indirect]
1333#[rustc_intrinsic]
1334#[rustc_nounwind]
1335pub const fn fmaf64(a: f64, b: f64, c: f64) -> f64;
1336/// Returns `a * b + c` without rounding the intermediate result for `f128` values.
1337///
1338/// The stabilized version of this intrinsic is
1339/// [`f128::mul_add`](../../std/primitive.f128.html#method.mul_add)
1340#[rustc_intrinsic_const_stable_indirect]
1341#[rustc_intrinsic]
1342#[rustc_nounwind]
1343pub const fn fmaf128(a: f128, b: f128, c: f128) -> f128;
1344
1345/// Returns `a * b + c` for `f16` values, non-deterministically executing
1346/// either a fused multiply-add or two operations with rounding of the
1347/// intermediate result.
1348///
1349/// The operation is fused if the code generator determines that target
1350/// instruction set has support for a fused operation, and that the fused
1351/// operation is more efficient than the equivalent, separate pair of mul
1352/// and add instructions. It is unspecified whether or not a fused operation
1353/// is selected, and that may depend on optimization level and context, for
1354/// example.
1355#[inline]
1356#[rustc_intrinsic]
1357#[rustc_nounwind]
1358pub const fn fmuladdf16(a: f16, b: f16, c: f16) -> f16 {
1359 a * b + c
1360}
1361/// Returns `a * b + c` for `f32` values, non-deterministically executing
1362/// either a fused multiply-add or two operations with rounding of the
1363/// intermediate result.
1364///
1365/// The operation is fused if the code generator determines that target
1366/// instruction set has support for a fused operation, and that the fused
1367/// operation is more efficient than the equivalent, separate pair of mul
1368/// and add instructions. It is unspecified whether or not a fused operation
1369/// is selected, and that may depend on optimization level and context, for
1370/// example.
1371#[inline]
1372#[rustc_intrinsic]
1373#[rustc_nounwind]
1374pub const fn fmuladdf32(a: f32, b: f32, c: f32) -> f32 {
1375 a * b + c
1376}
1377/// Returns `a * b + c` for `f64` values, non-deterministically executing
1378/// either a fused multiply-add or two operations with rounding of the
1379/// intermediate result.
1380///
1381/// The operation is fused if the code generator determines that target
1382/// instruction set has support for a fused operation, and that the fused
1383/// operation is more efficient than the equivalent, separate pair of mul
1384/// and add instructions. It is unspecified whether or not a fused operation
1385/// is selected, and that may depend on optimization level and context, for
1386/// example.
1387#[inline]
1388#[rustc_intrinsic]
1389#[rustc_nounwind]
1390pub const fn fmuladdf64(a: f64, b: f64, c: f64) -> f64 {
1391 a * b + c
1392}
1393/// Returns `a * b + c` for `f128` values, non-deterministically executing
1394/// either a fused multiply-add or two operations with rounding of the
1395/// intermediate result.
1396///
1397/// The operation is fused if the code generator determines that target
1398/// instruction set has support for a fused operation, and that the fused
1399/// operation is more efficient than the equivalent, separate pair of mul
1400/// and add instructions. It is unspecified whether or not a fused operation
1401/// is selected, and that may depend on optimization level and context, for
1402/// example.
1403#[inline]
1404#[rustc_intrinsic]
1405#[rustc_nounwind]
1406pub const fn fmuladdf128(a: f128, b: f128, c: f128) -> f128 {
1407 a * b + c
1408}
1409
1410/// Returns the largest integer less than or equal to an `f16`.
1411///
1412/// The stabilized version of this intrinsic is
1413/// [`f16::floor`](../../std/primitive.f16.html#method.floor)
1414#[rustc_intrinsic_const_stable_indirect]
1415#[inline]
1416#[rustc_intrinsic]
1417#[rustc_nounwind]
1418pub const fn floorf16(x: f16) -> f16 {
1419 floorf32(x as f32) as f16
1420}
1421/// Returns the largest integer less than or equal to an `f32`.
1422///
1423/// The stabilized version of this intrinsic is
1424/// [`f32::floor`](../../std/primitive.f32.html#method.floor)
1425#[rustc_intrinsic_const_stable_indirect]
1426#[rustc_intrinsic]
1427#[rustc_nounwind]
1428pub const fn floorf32(x: f32) -> f32;
1429/// Returns the largest integer less than or equal to an `f64`.
1430///
1431/// The stabilized version of this intrinsic is
1432/// [`f64::floor`](../../std/primitive.f64.html#method.floor)
1433#[rustc_intrinsic_const_stable_indirect]
1434#[rustc_intrinsic]
1435#[rustc_nounwind]
1436pub const fn floorf64(x: f64) -> f64;
1437/// Returns the largest integer less than or equal to an `f128`.
1438///
1439/// The stabilized version of this intrinsic is
1440/// [`f128::floor`](../../std/primitive.f128.html#method.floor)
1441#[rustc_intrinsic_const_stable_indirect]
1442#[rustc_intrinsic]
1443#[rustc_nounwind]
1444pub const fn floorf128(x: f128) -> f128;
1445
1446/// Returns the smallest integer greater than or equal to an `f16`.
1447///
1448/// The stabilized version of this intrinsic is
1449/// [`f16::ceil`](../../std/primitive.f16.html#method.ceil)
1450#[rustc_intrinsic_const_stable_indirect]
1451#[inline]
1452#[rustc_intrinsic]
1453#[rustc_nounwind]
1454pub const fn ceilf16(x: f16) -> f16 {
1455 ceilf32(x as f32) as f16
1456}
1457/// Returns the smallest integer greater than or equal to an `f32`.
1458///
1459/// The stabilized version of this intrinsic is
1460/// [`f32::ceil`](../../std/primitive.f32.html#method.ceil)
1461#[rustc_intrinsic_const_stable_indirect]
1462#[rustc_intrinsic]
1463#[rustc_nounwind]
1464pub const fn ceilf32(x: f32) -> f32;
1465/// Returns the smallest integer greater than or equal to an `f64`.
1466///
1467/// The stabilized version of this intrinsic is
1468/// [`f64::ceil`](../../std/primitive.f64.html#method.ceil)
1469#[rustc_intrinsic_const_stable_indirect]
1470#[rustc_intrinsic]
1471#[rustc_nounwind]
1472pub const fn ceilf64(x: f64) -> f64;
1473/// Returns the smallest integer greater than or equal to an `f128`.
1474///
1475/// The stabilized version of this intrinsic is
1476/// [`f128::ceil`](../../std/primitive.f128.html#method.ceil)
1477#[rustc_intrinsic_const_stable_indirect]
1478#[rustc_intrinsic]
1479#[rustc_nounwind]
1480pub const fn ceilf128(x: f128) -> f128;
1481
1482/// Returns the integer part of an `f16`.
1483///
1484/// The stabilized version of this intrinsic is
1485/// [`f16::trunc`](../../std/primitive.f16.html#method.trunc)
1486#[rustc_intrinsic_const_stable_indirect]
1487#[inline]
1488#[rustc_intrinsic]
1489#[rustc_nounwind]
1490pub const fn truncf16(x: f16) -> f16 {
1491 truncf32(x as f32) as f16
1492}
1493/// Returns the integer part of an `f32`.
1494///
1495/// The stabilized version of this intrinsic is
1496/// [`f32::trunc`](../../std/primitive.f32.html#method.trunc)
1497#[rustc_intrinsic_const_stable_indirect]
1498#[rustc_intrinsic]
1499#[rustc_nounwind]
1500pub const fn truncf32(x: f32) -> f32;
1501/// Returns the integer part of an `f64`.
1502///
1503/// The stabilized version of this intrinsic is
1504/// [`f64::trunc`](../../std/primitive.f64.html#method.trunc)
1505#[rustc_intrinsic_const_stable_indirect]
1506#[rustc_intrinsic]
1507#[rustc_nounwind]
1508pub const fn truncf64(x: f64) -> f64;
1509/// Returns the integer part of an `f128`.
1510///
1511/// The stabilized version of this intrinsic is
1512/// [`f128::trunc`](../../std/primitive.f128.html#method.trunc)
1513#[rustc_intrinsic_const_stable_indirect]
1514#[rustc_intrinsic]
1515#[rustc_nounwind]
1516pub const fn truncf128(x: f128) -> f128;
1517
1518/// Returns the nearest integer to an `f16`. Rounds half-way cases to the number with an even
1519/// least significant digit.
1520///
1521/// The stabilized version of this intrinsic is
1522/// [`f16::round_ties_even`](../../std/primitive.f16.html#method.round_ties_even)
1523#[rustc_intrinsic_const_stable_indirect]
1524#[inline]
1525#[rustc_intrinsic]
1526#[rustc_nounwind]
1527pub const fn round_ties_even_f16(x: f16) -> f16 {
1528 round_ties_even_f32(x as f32) as f16
1529}
1530
1531/// Returns the nearest integer to an `f32`. Rounds half-way cases to the number with an even
1532/// least significant digit.
1533///
1534/// The stabilized version of this intrinsic is
1535/// [`f32::round_ties_even`](../../std/primitive.f32.html#method.round_ties_even)
1536#[rustc_intrinsic_const_stable_indirect]
1537#[rustc_intrinsic]
1538#[rustc_nounwind]
1539pub const fn round_ties_even_f32(x: f32) -> f32;
1540
1541/// Returns the nearest integer to an `f64`. Rounds half-way cases to the number with an even
1542/// least significant digit.
1543///
1544/// The stabilized version of this intrinsic is
1545/// [`f64::round_ties_even`](../../std/primitive.f64.html#method.round_ties_even)
1546#[rustc_intrinsic_const_stable_indirect]
1547#[rustc_intrinsic]
1548#[rustc_nounwind]
1549pub const fn round_ties_even_f64(x: f64) -> f64;
1550
1551/// Returns the nearest integer to an `f128`. Rounds half-way cases to the number with an even
1552/// least significant digit.
1553///
1554/// The stabilized version of this intrinsic is
1555/// [`f128::round_ties_even`](../../std/primitive.f128.html#method.round_ties_even)
1556#[rustc_intrinsic_const_stable_indirect]
1557#[rustc_intrinsic]
1558#[rustc_nounwind]
1559pub const fn round_ties_even_f128(x: f128) -> f128;
1560
1561/// Returns the nearest integer to an `f16`. Rounds half-way cases away from zero.
1562///
1563/// The stabilized version of this intrinsic is
1564/// [`f16::round`](../../std/primitive.f16.html#method.round)
1565#[rustc_intrinsic_const_stable_indirect]
1566#[inline]
1567#[rustc_intrinsic]
1568#[rustc_nounwind]
1569pub const fn roundf16(x: f16) -> f16 {
1570 roundf32(x as f32) as f16
1571}
1572/// Returns the nearest integer to an `f32`. Rounds half-way cases away from zero.
1573///
1574/// The stabilized version of this intrinsic is
1575/// [`f32::round`](../../std/primitive.f32.html#method.round)
1576#[rustc_intrinsic_const_stable_indirect]
1577#[rustc_intrinsic]
1578#[rustc_nounwind]
1579pub const fn roundf32(x: f32) -> f32;
1580/// Returns the nearest integer to an `f64`. Rounds half-way cases away from zero.
1581///
1582/// The stabilized version of this intrinsic is
1583/// [`f64::round`](../../std/primitive.f64.html#method.round)
1584#[rustc_intrinsic_const_stable_indirect]
1585#[rustc_intrinsic]
1586#[rustc_nounwind]
1587pub const fn roundf64(x: f64) -> f64;
1588/// Returns the nearest integer to an `f128`. Rounds half-way cases away from zero.
1589///
1590/// The stabilized version of this intrinsic is
1591/// [`f128::round`](../../std/primitive.f128.html#method.round)
1592#[rustc_intrinsic_const_stable_indirect]
1593#[rustc_intrinsic]
1594#[rustc_nounwind]
1595pub const fn roundf128(x: f128) -> f128;
1596
1597/// Float addition that allows optimizations based on algebraic rules.
1598/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1599///
1600/// This intrinsic does not have a stable counterpart.
1601#[rustc_intrinsic]
1602#[rustc_nounwind]
1603pub unsafe fn fadd_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1604
1605/// Float subtraction that allows optimizations based on algebraic rules.
1606/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1607///
1608/// This intrinsic does not have a stable counterpart.
1609#[rustc_intrinsic]
1610#[rustc_nounwind]
1611pub unsafe fn fsub_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1612
1613/// Float multiplication that allows optimizations based on algebraic rules.
1614/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1615///
1616/// This intrinsic does not have a stable counterpart.
1617#[rustc_intrinsic]
1618#[rustc_nounwind]
1619pub unsafe fn fmul_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1620
1621/// Float division that allows optimizations based on algebraic rules.
1622/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1623///
1624/// This intrinsic does not have a stable counterpart.
1625#[rustc_intrinsic]
1626#[rustc_nounwind]
1627pub unsafe fn fdiv_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1628
1629/// Float remainder that allows optimizations based on algebraic rules.
1630/// Requires that inputs and output of the operation are finite, causing UB otherwise.
1631///
1632/// This intrinsic does not have a stable counterpart.
1633#[rustc_intrinsic]
1634#[rustc_nounwind]
1635pub unsafe fn frem_fast<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1636
1637/// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range
1638/// (<https://github.com/rust-lang/rust/issues/10184>)
1639///
1640/// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`].
1641#[rustc_intrinsic]
1642#[rustc_nounwind]
1643pub unsafe fn float_to_int_unchecked<Float: bounds::FloatPrimitive, Int: Copy>(value: Float)
1644-> Int;
1645
1646/// Float addition that allows optimizations based on algebraic rules.
1647///
1648/// Stabilized as [`f16::algebraic_add`], [`f32::algebraic_add`], [`f64::algebraic_add`] and [`f128::algebraic_add`].
1649#[rustc_intrinsic_const_stable_indirect]
1650#[rustc_nounwind]
1651#[rustc_intrinsic]
1652pub const fn fadd_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1653
1654/// Float subtraction that allows optimizations based on algebraic rules.
1655///
1656/// Stabilized as [`f16::algebraic_sub`], [`f32::algebraic_sub`], [`f64::algebraic_sub`] and [`f128::algebraic_sub`].
1657#[rustc_intrinsic_const_stable_indirect]
1658#[rustc_nounwind]
1659#[rustc_intrinsic]
1660pub const fn fsub_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1661
1662/// Float multiplication that allows optimizations based on algebraic rules.
1663///
1664/// Stabilized as [`f16::algebraic_mul`], [`f32::algebraic_mul`], [`f64::algebraic_mul`] and [`f128::algebraic_mul`].
1665#[rustc_intrinsic_const_stable_indirect]
1666#[rustc_nounwind]
1667#[rustc_intrinsic]
1668pub const fn fmul_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1669
1670/// Float division that allows optimizations based on algebraic rules.
1671///
1672/// Stabilized as [`f16::algebraic_div`], [`f32::algebraic_div`], [`f64::algebraic_div`] and [`f128::algebraic_div`].
1673#[rustc_intrinsic_const_stable_indirect]
1674#[rustc_nounwind]
1675#[rustc_intrinsic]
1676pub const fn fdiv_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1677
1678/// Float remainder that allows optimizations based on algebraic rules.
1679///
1680/// Stabilized as [`f16::algebraic_rem`], [`f32::algebraic_rem`], [`f64::algebraic_rem`] and [`f128::algebraic_rem`].
1681#[rustc_intrinsic_const_stable_indirect]
1682#[rustc_nounwind]
1683#[rustc_intrinsic]
1684pub const fn frem_algebraic<T: bounds::FloatPrimitive>(a: T, b: T) -> T;
1685
1686/// Integer `min`imum, signed or unsigned depending on `T`.
1687///
1688/// Allowed only on `uN`, `iN`, `usize`, and `isize`.
1689/// (Not on `bool` nor on `char`.)
1690///
1691/// Stabilized as [`u16::min`] and [`i64::min`] and similar.
1692#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1693#[rustc_nounwind]
1694#[rustc_intrinsic]
1695#[miri::intrinsic_fallback_is_spec]
1696pub const fn integer_min<T: [const] bounds::IntegerPrimitive>(a: T, b: T) -> T {
1697 if a < b { a } else { b }
1698}
1699
1700/// Integer `max`imum, signed or unsigned depending on `T`.
1701///
1702/// Allowed only on `uN`, `iN`, `usize`, and `isize`.
1703/// (Not on `bool` nor on `char`.)
1704///
1705/// Stabilized as [`u16::max`] and [`i64::max`] and similar.
1706#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1707#[rustc_nounwind]
1708#[rustc_intrinsic]
1709#[miri::intrinsic_fallback_is_spec]
1710pub const fn integer_max<T: [const] bounds::IntegerPrimitive>(a: T, b: T) -> T {
1711 if a < b { b } else { a }
1712}
1713
1714/// Returns the number of bits set in an integer type `T`
1715///
1716/// Note that, unlike most intrinsics, this is safe to call;
1717/// it does not require an `unsafe` block.
1718/// Therefore, implementations must not require the user to uphold
1719/// any safety invariants.
1720///
1721/// The stabilized versions of this intrinsic are available on the integer
1722/// primitives via the `count_ones` method. For example,
1723/// [`u32::count_ones`]
1724#[rustc_intrinsic_const_stable_indirect]
1725#[rustc_nounwind]
1726#[rustc_intrinsic]
1727pub const fn ctpop<T: Copy>(x: T) -> u32;
1728
1729/// Returns the number of leading unset bits (zeroes) in an integer type `T`.
1730///
1731/// Note that, unlike most intrinsics, this is safe to call;
1732/// it does not require an `unsafe` block.
1733/// Therefore, implementations must not require the user to uphold
1734/// any safety invariants.
1735///
1736/// The stabilized versions of this intrinsic are available on the integer
1737/// primitives via the `leading_zeros` method. For example,
1738/// [`u32::leading_zeros`]
1739///
1740/// # Examples
1741///
1742/// ```
1743/// #![feature(core_intrinsics)]
1744/// # #![allow(internal_features)]
1745///
1746/// use std::intrinsics::ctlz;
1747///
1748/// let x = 0b0001_1100_u8;
1749/// let num_leading = ctlz(x);
1750/// assert_eq!(num_leading, 3);
1751/// ```
1752///
1753/// An `x` with value `0` will return the bit width of `T`.
1754///
1755/// ```
1756/// #![feature(core_intrinsics)]
1757/// # #![allow(internal_features)]
1758///
1759/// use std::intrinsics::ctlz;
1760///
1761/// let x = 0u16;
1762/// let num_leading = ctlz(x);
1763/// assert_eq!(num_leading, 16);
1764/// ```
1765#[rustc_intrinsic_const_stable_indirect]
1766#[rustc_nounwind]
1767#[rustc_intrinsic]
1768pub const fn ctlz<T: Copy>(x: T) -> u32;
1769
1770/// Like `ctlz`, but extra-unsafe as it returns `undef` when
1771/// given an `x` with value `0`.
1772///
1773/// This intrinsic does not have a stable counterpart.
1774///
1775/// # Examples
1776///
1777/// ```
1778/// #![feature(core_intrinsics)]
1779/// # #![allow(internal_features)]
1780///
1781/// use std::intrinsics::ctlz_nonzero;
1782///
1783/// let x = 0b0001_1100_u8;
1784/// let num_leading = unsafe { ctlz_nonzero(x) };
1785/// assert_eq!(num_leading, 3);
1786/// ```
1787#[rustc_intrinsic_const_stable_indirect]
1788#[rustc_nounwind]
1789#[rustc_intrinsic]
1790pub const unsafe fn ctlz_nonzero<T: Copy>(x: T) -> u32;
1791
1792/// Returns the number of trailing unset bits (zeroes) in an integer type `T`.
1793///
1794/// Note that, unlike most intrinsics, this is safe to call;
1795/// it does not require an `unsafe` block.
1796/// Therefore, implementations must not require the user to uphold
1797/// any safety invariants.
1798///
1799/// The stabilized versions of this intrinsic are available on the integer
1800/// primitives via the `trailing_zeros` method. For example,
1801/// [`u32::trailing_zeros`]
1802///
1803/// # Examples
1804///
1805/// ```
1806/// #![feature(core_intrinsics)]
1807/// # #![allow(internal_features)]
1808///
1809/// use std::intrinsics::cttz;
1810///
1811/// let x = 0b0011_1000_u8;
1812/// let num_trailing = cttz(x);
1813/// assert_eq!(num_trailing, 3);
1814/// ```
1815///
1816/// An `x` with value `0` will return the bit width of `T`:
1817///
1818/// ```
1819/// #![feature(core_intrinsics)]
1820/// # #![allow(internal_features)]
1821///
1822/// use std::intrinsics::cttz;
1823///
1824/// let x = 0u16;
1825/// let num_trailing = cttz(x);
1826/// assert_eq!(num_trailing, 16);
1827/// ```
1828#[rustc_intrinsic_const_stable_indirect]
1829#[rustc_nounwind]
1830#[rustc_intrinsic]
1831pub const fn cttz<T: Copy>(x: T) -> u32;
1832
1833/// Like `cttz`, but extra-unsafe as it returns `undef` when
1834/// given an `x` with value `0`.
1835///
1836/// This intrinsic does not have a stable counterpart.
1837///
1838/// # Examples
1839///
1840/// ```
1841/// #![feature(core_intrinsics)]
1842/// # #![allow(internal_features)]
1843///
1844/// use std::intrinsics::cttz_nonzero;
1845///
1846/// let x = 0b0011_1000_u8;
1847/// let num_trailing = unsafe { cttz_nonzero(x) };
1848/// assert_eq!(num_trailing, 3);
1849/// ```
1850#[rustc_intrinsic_const_stable_indirect]
1851#[rustc_nounwind]
1852#[rustc_intrinsic]
1853pub const unsafe fn cttz_nonzero<T: Copy>(x: T) -> u32;
1854
1855/// Reverses the bytes in an integer type `T`.
1856///
1857/// Note that, unlike most intrinsics, this is safe to call;
1858/// it does not require an `unsafe` block.
1859/// Therefore, implementations must not require the user to uphold
1860/// any safety invariants.
1861///
1862/// The stabilized versions of this intrinsic are available on the integer
1863/// primitives via the `swap_bytes` method. For example,
1864/// [`u32::swap_bytes`]
1865#[rustc_intrinsic_const_stable_indirect]
1866#[rustc_nounwind]
1867#[rustc_intrinsic]
1868pub const fn bswap<T: Copy>(x: T) -> T;
1869
1870/// Reverses the bits in an integer type `T`.
1871///
1872/// Note that, unlike most intrinsics, this is safe to call;
1873/// it does not require an `unsafe` block.
1874/// Therefore, implementations must not require the user to uphold
1875/// any safety invariants.
1876///
1877/// The stabilized versions of this intrinsic are available on the integer
1878/// primitives via the `reverse_bits` method. For example,
1879/// [`u32::reverse_bits`]
1880#[rustc_intrinsic_const_stable_indirect]
1881#[rustc_nounwind]
1882#[rustc_intrinsic]
1883pub const fn bitreverse<T: Copy>(x: T) -> T;
1884
1885/// Does a three-way comparison between the two arguments,
1886/// which must be of character or integer (signed or unsigned) type.
1887///
1888/// This was originally added because it greatly simplified the MIR in `cmp`
1889/// implementations, and then LLVM 20 added a backend intrinsic for it too.
1890///
1891/// The stabilized version of this intrinsic is [`Ord::cmp`].
1892#[rustc_intrinsic_const_stable_indirect]
1893#[rustc_nounwind]
1894#[rustc_intrinsic]
1895pub const fn three_way_compare<T: Copy>(lhs: T, rhss: T) -> crate::cmp::Ordering;
1896
1897/// Combine two values which have no bits in common.
1898///
1899/// This allows the backend to implement it as `a + b` *or* `a | b`,
1900/// depending which is easier to implement on a specific target.
1901///
1902/// # Safety
1903///
1904/// Requires that `(a & b) == 0`, or equivalently that `(a | b) == (a + b)`.
1905///
1906/// Otherwise it's immediate UB.
1907#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1908#[rustc_nounwind]
1909#[rustc_intrinsic]
1910#[track_caller]
1911#[miri::intrinsic_fallback_is_spec] // the fallbacks all `assume` to tell Miri
1912pub const unsafe fn disjoint_bitor<T: [const] fallback::DisjointBitOr>(a: T, b: T) -> T {
1913 // SAFETY: same preconditions as this function.
1914 unsafe { fallback::DisjointBitOr::disjoint_bitor(a, b) }
1915}
1916
1917/// Performs checked integer addition.
1918///
1919/// Note that, unlike most intrinsics, this is safe to call;
1920/// it does not require an `unsafe` block.
1921/// Therefore, implementations must not require the user to uphold
1922/// any safety invariants.
1923///
1924/// The stabilized versions of this intrinsic are available on the integer
1925/// primitives via the `overflowing_add` method. For example,
1926/// [`u32::overflowing_add`]
1927#[rustc_intrinsic_const_stable_indirect]
1928#[rustc_nounwind]
1929#[rustc_intrinsic]
1930pub const fn add_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1931
1932/// Performs checked integer subtraction
1933///
1934/// Note that, unlike most intrinsics, this is safe to call;
1935/// it does not require an `unsafe` block.
1936/// Therefore, implementations must not require the user to uphold
1937/// any safety invariants.
1938///
1939/// The stabilized versions of this intrinsic are available on the integer
1940/// primitives via the `overflowing_sub` method. For example,
1941/// [`u32::overflowing_sub`]
1942#[rustc_intrinsic_const_stable_indirect]
1943#[rustc_nounwind]
1944#[rustc_intrinsic]
1945pub const fn sub_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1946
1947/// Performs checked integer multiplication
1948///
1949/// Note that, unlike most intrinsics, this is safe to call;
1950/// it does not require an `unsafe` block.
1951/// Therefore, implementations must not require the user to uphold
1952/// any safety invariants.
1953///
1954/// The stabilized versions of this intrinsic are available on the integer
1955/// primitives via the `overflowing_mul` method. For example,
1956/// [`u32::overflowing_mul`]
1957#[rustc_intrinsic_const_stable_indirect]
1958#[rustc_nounwind]
1959#[rustc_intrinsic]
1960pub const fn mul_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1961
1962/// Performs full-width multiplication and addition with a carry:
1963/// `multiplier * multiplicand + addend + carry`.
1964///
1965/// This is possible without any overflow. For `uN`:
1966/// MAX * MAX + MAX + MAX
1967/// => (2ⁿ-1) × (2ⁿ-1) + (2ⁿ-1) + (2ⁿ-1)
1968/// => (2²ⁿ - 2ⁿ⁺¹ + 1) + (2ⁿ⁺¹ - 2)
1969/// => 2²ⁿ - 1
1970///
1971/// For `iN`, the upper bound is MIN * MIN + MAX + MAX => 2²ⁿ⁻² + 2ⁿ - 2,
1972/// and the lower bound is MAX * MIN + MIN + MIN => -2²ⁿ⁻² - 2ⁿ + 2ⁿ⁺¹.
1973///
1974/// This currently supports unsigned integers *only*, no signed ones.
1975/// The stabilized versions of this intrinsic are available on integers.
1976#[unstable(feature = "core_intrinsics", issue = "none")]
1977#[rustc_const_unstable(feature = "const_carrying_mul_add", issue = "85532")]
1978#[rustc_nounwind]
1979#[rustc_intrinsic]
1980#[miri::intrinsic_fallback_is_spec]
1981pub const fn carrying_mul_add<T: [const] fallback::CarryingMulAdd<Unsigned = U>, U>(
1982 multiplier: T,
1983 multiplicand: T,
1984 addend: T,
1985 carry: T,
1986) -> (U, T) {
1987 multiplier.carrying_mul_add(multiplicand, addend, carry)
1988}
1989
1990/// Performs an exact division, resulting in undefined behavior where
1991/// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`
1992///
1993/// This intrinsic does not have a stable counterpart.
1994#[rustc_intrinsic_const_stable_indirect]
1995#[rustc_nounwind]
1996#[rustc_intrinsic]
1997pub const unsafe fn exact_div<T: Copy>(x: T, y: T) -> T;
1998
1999/// Performs an unchecked division, resulting in undefined behavior
2000/// where `y == 0` or `x == T::MIN && y == -1`
2001///
2002/// Safe wrappers for this intrinsic are available on the integer
2003/// primitives via the `checked_div` method. For example,
2004/// [`u32::checked_div`]
2005#[rustc_intrinsic_const_stable_indirect]
2006#[rustc_nounwind]
2007#[rustc_intrinsic]
2008pub const unsafe fn unchecked_div<T: Copy>(x: T, y: T) -> T;
2009/// Returns the remainder of an unchecked division, resulting in
2010/// undefined behavior when `y == 0` or `x == T::MIN && y == -1`
2011///
2012/// Safe wrappers for this intrinsic are available on the integer
2013/// primitives via the `checked_rem` method. For example,
2014/// [`u32::checked_rem`]
2015#[rustc_intrinsic_const_stable_indirect]
2016#[rustc_nounwind]
2017#[rustc_intrinsic]
2018pub const unsafe fn unchecked_rem<T: Copy>(x: T, y: T) -> T;
2019
2020/// Performs an unchecked left shift, resulting in undefined behavior when
2021/// `y < 0` or `y >= N`, where N is the width of T in bits.
2022///
2023/// Safe wrappers for this intrinsic are available on the integer
2024/// primitives via the `checked_shl` method. For example,
2025/// [`u32::checked_shl`]
2026#[rustc_intrinsic_const_stable_indirect]
2027#[rustc_nounwind]
2028#[rustc_intrinsic]
2029pub const unsafe fn unchecked_shl<T: Copy, U: Copy>(x: T, y: U) -> T;
2030/// Performs an unchecked right shift, resulting in undefined behavior when
2031/// `y < 0` or `y >= N`, where N is the width of T in bits.
2032///
2033/// Safe wrappers for this intrinsic are available on the integer
2034/// primitives via the `checked_shr` method. For example,
2035/// [`u32::checked_shr`]
2036#[rustc_intrinsic_const_stable_indirect]
2037#[rustc_nounwind]
2038#[rustc_intrinsic]
2039pub const unsafe fn unchecked_shr<T: Copy, U: Copy>(x: T, y: U) -> T;
2040
2041/// Returns the result of an unchecked addition, resulting in
2042/// undefined behavior when `x + y > T::MAX` or `x + y < T::MIN`.
2043///
2044/// The stable counterpart of this intrinsic is `unchecked_add` on the various
2045/// integer types, such as [`u16::unchecked_add`] and [`i64::unchecked_add`].
2046#[rustc_intrinsic_const_stable_indirect]
2047#[rustc_nounwind]
2048#[rustc_intrinsic]
2049pub const unsafe fn unchecked_add<T: Copy>(x: T, y: T) -> T;
2050
2051/// Returns the result of an unchecked subtraction, resulting in
2052/// undefined behavior when `x - y > T::MAX` or `x - y < T::MIN`.
2053///
2054/// The stable counterpart of this intrinsic is `unchecked_sub` on the various
2055/// integer types, such as [`u16::unchecked_sub`] and [`i64::unchecked_sub`].
2056#[rustc_intrinsic_const_stable_indirect]
2057#[rustc_nounwind]
2058#[rustc_intrinsic]
2059pub const unsafe fn unchecked_sub<T: Copy>(x: T, y: T) -> T;
2060
2061/// Returns the result of an unchecked multiplication, resulting in
2062/// undefined behavior when `x * y > T::MAX` or `x * y < T::MIN`.
2063///
2064/// The stable counterpart of this intrinsic is `unchecked_mul` on the various
2065/// integer types, such as [`u16::unchecked_mul`] and [`i64::unchecked_mul`].
2066#[rustc_intrinsic_const_stable_indirect]
2067#[rustc_nounwind]
2068#[rustc_intrinsic]
2069pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
2070
2071/// Performs rotate left.
2072///
2073/// Note that, unlike most intrinsics, this is safe to call;
2074/// it does not require an `unsafe` block.
2075/// Therefore, implementations must not require the user to uphold
2076/// any safety invariants.
2077///
2078/// The stabilized versions of this intrinsic are available on the integer
2079/// primitives via the `rotate_left` method. For example,
2080/// [`u32::rotate_left`]
2081#[rustc_intrinsic_const_stable_indirect]
2082#[rustc_nounwind]
2083#[rustc_intrinsic]
2084#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2085#[miri::intrinsic_fallback_is_spec]
2086pub const fn rotate_left<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
2087 // Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2088 // SAFETY: we modulo `shift` so that the result is definitely less than the size of
2089 // `T` in bits.
2090 unsafe { unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>() as u32 * 8)) }
2091}
2092
2093/// Performs rotate right.
2094///
2095/// Note that, unlike most intrinsics, this is safe to call;
2096/// it does not require an `unsafe` block.
2097/// Therefore, implementations must not require the user to uphold
2098/// any safety invariants.
2099///
2100/// The stabilized versions of this intrinsic are available on the integer
2101/// primitives via the `rotate_right` method. For example,
2102/// [`u32::rotate_right`]
2103#[rustc_intrinsic_const_stable_indirect]
2104#[rustc_nounwind]
2105#[rustc_intrinsic]
2106#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2107#[miri::intrinsic_fallback_is_spec]
2108pub const fn rotate_right<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
2109 // Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2110 // SAFETY: we modulo `shift` so that the result is definitely less than the size of
2111 // `T` in bits.
2112 unsafe { unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>() as u32 * 8)) }
2113}
2114
2115/// Wrapping (modular) addition. Computes `a + b`,
2116/// wrapping around at the boundary of the type.
2117///
2118/// Note that, unlike most intrinsics, this is safe to call;
2119/// it does not require an `unsafe` block.
2120/// Therefore, implementations must not require the user to uphold
2121/// any safety invariants.
2122///
2123/// The stabilized versions of this intrinsic are available on the integer
2124/// primitives via the `wrapping_add` method. For example,
2125/// [`u32::wrapping_add`]
2126#[rustc_intrinsic_const_stable_indirect]
2127#[rustc_nounwind]
2128#[rustc_intrinsic]
2129pub const fn wrapping_add<T: Copy>(a: T, b: T) -> T;
2130/// Wrapping (modular) subtraction. Computes `a - b`,
2131/// wrapping around at the boundary of the type.
2132///
2133/// Note that, unlike most intrinsics, this is safe to call;
2134/// it does not require an `unsafe` block.
2135/// Therefore, implementations must not require the user to uphold
2136/// any safety invariants.
2137///
2138/// The stabilized versions of this intrinsic are available on the integer
2139/// primitives via the `wrapping_sub` method. For example,
2140/// [`u32::wrapping_sub`]
2141#[rustc_intrinsic_const_stable_indirect]
2142#[rustc_nounwind]
2143#[rustc_intrinsic]
2144pub const fn wrapping_sub<T: Copy>(a: T, b: T) -> T;
2145/// Wrapping (modular) multiplication. Computes `a *
2146/// b`, wrapping around at the boundary of the type.
2147///
2148/// Note that, unlike most intrinsics, this is safe to call;
2149/// it does not require an `unsafe` block.
2150/// Therefore, implementations must not require the user to uphold
2151/// any safety invariants.
2152///
2153/// The stabilized versions of this intrinsic are available on the integer
2154/// primitives via the `wrapping_mul` method. For example,
2155/// [`u32::wrapping_mul`]
2156#[rustc_intrinsic_const_stable_indirect]
2157#[rustc_nounwind]
2158#[rustc_intrinsic]
2159pub const fn wrapping_mul<T: Copy>(a: T, b: T) -> T;
2160
2161/// Computes `a + b`, saturating at numeric bounds.
2162///
2163/// Note that, unlike most intrinsics, this is safe to call;
2164/// it does not require an `unsafe` block.
2165/// Therefore, implementations must not require the user to uphold
2166/// any safety invariants.
2167///
2168/// The stabilized versions of this intrinsic are available on the integer
2169/// primitives via the `saturating_add` method. For example,
2170/// [`u32::saturating_add`]
2171#[rustc_intrinsic_const_stable_indirect]
2172#[rustc_nounwind]
2173#[rustc_intrinsic]
2174pub const fn saturating_add<T: Copy>(a: T, b: T) -> T;
2175/// Computes `a - b`, saturating at numeric bounds.
2176///
2177/// Note that, unlike most intrinsics, this is safe to call;
2178/// it does not require an `unsafe` block.
2179/// Therefore, implementations must not require the user to uphold
2180/// any safety invariants.
2181///
2182/// The stabilized versions of this intrinsic are available on the integer
2183/// primitives via the `saturating_sub` method. For example,
2184/// [`u32::saturating_sub`]
2185#[rustc_intrinsic_const_stable_indirect]
2186#[rustc_nounwind]
2187#[rustc_intrinsic]
2188pub const fn saturating_sub<T: Copy>(a: T, b: T) -> T;
2189
2190/// Funnel Shift left.
2191///
2192/// Concatenates `a` and `b` (with `a` in the most significant half),
2193/// creating an integer twice as wide. Then shift this integer left
2194/// by `shift`), and extract the most significant half. If `a` and `b`
2195/// are the same, this is equivalent to a rotate left operation.
2196///
2197/// It is undefined behavior if `shift` is greater than or equal to the
2198/// bit size of `T`.
2199///
2200/// Safe versions of this intrinsic are available on the integer primitives
2201/// via the `funnel_shl` method. For example, [`u32::funnel_shl`].
2202#[rustc_intrinsic]
2203#[rustc_nounwind]
2204#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
2205#[unstable(feature = "funnel_shifts", issue = "145686")]
2206#[track_caller]
2207#[miri::intrinsic_fallback_is_spec]
2208pub const unsafe fn unchecked_funnel_shl<T: [const] fallback::FunnelShift>(
2209 a: T,
2210 b: T,
2211 shift: u32,
2212) -> T {
2213 // SAFETY: caller ensures that `shift` is in-range
2214 unsafe { a.unchecked_funnel_shl(b, shift) }
2215}
2216
2217/// Funnel Shift right.
2218///
2219/// Concatenates `a` and `b` (with `a` in the most significant half),
2220/// creating an integer twice as wide. Then shift this integer right
2221/// by `shift` (taken modulo the bit size of `T`), and extract the
2222/// least significant half. If `a` and `b` are the same, this is equivalent
2223/// to a rotate right operation.
2224///
2225/// It is undefined behavior if `shift` is greater than or equal to the
2226/// bit size of `T`.
2227///
2228/// Safer versions of this intrinsic are available on the integer primitives
2229/// via the `funnel_shr` method. For example, [`u32::funnel_shr`]
2230#[rustc_intrinsic]
2231#[rustc_nounwind]
2232#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
2233#[unstable(feature = "funnel_shifts", issue = "145686")]
2234#[track_caller]
2235#[miri::intrinsic_fallback_is_spec]
2236pub const unsafe fn unchecked_funnel_shr<T: [const] fallback::FunnelShift>(
2237 a: T,
2238 b: T,
2239 shift: u32,
2240) -> T {
2241 // SAFETY: caller ensures that `shift` is in-range
2242 unsafe { a.unchecked_funnel_shr(b, shift) }
2243}
2244
2245/// Carryless multiply.
2246///
2247/// Safe versions of this intrinsic are available on the integer primitives
2248/// via the `carryless_mul` method. For example, [`u32::carryless_mul`].
2249#[rustc_intrinsic]
2250#[rustc_nounwind]
2251#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
2252#[unstable(feature = "uint_carryless_mul", issue = "152080")]
2253#[miri::intrinsic_fallback_is_spec]
2254pub const fn carryless_mul<T: [const] fallback::CarrylessMul>(a: T, b: T) -> T {
2255 a.carryless_mul(b)
2256}
2257
2258/// This is an implementation detail of [`crate::ptr::read`] and should
2259/// not be used anywhere else. See its comments for why this exists.
2260///
2261/// This intrinsic can *only* be called where the pointer is a local without
2262/// projections (`read_via_copy(ptr)`, not `read_via_copy(*ptr)`) so that it
2263/// trivially obeys runtime-MIR rules about derefs in operands.
2264#[rustc_intrinsic_const_stable_indirect]
2265#[rustc_nounwind]
2266#[rustc_intrinsic]
2267pub const unsafe fn read_via_copy<T>(ptr: *const T) -> T;
2268
2269/// This is an implementation detail of [`crate::ptr::write`] and should
2270/// not be used anywhere else. See its comments for why this exists.
2271///
2272/// This intrinsic can *only* be called where the pointer is a local without
2273/// projections (`write_via_move(ptr, x)`, not `write_via_move(*ptr, x)`) so
2274/// that it trivially obeys runtime-MIR rules about derefs in operands.
2275#[rustc_intrinsic_const_stable_indirect]
2276#[rustc_nounwind]
2277#[rustc_intrinsic]
2278pub const unsafe fn write_via_move<T>(ptr: *mut T, value: T);
2279
2280/// Returns the value of the discriminant for the variant in 'v';
2281/// if `T` has no discriminant, returns `0`.
2282///
2283/// Note that, unlike most intrinsics, this is safe to call;
2284/// it does not require an `unsafe` block.
2285/// Therefore, implementations must not require the user to uphold
2286/// any safety invariants.
2287///
2288/// The stabilized version of this intrinsic is [`core::mem::discriminant`].
2289#[rustc_intrinsic_const_stable_indirect]
2290#[rustc_nounwind]
2291#[rustc_intrinsic]
2292pub const fn discriminant_value<T>(v: &T) -> <T as DiscriminantKind>::Discriminant;
2293
2294/// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the
2295/// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs.
2296/// Returns `true` if unwinding occurred and `catch_fn` was called; returns `false` otherwise.
2297///
2298/// `catch_fn` must not unwind.
2299///
2300/// The third argument is a function called if an unwind occurs (both Rust `panic` and foreign
2301/// unwinds). This function takes the data pointer and a pointer to the target- and
2302/// runtime-specific exception object that was caught.
2303///
2304/// Note that in the case of a foreign unwinding operation, the exception object data may not be
2305/// safely usable from Rust, and should not be directly exposed via the standard library. To
2306/// prevent unsafe access, the library implementation may either abort the process or present an
2307/// opaque error type to the user.
2308///
2309/// For more information, see the compiler's source, as well as the documentation for the stable
2310/// version of this intrinsic, `std::panic::catch_unwind`.
2311#[rustc_intrinsic]
2312#[rustc_nounwind]
2313pub unsafe fn catch_unwind<Data: ptr::Thin>(
2314 _try_fn: unsafe fn(*mut Data),
2315 _data: *mut Data,
2316 _catch_fn: unsafe fn(*mut Data, *mut u8),
2317) -> bool;
2318
2319/// Emits a `nontemporal` store, which gives a hint to the CPU that the data should not be held
2320/// in cache. Except for performance, this is fully equivalent to `ptr.write(val)`.
2321///
2322/// Not all architectures provide such an operation. For instance, x86 does not: while `MOVNT`
2323/// exists, that operation is *not* equivalent to `ptr.write(val)` (`MOVNT` writes can be reordered
2324/// in ways that are not allowed for regular writes).
2325#[rustc_intrinsic]
2326#[rustc_nounwind]
2327pub unsafe fn nontemporal_store<T>(ptr: *mut T, val: T);
2328
2329/// See documentation of `<*const T>::offset_from` for details.
2330#[rustc_intrinsic_const_stable_indirect]
2331#[rustc_nounwind]
2332#[rustc_intrinsic]
2333pub const unsafe fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
2334
2335/// See documentation of `<*const T>::offset_from_unsigned` for details.
2336#[rustc_nounwind]
2337#[rustc_intrinsic]
2338#[rustc_intrinsic_const_stable_indirect]
2339pub const unsafe fn ptr_offset_from_unsigned<T>(ptr: *const T, base: *const T) -> usize;
2340
2341/// See documentation of `<*const T>::guaranteed_eq` for details.
2342/// Returns `2` if the result is unknown.
2343/// Returns `1` if the pointers are guaranteed equal.
2344/// Returns `0` if the pointers are guaranteed inequal.
2345#[rustc_intrinsic]
2346#[rustc_nounwind]
2347#[rustc_do_not_const_check]
2348#[inline]
2349#[miri::intrinsic_fallback_is_spec]
2350pub const fn ptr_guaranteed_cmp<T>(ptr: *const T, other: *const T) -> u8 {
2351 (ptr == other) as u8
2352}
2353
2354/// Determines whether the raw bytes of the two values are equal.
2355///
2356/// This is particularly handy for arrays, since it allows things like just
2357/// comparing `i96`s instead of forcing `alloca`s for `[6 x i16]`.
2358///
2359/// Above some backend-decided threshold this will emit calls to `memcmp`,
2360/// like slice equality does, instead of causing massive code size.
2361///
2362/// Since this works by comparing the underlying bytes, the actual `T` is
2363/// not particularly important. It will be used for its size and alignment,
2364/// but any validity restrictions will be ignored, not enforced.
2365///
2366/// # Safety
2367///
2368/// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized.
2369/// Note that this is a stricter criterion than just the *values* being
2370/// fully-initialized: if `T` has padding, it's UB to call this intrinsic.
2371///
2372/// At compile-time, it is furthermore UB to call this if any of the bytes
2373/// in `*a` or `*b` have provenance.
2374///
2375/// (The implementation is allowed to branch on the results of comparisons,
2376/// which is UB if any of their inputs are `undef`.)
2377#[rustc_nounwind]
2378#[rustc_intrinsic]
2379pub const unsafe fn raw_eq<T>(a: &T, b: &T) -> bool;
2380
2381/// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)`
2382/// as unsigned bytes, returning negative if `left` is less, zero if all the
2383/// bytes match, or positive if `left` is greater.
2384///
2385/// This underlies things like `<[u8]>::cmp`, and will usually lower to `memcmp`.
2386///
2387/// # Safety
2388///
2389/// `left` and `right` must each be [valid] for reads of `bytes` bytes.
2390///
2391/// Note that this applies to the whole range, not just until the first byte
2392/// that differs. That allows optimizations that can read in large chunks.
2393///
2394/// [valid]: crate::ptr#safety
2395#[rustc_nounwind]
2396#[rustc_intrinsic]
2397#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
2398pub const unsafe fn compare_bytes(left: *const u8, right: *const u8, bytes: usize) -> i32;
2399
2400/// See documentation of [`std::hint::black_box`] for details.
2401///
2402/// [`std::hint::black_box`]: crate::hint::black_box
2403#[rustc_nounwind]
2404#[rustc_intrinsic]
2405#[rustc_intrinsic_const_stable_indirect]
2406pub const fn black_box<T>(dummy: T) -> T;
2407
2408/// Selects which function to call depending on the context.
2409///
2410/// If this function is evaluated at compile-time, then a call to this
2411/// intrinsic will be replaced with a call to `called_in_const`. It gets
2412/// replaced with a call to `called_at_rt` otherwise.
2413///
2414/// This function is safe to call, but note the stability concerns below.
2415///
2416/// # Type Requirements
2417///
2418/// The two functions must be both function items. They cannot be function
2419/// pointers or closures. The first function must be a `const fn`.
2420///
2421/// `arg` will be the tupled arguments that will be passed to either one of
2422/// the two functions, therefore, both functions must accept the same type of
2423/// arguments. Both functions must return RET.
2424///
2425/// # Stability concerns
2426///
2427/// Rust has not yet decided that `const fn` are allowed to tell whether
2428/// they run at compile-time or at runtime. Therefore, when using this
2429/// intrinsic anywhere that can be reached from stable, it is crucial that
2430/// the end-to-end behavior of the stable `const fn` is the same for both
2431/// modes of execution. (Here, Undefined Behavior is considered "the same"
2432/// as any other behavior, so if the function exhibits UB at runtime then
2433/// it may do whatever it wants at compile-time.)
2434///
2435/// Here is an example of how this could cause a problem:
2436/// ```no_run
2437/// #![feature(const_eval_select)]
2438/// #![feature(core_intrinsics)]
2439/// # #![allow(internal_features)]
2440/// use std::intrinsics::const_eval_select;
2441///
2442/// // Standard library
2443/// pub const fn inconsistent() -> i32 {
2444/// fn runtime() -> i32 { 1 }
2445/// const fn compiletime() -> i32 { 2 }
2446///
2447/// // ⚠ This code violates the required equivalence of `compiletime`
2448/// // and `runtime`.
2449/// const_eval_select((), compiletime, runtime)
2450/// }
2451///
2452/// // User Crate
2453/// const X: i32 = inconsistent();
2454/// let x = inconsistent();
2455/// assert_eq!(x, X);
2456/// ```
2457///
2458/// Currently such an assertion would always succeed; until Rust decides
2459/// otherwise, that principle should not be violated.
2460#[rustc_const_unstable(feature = "const_eval_select", issue = "124625")]
2461#[rustc_intrinsic]
2462pub const fn const_eval_select<ARG: Tuple, F, G, RET>(
2463 _arg: ARG,
2464 _called_in_const: F,
2465 _called_at_rt: G,
2466) -> RET
2467where
2468 G: FnOnce<ARG, Output = RET>,
2469 F: const FnOnce<ARG, Output = RET>;
2470
2471/// A macro to make it easier to invoke const_eval_select. Use as follows:
2472/// ```rust,ignore (just a macro example)
2473/// const_eval_select!(
2474/// @capture { arg1: i32 = some_expr, arg2: T = other_expr } -> U:
2475/// if const #[attributes_for_const_arm] {
2476/// // Compile-time code goes here.
2477/// } else #[attributes_for_runtime_arm] {
2478/// // Run-time code goes here.
2479/// }
2480/// )
2481/// ```
2482/// The `@capture` block declares which surrounding variables / expressions can be
2483/// used inside the `if const`.
2484/// Note that the two arms of this `if` really each become their own function, which is why the
2485/// macro supports setting attributes for those functions. Both functions are marked as `#[inline]`.
2486///
2487/// See [`const_eval_select()`] for the rules and requirements around that intrinsic.
2488pub(crate) macro const_eval_select {
2489 (
2490 @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty = $val:expr),* $(,)? } $( -> $ret:ty )? :
2491 if const
2492 $(#[$compiletime_attr:meta])* $compiletime:block
2493 else
2494 $(#[$runtime_attr:meta])* $runtime:block
2495 ) => {{
2496 #[inline]
2497 $(#[$runtime_attr])*
2498 fn runtime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2499 $runtime
2500 }
2501
2502 #[inline]
2503 $(#[$compiletime_attr])*
2504 const fn compiletime$(<$($binders)*>)?($($arg: $ty),*) $( -> $ret )? {
2505 // Don't warn if one of the arguments is unused.
2506 $(let _ = $arg;)*
2507
2508 $compiletime
2509 }
2510
2511 const_eval_select(($($val,)*), compiletime, runtime)
2512 }},
2513 // We support leaving away the `val` expressions for *all* arguments
2514 // (but not for *some* arguments, that's too tricky).
2515 (
2516 @capture$([$($binders:tt)*])? { $($arg:ident : $ty:ty),* $(,)? } $( -> $ret:ty )? :
2517 if const
2518 $(#[$compiletime_attr:meta])* $compiletime:block
2519 else
2520 $(#[$runtime_attr:meta])* $runtime:block
2521 ) => {
2522 $crate::intrinsics::const_eval_select!(
2523 @capture$([$($binders)*])? { $($arg : $ty = $arg),* } $(-> $ret)? :
2524 if const
2525 $(#[$compiletime_attr])* $compiletime
2526 else
2527 $(#[$runtime_attr])* $runtime
2528 )
2529 },
2530}
2531
2532/// Returns whether the argument's value is statically known at
2533/// compile-time.
2534///
2535/// This is useful when there is a way of writing the code that will
2536/// be *faster* when some variables have known values, but *slower*
2537/// in the general case: an `if is_val_statically_known(var)` can be used
2538/// to select between these two variants. The `if` will be optimized away
2539/// and only the desired branch remains.
2540///
2541/// Formally speaking, this function non-deterministically returns `true`
2542/// or `false`, and the caller has to ensure sound behavior for both cases.
2543/// In other words, the following code has *Undefined Behavior*:
2544///
2545/// ```no_run
2546/// #![feature(core_intrinsics)]
2547/// # #![allow(internal_features)]
2548/// use std::hint::unreachable_unchecked;
2549/// use std::intrinsics::is_val_statically_known;
2550///
2551/// if !is_val_statically_known(0) { unsafe { unreachable_unchecked(); } }
2552/// ```
2553///
2554/// This also means that the following code's behavior is unspecified; it
2555/// may panic, or it may not:
2556///
2557/// ```no_run
2558/// #![feature(core_intrinsics)]
2559/// # #![allow(internal_features)]
2560/// use std::intrinsics::is_val_statically_known;
2561///
2562/// assert_eq!(is_val_statically_known(0), is_val_statically_known(0));
2563/// ```
2564///
2565/// Unsafe code may not rely on `is_val_statically_known` returning any
2566/// particular value, ever. However, the compiler will generally make it
2567/// return `true` only if the value of the argument is actually known.
2568///
2569/// # Type Requirements
2570///
2571/// `T` must be either a `bool`, a `char`, a primitive numeric type (e.g. `f32`,
2572/// but not `NonZeroISize`), or any thin pointer (e.g. `*mut String`).
2573/// Any other argument types *may* cause a compiler error.
2574///
2575/// ## Pointers
2576///
2577/// When the input is a pointer, only the pointer itself is
2578/// ever considered. The pointee has no effect. Currently, these functions
2579/// behave identically:
2580///
2581/// ```
2582/// #![feature(core_intrinsics)]
2583/// # #![allow(internal_features)]
2584/// use std::intrinsics::is_val_statically_known;
2585///
2586/// fn foo(x: &i32) -> bool {
2587/// is_val_statically_known(x)
2588/// }
2589///
2590/// fn bar(x: &i32) -> bool {
2591/// is_val_statically_known(
2592/// (x as *const i32).addr()
2593/// )
2594/// }
2595/// # _ = foo(&5_i32);
2596/// # _ = bar(&5_i32);
2597/// ```
2598#[rustc_const_stable_indirect]
2599#[rustc_nounwind]
2600#[unstable(feature = "core_intrinsics", issue = "none")]
2601#[rustc_intrinsic]
2602pub const fn is_val_statically_known<T: Copy>(_arg: T) -> bool {
2603 false
2604}
2605
2606/// Non-overlapping *typed* swap of a single value.
2607///
2608/// The codegen backends will replace this with a better implementation when
2609/// `T` is a simple type that can be loaded and stored as an immediate.
2610///
2611/// The stabilized form of this intrinsic is [`crate::mem::swap`].
2612///
2613/// # Safety
2614/// Behavior is undefined if any of the following conditions are violated:
2615///
2616/// * Both `x` and `y` must be [valid] for both reads and writes.
2617///
2618/// * Both `x` and `y` must be properly aligned.
2619///
2620/// * The region of memory beginning at `x` must *not* overlap with the region of memory
2621/// beginning at `y`.
2622///
2623/// * The memory pointed by `x` and `y` must both contain values of type `T`.
2624///
2625/// [valid]: crate::ptr#safety
2626#[rustc_nounwind]
2627#[inline]
2628#[rustc_intrinsic]
2629#[rustc_intrinsic_const_stable_indirect]
2630pub const unsafe fn typed_swap_nonoverlapping<T>(x: *mut T, y: *mut T) {
2631 // SAFETY: The caller provided single non-overlapping items behind
2632 // pointers, so swapping them with `count: 1` is fine.
2633 unsafe { ptr::swap_nonoverlapping(x, y, 1) };
2634}
2635
2636/// Returns whether we should perform some UB-checking at runtime. This eventually evaluates to
2637/// `cfg!(ub_checks)`, but behaves different from `cfg!` when mixing crates built with different
2638/// flags: if the crate has UB checks enabled or carries the `#[rustc_preserve_ub_checks]`
2639/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2640/// a crate that does not delay evaluation further); otherwise it can happen any time.
2641///
2642/// The common case here is a user program built with ub_checks linked against the distributed
2643/// sysroot which is built without ub_checks but with `#[rustc_preserve_ub_checks]`.
2644/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2645/// `#[inline]`), gating assertions on `ub_checks()` rather than `cfg!(ub_checks)` means that
2646/// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the
2647/// user has UB checks disabled, the checks will still get optimized out. This intrinsic is
2648/// primarily used by [`crate::ub_checks::assert_unsafe_precondition`].
2649///
2650/// # Consteval
2651///
2652/// In consteval, this function currently returns `true`. This is because the value of the `ub_checks`
2653/// configuration can differ across crates, but we need this function to always return the same
2654/// value in consteval in order to avoid unsoundness.
2655#[rustc_intrinsic_const_stable_indirect] // just for UB checks
2656#[inline(always)]
2657#[rustc_intrinsic]
2658pub const fn ub_checks() -> bool {
2659 cfg!(ub_checks)
2660}
2661
2662/// Returns whether we should perform some overflow-checking at runtime. This eventually evaluates to
2663/// `cfg!(overflow_checks)`, but behaves different from `cfg!` when mixing crates built with different
2664/// flags: if the crate has overflow checks enabled or carries the `#[rustc_inherit_overflow_checks]`
2665/// attribute, evaluation is delayed until monomorphization (or until the call gets inlined into
2666/// a crate that does not delay evaluation further); otherwise it can happen any time.
2667///
2668/// The common case here is a user program built with overflow_checks linked against the distributed
2669/// sysroot which is built without overflow_checks but with `#[rustc_inherit_overflow_checks]`.
2670/// For code that gets monomorphized in the user crate (i.e., generic functions and functions with
2671/// `#[inline]`), gating assertions on `overflow_checks()` rather than `cfg!(overflow_checks)` means that
2672/// assertions are enabled whenever the *user crate* has overflow checks enabled. However if the
2673/// user has overflow checks disabled, the checks will still get optimized out.
2674///
2675/// # Consteval
2676///
2677/// In consteval, this function currently returns `true`. This is because the value of the `overflow_checks`
2678/// configuration can differ across crates, but we need this function to always return the same
2679/// value in consteval in order to avoid unsoundness.
2680#[inline(always)]
2681#[rustc_intrinsic]
2682pub const fn overflow_checks() -> bool {
2683 cfg!(debug_assertions)
2684}
2685
2686/// Allocates a block of memory at compile time.
2687/// At runtime, just returns a null pointer.
2688///
2689/// # Safety
2690///
2691/// - The `align` argument must be a power of two.
2692/// - At compile time, a compile error occurs if this constraint is violated.
2693/// - At runtime, it is not checked.
2694#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2695#[rustc_nounwind]
2696#[rustc_intrinsic]
2697#[miri::intrinsic_fallback_is_spec]
2698pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 {
2699 // const eval overrides this function, but runtime code for now just returns null pointers.
2700 // See <https://github.com/rust-lang/rust/issues/93935>.
2701 crate::ptr::null_mut()
2702}
2703
2704/// Deallocates a memory which allocated by `intrinsics::const_allocate` at compile time.
2705/// At runtime, it does nothing.
2706///
2707/// # Safety
2708///
2709/// - The `align` argument must be a power of two.
2710/// - At compile time, a compile error occurs if this constraint is violated.
2711/// - At runtime, it is not checked.
2712/// - If the `ptr` is created in an another const, this intrinsic doesn't deallocate it.
2713/// - If the `ptr` is pointing to a local variable, this intrinsic doesn't deallocate it.
2714#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2715#[unstable(feature = "core_intrinsics", issue = "none")]
2716#[rustc_nounwind]
2717#[rustc_intrinsic]
2718#[miri::intrinsic_fallback_is_spec]
2719pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {
2720 // Runtime NOP
2721}
2722
2723/// Convert the allocation this pointer points to into immutable global memory.
2724/// The pointer must point to the beginning of a heap allocation.
2725/// This operation only makes sense during compile time. At runtime, it does nothing.
2726#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2727#[rustc_nounwind]
2728#[rustc_intrinsic]
2729#[miri::intrinsic_fallback_is_spec]
2730pub const unsafe fn const_make_global(ptr: *mut u8) -> *const u8 {
2731 // const eval overrides this function; at runtime, it is a NOP.
2732 ptr
2733}
2734
2735/// Check if the pre-condition `cond` has been met.
2736///
2737/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2738/// returns false.
2739///
2740/// Note that this function is a no-op during constant evaluation.
2741#[unstable(feature = "contracts_internals", issue = "128044")]
2742// Calls to this function get inserted by an AST expansion pass, which uses the equivalent of
2743// `#[allow_internal_unstable]` to allow using `contracts_internals` functions. Const-checking
2744// doesn't honor `#[allow_internal_unstable]`, so for the const feature gate we use the user-facing
2745// `contracts` feature rather than the perma-unstable `contracts_internals`
2746#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2747#[lang = "contract_check_requires"]
2748#[rustc_intrinsic]
2749pub const fn contract_check_requires<C: Fn() -> bool + Copy>(cond: C) {
2750 const_eval_select!(
2751 @capture[C: Fn() -> bool + Copy] { cond: C } :
2752 if const {
2753 // Do nothing
2754 } else {
2755 if !cond() {
2756 // Emit no unwind panic in case this was a safety requirement.
2757 crate::panicking::panic_nounwind("failed requires check");
2758 }
2759 }
2760 )
2761}
2762
2763/// Check if the post-condition `cond` has been met.
2764///
2765/// By default, if `contract_checks` is enabled, this will panic with no unwind if the condition
2766/// returns false.
2767///
2768/// If `cond` is `None`, then no postcondition checking is performed.
2769///
2770/// Note that this function is a no-op during constant evaluation.
2771#[unstable(feature = "contracts_internals", issue = "128044")]
2772// Similar to `contract_check_requires`, we need to use the user-facing
2773// `contracts` feature rather than the perma-unstable `contracts_internals`.
2774// Const-checking doesn't honor allow_internal_unstable logic used by contract expansion.
2775#[rustc_const_unstable(feature = "contracts", issue = "128044")]
2776#[lang = "contract_check_ensures"]
2777#[rustc_intrinsic]
2778pub const fn contract_check_ensures<C: Fn(&Ret) -> bool + Copy, Ret>(
2779 cond: Option<C>,
2780 ret: Ret,
2781) -> Ret {
2782 const_eval_select!(
2783 @capture[C: Fn(&Ret) -> bool + Copy, Ret] { cond: Option<C>, ret: Ret } -> Ret :
2784 if const {
2785 // Do nothing
2786 ret
2787 } else {
2788 if let crate::option::Option::Some(cond) = cond && !cond(&ret) {
2789 // Emit no unwind panic in case this was a safety requirement.
2790 crate::panicking::panic_nounwind("failed ensures check");
2791 }
2792 ret
2793 }
2794 )
2795}
2796
2797/// The intrinsic will return the size stored in that vtable.
2798///
2799/// # Safety
2800///
2801/// `ptr` must point to a vtable.
2802#[rustc_nounwind]
2803#[unstable(feature = "core_intrinsics", issue = "none")]
2804#[rustc_intrinsic]
2805pub unsafe fn vtable_size(ptr: *const ()) -> usize;
2806
2807/// The intrinsic will return the alignment stored in that vtable.
2808///
2809/// # Safety
2810///
2811/// `ptr` must point to a vtable.
2812#[rustc_nounwind]
2813#[unstable(feature = "core_intrinsics", issue = "none")]
2814#[rustc_intrinsic]
2815pub unsafe fn vtable_align(ptr: *const ()) -> usize;
2816
2817/// The size of a type in bytes.
2818///
2819/// Note that, unlike most intrinsics, this is safe to call;
2820/// it does not require an `unsafe` block.
2821/// Therefore, implementations must not require the user to uphold
2822/// any safety invariants.
2823///
2824/// More specifically, this is the offset in bytes between successive
2825/// items of the same type, including alignment padding.
2826///
2827/// Note that, unlike most intrinsics, this can only be called at compile-time
2828/// as backends do not have an implementation for it. The only caller (its
2829/// stable counterpart) wraps this intrinsic call in a `const` block so that
2830/// backends only see an evaluated constant.
2831///
2832/// The stabilized version of this intrinsic is [`core::mem::size_of`].
2833#[rustc_nounwind]
2834#[unstable(feature = "core_intrinsics", issue = "none")]
2835#[rustc_intrinsic_const_stable_indirect]
2836#[rustc_intrinsic]
2837#[rustc_comptime]
2838pub fn size_of<T>() -> usize;
2839
2840/// The minimum alignment of a type.
2841///
2842/// Note that, unlike most intrinsics, this is safe to call;
2843/// it does not require an `unsafe` block.
2844/// Therefore, implementations must not require the user to uphold
2845/// any safety invariants.
2846///
2847/// Note that, unlike most intrinsics, this can only be called at compile-time
2848/// as backends do not have an implementation for it. The only caller (its
2849/// stable counterpart) wraps this intrinsic call in a `const` block so that
2850/// backends only see an evaluated constant.
2851///
2852/// The stabilized version of this intrinsic is [`core::mem::align_of`].
2853#[rustc_nounwind]
2854#[unstable(feature = "core_intrinsics", issue = "none")]
2855#[rustc_intrinsic_const_stable_indirect]
2856#[rustc_intrinsic]
2857#[rustc_comptime]
2858pub fn align_of<T>() -> usize;
2859
2860/// The offset of a field inside a type.
2861///
2862/// Note that, unlike most intrinsics, this is safe to call;
2863/// it does not require an `unsafe` block.
2864/// Therefore, implementations must not require the user to uphold
2865/// any safety invariants.
2866///
2867/// This intrinsic can only be evaluated at compile-time, and should only appear in
2868/// constants or inline const blocks.
2869///
2870/// The stabilized version of this intrinsic is [`core::mem::offset_of`].
2871/// This intrinsic is also a lang item so `offset_of!` can desugar to calls to it.
2872#[rustc_nounwind]
2873#[unstable(feature = "core_intrinsics", issue = "none")]
2874#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")]
2875#[rustc_intrinsic_const_stable_indirect]
2876#[rustc_intrinsic]
2877#[lang = "offset_of"]
2878#[rustc_comptime]
2879pub fn offset_of<T: PointeeSized>(variant: u32, field: u32) -> usize;
2880
2881/// The offset of a field queried by its field representing type.
2882///
2883/// Returns the offset of the field represented by `F`. This function essentially does the same as
2884/// the [`offset_of`] intrinsic, but expects the field to be represented by a generic rather than
2885/// the variant and field indices. This also is a safe intrinsic and can only be evaluated at
2886/// compile-time, so it should only appear in constants or inline const blocks.
2887///
2888/// There should be no need to call this intrinsic manually, as its value is used to define
2889/// [`Field::OFFSET`](crate::field::Field::OFFSET), which is publicly accessible.
2890#[rustc_intrinsic]
2891#[unstable(feature = "field_projections", issue = "145383")]
2892#[rustc_const_unstable(feature = "field_projections", issue = "145383")]
2893#[rustc_comptime]
2894pub fn field_offset<F: crate::field::Field>() -> usize;
2895
2896/// Returns the number of variants of the type `T` cast to a `usize`;
2897/// if `T` has no variants, returns `0`. Uninhabited variants will be counted.
2898///
2899/// Note that, unlike most intrinsics, this can only be called at compile-time
2900/// as backends do not have an implementation for it. The only caller (its
2901/// stable counterpart) wraps this intrinsic call in a `const` block so that
2902/// backends only see an evaluated constant.
2903///
2904/// The to-be-stabilized version of this intrinsic is [`crate::mem::variant_count`].
2905#[rustc_nounwind]
2906#[unstable(feature = "core_intrinsics", issue = "none")]
2907#[rustc_intrinsic]
2908#[rustc_comptime]
2909pub fn variant_count<T>() -> usize;
2910
2911/// The size of the referenced value in bytes.
2912///
2913/// The stabilized version of this intrinsic is [`core::mem::size_of_val`].
2914///
2915/// # Safety
2916///
2917/// See [`crate::mem::size_of_val_raw`] for safety conditions.
2918#[rustc_nounwind]
2919#[unstable(feature = "core_intrinsics", issue = "none")]
2920#[rustc_intrinsic]
2921#[rustc_intrinsic_const_stable_indirect]
2922pub const unsafe fn size_of_val<T: ?Sized>(ptr: *const T) -> usize;
2923
2924/// The required alignment of the referenced value.
2925///
2926/// The stabilized version of this intrinsic is [`core::mem::align_of_val`].
2927///
2928/// # Safety
2929///
2930/// See [`crate::mem::align_of_val_raw`] for safety conditions.
2931#[rustc_nounwind]
2932#[unstable(feature = "core_intrinsics", issue = "none")]
2933#[rustc_intrinsic]
2934#[rustc_intrinsic_const_stable_indirect]
2935pub const unsafe fn align_of_val<T: ?Sized>(ptr: *const T) -> usize;
2936
2937#[rustc_intrinsic]
2938#[rustc_comptime]
2939#[unstable(feature = "core_intrinsics", issue = "none")]
2940/// Check if a type represented by a `TypeId` implements a trait represented by a `TypeId`.
2941/// It can only be called at compile time, the backends do
2942/// not implement it. If it implements the trait the dyn metadata gets returned for vtable access.
2943pub fn type_id_vtable(
2944 _id: crate::any::TypeId,
2945 _trait: crate::any::TypeId,
2946) -> Option<ptr::DynMetadata<*const ()>>;
2947
2948/// Compute the type information of a concrete type.
2949/// It can only be called at compile time, the backends do
2950/// not implement it.
2951#[rustc_intrinsic]
2952#[unstable(feature = "core_intrinsics", issue = "none")]
2953#[rustc_comptime]
2954pub fn type_of(_id: crate::any::TypeId) -> crate::mem::type_info::Type;
2955
2956/// Gets a static string slice containing the name of a type.
2957///
2958/// Note that, unlike most intrinsics, this can only be called at compile-time
2959/// as backends do not have an implementation for it. The only caller (its
2960/// stable counterpart) wraps this intrinsic call in a `const` block so that
2961/// backends only see an evaluated constant.
2962///
2963/// The stabilized version of this intrinsic is [`core::any::type_name`].
2964#[rustc_nounwind]
2965#[unstable(feature = "core_intrinsics", issue = "none")]
2966#[rustc_intrinsic]
2967#[rustc_comptime]
2968pub fn type_name<T: ?Sized>() -> &'static str;
2969
2970/// Gets an identifier which is globally unique to the specified type. This
2971/// function will return the same value for a type regardless of whichever
2972/// crate it is invoked in.
2973///
2974/// Note that, unlike most intrinsics, this can only be called at compile-time
2975/// as backends do not have an implementation for it. The only caller (its
2976/// stable counterpart) wraps this intrinsic call in a `const` block so that
2977/// backends only see an evaluated constant.
2978///
2979/// The stabilized version of this intrinsic is [`core::any::TypeId::of`].
2980#[rustc_nounwind]
2981#[unstable(feature = "core_intrinsics", issue = "none")]
2982#[rustc_intrinsic]
2983#[rustc_comptime]
2984pub fn type_id<T: ?Sized>() -> crate::any::TypeId;
2985
2986/// Tests (at compile-time) if two [`crate::any::TypeId`] instances identify the
2987/// same type. This is necessary because at const-eval time the actual discriminating
2988/// data is opaque and cannot be inspected directly.
2989///
2990/// The stabilized version of this intrinsic is the [PartialEq] impl for [`core::any::TypeId`].
2991#[rustc_nounwind]
2992#[unstable(feature = "core_intrinsics", issue = "none")]
2993#[rustc_intrinsic]
2994#[rustc_do_not_const_check]
2995pub const fn type_id_eq(a: crate::any::TypeId, b: crate::any::TypeId) -> bool {
2996 // SAFETY: we know `TypeId` is 16 bytes of initialized data.
2997 // This is runtime-only code so we do not have to worry about provenance.
2998 unsafe { crate::mem::transmute::<_, u128>(a) == crate::mem::transmute::<_, u128>(b) }
2999}
3000
3001/// Returns whether the type represented by this `TypeId` is a signed integer.
3002///
3003/// The more user-friendly version of this intrinsic is [`core::any::TypeId::is_signed`].
3004#[rustc_intrinsic]
3005#[unstable(feature = "core_intrinsics", issue = "none")]
3006#[rustc_comptime]
3007pub fn type_id_is_signed(_id: crate::any::TypeId) -> bool;
3008
3009/// Gets the size of the type represented by this `TypeId`.
3010///
3011/// The more user-friendly version of this intrinsic is [`core::any::TypeId::size`].
3012#[rustc_intrinsic]
3013#[unstable(feature = "core_intrinsics", issue = "none")]
3014#[rustc_comptime]
3015pub fn size_of_type_id(_id: crate::any::TypeId) -> Option<usize>;
3016
3017/// Gets the number of variants of the type represented by this `TypeId`.
3018///
3019/// The more user-friendly version of this intrinsic is [`core::any::TypeId::variants`].
3020#[rustc_intrinsic]
3021#[unstable(feature = "core_intrinsics", issue = "none")]
3022#[rustc_comptime]
3023pub fn type_id_variants(_id: crate::any::TypeId) -> usize;
3024
3025/// Gets the name of the variant represented by the base `TypeId` and variant_idx.
3026///
3027/// The more user-friendly version of this intrinsic is [`core::mem::type_info::VariantId::name`].
3028///
3029/// [`TypeId`]: crate::any::TypeId
3030#[rustc_intrinsic]
3031#[unstable(feature = "core_intrinsics", issue = "none")]
3032#[rustc_comptime]
3033pub fn variant_name(_base: crate::any::TypeId, _variant_index: usize) -> &'static str;
3034
3035/// Returns true when the variant represented by the base `TypeId` and variant_idx is non
3036/// exhaustive.
3037///
3038/// The more user-friendly version of this intrinsic is
3039/// [`core::mem::type_info::VariantId::non_exhaustive`].
3040///
3041/// [`TypeId`]: crate::any::TypeId
3042#[rustc_intrinsic]
3043#[unstable(feature = "core_intrinsics", issue = "none")]
3044#[rustc_comptime]
3045pub fn variant_non_exhaustive(base: crate::any::TypeId, variant: usize) -> bool;
3046
3047/// Gets the number of fields at the given `variant_index` represented by this `TypeId`.
3048///
3049/// The more user-friendly version of this intrinsic is [`core::any::TypeId::fields`].
3050#[rustc_intrinsic]
3051#[unstable(feature = "core_intrinsics", issue = "none")]
3052#[rustc_comptime]
3053pub fn type_id_fields(_id: crate::any::TypeId, _variant_index: usize) -> usize;
3054
3055/// Gets the [`FieldRepresentingType`]'s `TypeId` at the given index of the type represented by this `TypeId`.
3056///
3057/// The more user-friendly version of this intrinsic is [`core::any::TypeId::field`].
3058///
3059/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType
3060#[rustc_intrinsic]
3061#[unstable(feature = "core_intrinsics", issue = "none")]
3062#[rustc_comptime]
3063pub fn type_id_field_representing_type(
3064 _id: crate::any::TypeId,
3065 _variant_index: usize,
3066 _field_index: usize,
3067) -> crate::any::TypeId;
3068
3069/// Gets the actual field `TypeId` of the [`FieldRepresentingType`]'s `TypeId`.
3070///
3071/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::type_id`].
3072///
3073/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType
3074#[rustc_intrinsic]
3075#[unstable(feature = "core_intrinsics", issue = "none")]
3076#[rustc_comptime]
3077pub fn field_representing_type_actual_type_id(
3078 _frt_type_id: crate::any::TypeId,
3079) -> crate::any::TypeId;
3080
3081/// Gets the name of the field represented by the [`FieldRepresentingType`]'s `TypeId`.
3082///
3083/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::name`].
3084///
3085/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType
3086#[rustc_intrinsic]
3087#[unstable(feature = "core_intrinsics", issue = "none")]
3088#[rustc_comptime]
3089pub fn field_representing_type_name(_frt_type_id: crate::any::TypeId) -> &'static str;
3090
3091/// Gets the name of the field represented by the [`FieldRepresentingType`]'s `TypeId`.
3092///
3093/// The more user-friendly version of this intrinsic is [`core::mem::type_info::FieldId::name`].
3094///
3095/// [`FieldRepresentingType`]: crate::field::FieldRepresentingType
3096#[rustc_intrinsic]
3097#[unstable(feature = "core_intrinsics", issue = "none")]
3098#[rustc_comptime]
3099pub fn field_representing_type_offset(_frt_type_id: crate::any::TypeId) -> usize;
3100
3101/// Checks whether this type is non-exhaustive.
3102#[rustc_intrinsic]
3103#[unstable(feature = "core_intrinsics", issue = "none")]
3104#[rustc_comptime]
3105pub fn non_exhaustive(_id: crate::any::TypeId) -> bool;
3106
3107/// Returns the list of generic args on this type.
3108/// Only meaningful for Adts, closures, ... Everything else returns an empty slice.
3109#[rustc_intrinsic]
3110#[unstable(feature = "core_intrinsics", issue = "none")]
3111#[rustc_comptime]
3112pub fn type_id_generics(_id: crate::any::TypeId) -> &'static [crate::mem::type_info::Generic];
3113
3114/// Lowers in MIR to `Rvalue::Aggregate` with `AggregateKind::RawPtr`.
3115///
3116/// This is used to implement functions like `slice::from_raw_parts_mut` and
3117/// `ptr::from_raw_parts` in a way compatible with the compiler being able to
3118/// change the possible layouts of pointers.
3119#[rustc_nounwind]
3120#[unstable(feature = "core_intrinsics", issue = "none")]
3121#[rustc_intrinsic_const_stable_indirect]
3122#[rustc_intrinsic]
3123pub const fn aggregate_raw_ptr<P: bounds::BuiltinDeref, D, M>(data: D, meta: M) -> P
3124where
3125 <P as bounds::BuiltinDeref>::Pointee: ptr::Pointee<Metadata = M>;
3126
3127/// Lowers in MIR to `Rvalue::UnaryOp` with `UnOp::PtrMetadata`.
3128///
3129/// This is used to implement functions like `ptr::metadata`.
3130#[rustc_nounwind]
3131#[unstable(feature = "core_intrinsics", issue = "none")]
3132#[rustc_intrinsic_const_stable_indirect]
3133#[rustc_intrinsic]
3134pub const fn ptr_metadata<P: ptr::Pointee<Metadata = M> + PointeeSized, M>(ptr: *const P) -> M;
3135
3136/// This is an accidentally-stable alias to [`ptr::copy_nonoverlapping`]; use that instead.
3137// Note (intentionally not in the doc comment): `ptr::copy_nonoverlapping` adds some extra
3138// debug assertions; if you are writing compiler tests or code inside the standard library
3139// that wants to avoid those debug assertions, directly call this intrinsic instead.
3140#[stable(feature = "rust1", since = "1.0.0")]
3141#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
3142#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
3143#[rustc_nounwind]
3144#[rustc_intrinsic]
3145pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
3146
3147/// This is an accidentally-stable alias to [`ptr::copy`]; use that instead.
3148// Note (intentionally not in the doc comment): `ptr::copy` adds some extra
3149// debug assertions; if you are writing compiler tests or code inside the standard library
3150// that wants to avoid those debug assertions, directly call this intrinsic instead.
3151#[stable(feature = "rust1", since = "1.0.0")]
3152#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
3153#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
3154#[rustc_nounwind]
3155#[rustc_intrinsic]
3156pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize);
3157
3158/// This is an accidentally-stable alias to [`ptr::write_bytes`]; use that instead.
3159// Note (intentionally not in the doc comment): `ptr::write_bytes` adds some extra
3160// debug assertions; if you are writing compiler tests or code inside the standard library
3161// that wants to avoid those debug assertions, directly call this intrinsic instead.
3162#[stable(feature = "rust1", since = "1.0.0")]
3163#[rustc_allowed_through_unstable_modules = "import this function via `std::ptr` instead"]
3164#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
3165#[rustc_nounwind]
3166#[rustc_intrinsic]
3167pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
3168
3169/// Returns the minimum of two `f16` values, ignoring NaN.
3170///
3171/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3172/// zeros deterministically. In particular:
3173/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3174/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3175/// and `-0.0`), either input may be returned non-deterministically.
3176///
3177/// Note that, unlike most intrinsics, this is safe to call;
3178/// it does not require an `unsafe` block.
3179/// Therefore, implementations must not require the user to uphold
3180/// any safety invariants.
3181///
3182/// The stabilized version of this intrinsic is [`f16::min`].
3183#[rustc_nounwind]
3184#[rustc_intrinsic]
3185pub const fn minimum_number_nsz_f16(x: f16, y: f16) -> f16 {
3186 if x.is_nan() || y <= x {
3187 y
3188 } else {
3189 // Either y > x or y is a NaN.
3190 x
3191 }
3192}
3193
3194/// Returns the minimum of two `f32` values, ignoring NaN.
3195///
3196/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3197/// zeros deterministically. In particular:
3198/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3199/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3200/// and `-0.0`), either input may be returned non-deterministically.
3201///
3202/// Note that, unlike most intrinsics, this is safe to call;
3203/// it does not require an `unsafe` block.
3204/// Therefore, implementations must not require the user to uphold
3205/// any safety invariants.
3206///
3207/// The stabilized version of this intrinsic is [`f32::min`].
3208#[rustc_nounwind]
3209#[rustc_intrinsic_const_stable_indirect]
3210#[rustc_intrinsic]
3211pub const fn minimum_number_nsz_f32(x: f32, y: f32) -> f32 {
3212 if x.is_nan() || y <= x {
3213 y
3214 } else {
3215 // Either y > x or y is a NaN.
3216 x
3217 }
3218}
3219
3220/// Returns the minimum of two `f64` values, ignoring NaN.
3221///
3222/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3223/// zeros deterministically. In particular:
3224/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3225/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3226/// and `-0.0`), either input may be returned non-deterministically.
3227///
3228/// Note that, unlike most intrinsics, this is safe to call;
3229/// it does not require an `unsafe` block.
3230/// Therefore, implementations must not require the user to uphold
3231/// any safety invariants.
3232///
3233/// The stabilized version of this intrinsic is [`f64::min`].
3234#[rustc_nounwind]
3235#[rustc_intrinsic_const_stable_indirect]
3236#[rustc_intrinsic]
3237pub const fn minimum_number_nsz_f64(x: f64, y: f64) -> f64 {
3238 if x.is_nan() || y <= x {
3239 y
3240 } else {
3241 // Either y > x or y is a NaN.
3242 x
3243 }
3244}
3245
3246/// Returns the minimum of two `f128` values, ignoring NaN.
3247///
3248/// This behaves like IEEE 754-2019 minimumNumber, *except* that it does not order signed
3249/// zeros deterministically. In particular:
3250/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3251/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3252/// and `-0.0`), either input may be returned non-deterministically.
3253///
3254/// Note that, unlike most intrinsics, this is safe to call;
3255/// it does not require an `unsafe` block.
3256/// Therefore, implementations must not require the user to uphold
3257/// any safety invariants.
3258///
3259/// The stabilized version of this intrinsic is [`f128::min`].
3260#[rustc_nounwind]
3261#[rustc_intrinsic]
3262pub const fn minimum_number_nsz_f128(x: f128, y: f128) -> f128 {
3263 if x.is_nan() || y <= x {
3264 y
3265 } else {
3266 // Either y > x or y is a NaN.
3267 x
3268 }
3269}
3270
3271/// Returns the minimum of two `f16` values, propagating NaN.
3272///
3273/// This behaves like IEEE 754-2019 minimum. In particular:
3274/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3275/// For this operation, -0.0 is considered to be strictly less than +0.0.
3276///
3277/// Note that, unlike most intrinsics, this is safe to call;
3278/// it does not require an `unsafe` block.
3279/// Therefore, implementations must not require the user to uphold
3280/// any safety invariants.
3281#[rustc_nounwind]
3282#[rustc_intrinsic]
3283pub const fn minimumf16(x: f16, y: f16) -> f16 {
3284 if x < y {
3285 x
3286 } else if y < x {
3287 y
3288 } else if x == y {
3289 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3290 } else {
3291 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3292 x + y
3293 }
3294}
3295
3296/// Returns the minimum of two `f32` values, propagating NaN.
3297///
3298/// This behaves like IEEE 754-2019 minimum. In particular:
3299/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3300/// For this operation, -0.0 is considered to be strictly less than +0.0.
3301///
3302/// Note that, unlike most intrinsics, this is safe to call;
3303/// it does not require an `unsafe` block.
3304/// Therefore, implementations must not require the user to uphold
3305/// any safety invariants.
3306#[rustc_nounwind]
3307#[rustc_intrinsic]
3308pub const fn minimumf32(x: f32, y: f32) -> f32 {
3309 if x < y {
3310 x
3311 } else if y < x {
3312 y
3313 } else if x == y {
3314 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3315 } else {
3316 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3317 x + y
3318 }
3319}
3320
3321/// Returns the minimum of two `f64` values, propagating NaN.
3322///
3323/// This behaves like IEEE 754-2019 minimum. In particular:
3324/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3325/// For this operation, -0.0 is considered to be strictly less than +0.0.
3326///
3327/// Note that, unlike most intrinsics, this is safe to call;
3328/// it does not require an `unsafe` block.
3329/// Therefore, implementations must not require the user to uphold
3330/// any safety invariants.
3331#[rustc_nounwind]
3332#[rustc_intrinsic]
3333pub const fn minimumf64(x: f64, y: f64) -> f64 {
3334 if x < y {
3335 x
3336 } else if y < x {
3337 y
3338 } else if x == y {
3339 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3340 } else {
3341 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3342 x + y
3343 }
3344}
3345
3346/// Returns the minimum of two `f128` values, propagating NaN.
3347///
3348/// This behaves like IEEE 754-2019 minimum. In particular:
3349/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3350/// For this operation, -0.0 is considered to be strictly less than +0.0.
3351///
3352/// Note that, unlike most intrinsics, this is safe to call;
3353/// it does not require an `unsafe` block.
3354/// Therefore, implementations must not require the user to uphold
3355/// any safety invariants.
3356#[rustc_nounwind]
3357#[rustc_intrinsic]
3358pub const fn minimumf128(x: f128, y: f128) -> f128 {
3359 if x < y {
3360 x
3361 } else if y < x {
3362 y
3363 } else if x == y {
3364 if x.is_sign_negative() && y.is_sign_positive() { x } else { y }
3365 } else {
3366 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3367 x + y
3368 }
3369}
3370
3371/// Returns the maximum of two `f16` values, ignoring NaN.
3372///
3373/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3374/// zeros deterministically. In particular:
3375/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3376/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3377/// and `-0.0`), either input may be returned non-deterministically.
3378///
3379/// Note that, unlike most intrinsics, this is safe to call;
3380/// it does not require an `unsafe` block.
3381/// Therefore, implementations must not require the user to uphold
3382/// any safety invariants.
3383///
3384/// The stabilized version of this intrinsic is [`f16::max`].
3385#[rustc_nounwind]
3386#[rustc_intrinsic]
3387pub const fn maximum_number_nsz_f16(x: f16, y: f16) -> f16 {
3388 if x.is_nan() || y >= x {
3389 y
3390 } else {
3391 // Either y < x or y is a NaN.
3392 x
3393 }
3394}
3395
3396/// Returns the maximum of two `f32` values, ignoring NaN.
3397///
3398/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3399/// zeros deterministically. In particular:
3400/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3401/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3402/// and `-0.0`), either input may be returned non-deterministically.
3403///
3404/// Note that, unlike most intrinsics, this is safe to call;
3405/// it does not require an `unsafe` block.
3406/// Therefore, implementations must not require the user to uphold
3407/// any safety invariants.
3408///
3409/// The stabilized version of this intrinsic is [`f32::max`].
3410#[rustc_nounwind]
3411#[rustc_intrinsic_const_stable_indirect]
3412#[rustc_intrinsic]
3413pub const fn maximum_number_nsz_f32(x: f32, y: f32) -> f32 {
3414 if x.is_nan() || y >= x {
3415 y
3416 } else {
3417 // Either y < x or y is a NaN.
3418 x
3419 }
3420}
3421
3422/// Returns the maximum of two `f64` values, ignoring NaN.
3423///
3424/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3425/// zeros deterministically. In particular:
3426/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3427/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3428/// and `-0.0`), either input may be returned non-deterministically.
3429///
3430/// Note that, unlike most intrinsics, this is safe to call;
3431/// it does not require an `unsafe` block.
3432/// Therefore, implementations must not require the user to uphold
3433/// any safety invariants.
3434///
3435/// The stabilized version of this intrinsic is [`f64::max`].
3436#[rustc_nounwind]
3437#[rustc_intrinsic_const_stable_indirect]
3438#[rustc_intrinsic]
3439pub const fn maximum_number_nsz_f64(x: f64, y: f64) -> f64 {
3440 if x.is_nan() || y >= x {
3441 y
3442 } else {
3443 // Either y < x or y is a NaN.
3444 x
3445 }
3446}
3447
3448/// Returns the maximum of two `f128` values, ignoring NaN.
3449///
3450/// This behaves like IEEE 754-2019 maximumNumber, *except* that it does not order signed
3451/// zeros deterministically. In particular:
3452/// If one of the arguments is NaN (quiet or signaling), then the other argument is returned. If
3453/// both arguments are NaN, returns NaN. If the inputs compare equal (such as for the case of `+0.0`
3454/// and `-0.0`), either input may be returned non-deterministically.
3455///
3456/// Note that, unlike most intrinsics, this is safe to call;
3457/// it does not require an `unsafe` block.
3458/// Therefore, implementations must not require the user to uphold
3459/// any safety invariants.
3460///
3461/// The stabilized version of this intrinsic is [`f128::max`].
3462#[rustc_nounwind]
3463#[rustc_intrinsic]
3464pub const fn maximum_number_nsz_f128(x: f128, y: f128) -> f128 {
3465 if x.is_nan() || y >= x {
3466 y
3467 } else {
3468 // Either y < x or y is a NaN.
3469 x
3470 }
3471}
3472
3473/// Returns the maximum of two `f16` values, propagating NaN.
3474///
3475/// This behaves like IEEE 754-2019 maximum. In particular:
3476/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3477/// For this operation, -0.0 is considered to be strictly less than +0.0.
3478///
3479/// Note that, unlike most intrinsics, this is safe to call;
3480/// it does not require an `unsafe` block.
3481/// Therefore, implementations must not require the user to uphold
3482/// any safety invariants.
3483#[rustc_nounwind]
3484#[rustc_intrinsic]
3485pub const fn maximumf16(x: f16, y: f16) -> f16 {
3486 if x > y {
3487 x
3488 } else if y > x {
3489 y
3490 } else if x == y {
3491 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3492 } else {
3493 x + y
3494 }
3495}
3496
3497/// Returns the maximum of two `f32` values, propagating NaN.
3498///
3499/// This behaves like IEEE 754-2019 maximum. In particular:
3500/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3501/// For this operation, -0.0 is considered to be strictly less than +0.0.
3502///
3503/// Note that, unlike most intrinsics, this is safe to call;
3504/// it does not require an `unsafe` block.
3505/// Therefore, implementations must not require the user to uphold
3506/// any safety invariants.
3507#[rustc_nounwind]
3508#[rustc_intrinsic]
3509pub const fn maximumf32(x: f32, y: f32) -> f32 {
3510 if x > y {
3511 x
3512 } else if y > x {
3513 y
3514 } else if x == y {
3515 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3516 } else {
3517 x + y
3518 }
3519}
3520
3521/// Returns the maximum of two `f64` values, propagating NaN.
3522///
3523/// This behaves like IEEE 754-2019 maximum. In particular:
3524/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3525/// For this operation, -0.0 is considered to be strictly less than +0.0.
3526///
3527/// Note that, unlike most intrinsics, this is safe to call;
3528/// it does not require an `unsafe` block.
3529/// Therefore, implementations must not require the user to uphold
3530/// any safety invariants.
3531#[rustc_nounwind]
3532#[rustc_intrinsic]
3533pub const fn maximumf64(x: f64, y: f64) -> f64 {
3534 if x > y {
3535 x
3536 } else if y > x {
3537 y
3538 } else if x == y {
3539 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3540 } else {
3541 x + y
3542 }
3543}
3544
3545/// Returns the maximum of two `f128` values, propagating NaN.
3546///
3547/// This behaves like IEEE 754-2019 maximum. In particular:
3548/// If one of the arguments is NaN, then a NaN is returned using the usual NaN propagation rules.
3549/// For this operation, -0.0 is considered to be strictly less than +0.0.
3550///
3551/// Note that, unlike most intrinsics, this is safe to call;
3552/// it does not require an `unsafe` block.
3553/// Therefore, implementations must not require the user to uphold
3554/// any safety invariants.
3555#[rustc_nounwind]
3556#[rustc_intrinsic]
3557pub const fn maximumf128(x: f128, y: f128) -> f128 {
3558 if x > y {
3559 x
3560 } else if y > x {
3561 y
3562 } else if x == y {
3563 if x.is_sign_positive() && y.is_sign_negative() { x } else { y }
3564 } else {
3565 x + y
3566 }
3567}
3568
3569/// Returns the absolute value of a floating-point value.
3570///
3571/// The stabilized versions of this intrinsic are available on the float
3572/// primitives via the `abs` method. For example, [`f32::abs`].
3573#[rustc_nounwind]
3574#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")]
3575#[rustc_intrinsic_const_stable_indirect]
3576#[rustc_intrinsic]
3577#[miri::intrinsic_fallback_is_spec]
3578pub const fn fabs<T: const bounds::FloatPrimitive>(x: T) -> T {
3579 T::from_bits(x.to_bits() & !T::SIGN_MASK)
3580}
3581
3582/// Copies the sign from `y` to `x` for `f16` values.
3583///
3584/// The stabilized version of this intrinsic is
3585/// [`f16::copysign`](../../std/primitive.f16.html#method.copysign)
3586#[inline]
3587#[rustc_nounwind]
3588#[rustc_intrinsic]
3589pub const fn copysignf16(x: f16, y: f16) -> f16 {
3590 f16::from_bits((x.to_bits() & !f16::SIGN_MASK) | (y.to_bits() & f16::SIGN_MASK))
3591}
3592
3593/// Copies the sign from `y` to `x` for `f32` values.
3594///
3595/// The stabilized version of this intrinsic is
3596/// [`f32::copysign`](../../std/primitive.f32.html#method.copysign)
3597#[inline]
3598#[rustc_nounwind]
3599#[rustc_intrinsic_const_stable_indirect]
3600#[rustc_intrinsic]
3601pub const fn copysignf32(x: f32, y: f32) -> f32 {
3602 f32::from_bits((x.to_bits() & !f32::SIGN_MASK) | (y.to_bits() & f32::SIGN_MASK))
3603}
3604/// Copies the sign from `y` to `x` for `f64` values.
3605///
3606/// The stabilized version of this intrinsic is
3607/// [`f64::copysign`](../../std/primitive.f64.html#method.copysign)
3608#[inline]
3609#[rustc_nounwind]
3610#[rustc_intrinsic_const_stable_indirect]
3611#[rustc_intrinsic]
3612pub const fn copysignf64(x: f64, y: f64) -> f64 {
3613 f64::from_bits((x.to_bits() & !f64::SIGN_MASK) | (y.to_bits() & f64::SIGN_MASK))
3614}
3615
3616/// Copies the sign from `y` to `x` for `f128` values.
3617///
3618/// The stabilized version of this intrinsic is
3619/// [`f128::copysign`](../../std/primitive.f128.html#method.copysign)
3620#[inline]
3621#[rustc_nounwind]
3622#[rustc_intrinsic]
3623pub const fn copysignf128(x: f128, y: f128) -> f128 {
3624 f128::from_bits((x.to_bits() & !f128::SIGN_MASK) | (y.to_bits() & f128::SIGN_MASK))
3625}
3626
3627/// Generates the LLVM body for the automatic differentiation of `f` using Enzyme,
3628/// with `df` as the derivative function and `args` as its arguments.
3629///
3630/// Used internally as the body of `df` when expanding the `#[autodiff_forward]`
3631/// and `#[autodiff_reverse]` attribute macros.
3632///
3633/// Type Parameters:
3634/// - `F`: The original function to differentiate. Must be a function item.
3635/// - `G`: The derivative function. Must be a function item.
3636/// - `T`: A tuple of arguments passed to `df`.
3637/// - `R`: The return type of the derivative function.
3638///
3639/// This shows where the `autodiff` intrinsic is used during macro expansion:
3640///
3641/// ```rust,ignore (macro example)
3642/// #[autodiff_forward(df1, Dual, Const, Dual)]
3643/// pub fn f1(x: &[f64], y: f64) -> f64 {
3644/// unimplemented!()
3645/// }
3646/// ```
3647///
3648/// expands to:
3649///
3650/// ```rust,ignore (macro example)
3651/// #[rustc_autodiff]
3652/// #[inline(never)]
3653/// pub fn f1(x: &[f64], y: f64) -> f64 {
3654/// ::core::panicking::panic("not implemented")
3655/// }
3656/// #[rustc_autodiff(Forward, 1, Dual, Const, Dual)]
3657/// pub fn df1(x: &[f64], bx_0: &[f64], y: f64) -> (f64, f64) {
3658/// ::core::intrinsics::autodiff(f1::<>, df1::<>, (x, bx_0, y))
3659/// }
3660/// ```
3661#[rustc_nounwind]
3662#[rustc_intrinsic]
3663pub const fn autodiff<F, G, T: crate::marker::Tuple, R>(f: F, df: G, args: T) -> R;
3664
3665/// Generates the LLVM body of a wrapper function to offload a kernel `f`.
3666///
3667/// Type Parameters:
3668/// - `F`: The kernel to offload. Must be a function item.
3669/// - `T`: A tuple of arguments passed to `f`.
3670/// - `R`: The return type of the kernel.
3671///
3672/// Arguments:
3673/// - `f`: The kernel function to offload.
3674/// - `workgroup_dim`: A 3D size specifying the number of workgroups to launch.
3675/// - `thread_dim`: A 3D size specifying the number of threads per workgroup.
3676/// - `dyn_cache`: The amount of dynamic shared memory to request for the kernel.
3677/// - `device_id`: The device to offload to. Use `-1` to select the default device.
3678/// - `args`: A tuple of arguments forwarded to `f`.
3679///
3680/// Example usage (pseudocode):
3681///
3682/// ```rust,ignore (pseudocode)
3683/// fn kernel(x: *mut [f64; 128]) {
3684/// core::intrinsics::offload(kernel_1, [256, 1, 1], [32, 1, 1], 0, -1, (x,))
3685/// }
3686///
3687/// #[cfg(target_os = "linux")]
3688/// extern "C" {
3689/// pub fn kernel_1(array_b: *mut [f64; 128]);
3690/// }
3691///
3692/// #[cfg(not(target_os = "linux"))]
3693/// #[rustc_offload_kernel]
3694/// extern "gpu-kernel" fn kernel_1(x: *mut [f64; 128]) {
3695/// unsafe { (*x)[0] = 21.0 };
3696/// }
3697/// ```
3698///
3699/// For reference, see the Clang documentation on offloading:
3700/// <https://clang.llvm.org/docs/OffloadingDesign.html>.
3701#[rustc_nounwind]
3702#[rustc_intrinsic]
3703pub const fn offload<F, T: crate::marker::Tuple, R>(
3704 f: F,
3705 workgroup_dim: [u32; 3],
3706 thread_dim: [u32; 3],
3707 dyn_cache: u32,
3708 device_id: i32,
3709 args: T,
3710) -> R;
3711
3712/// Returns the number of offload devices available on the system.
3713///
3714/// Use this to discover which `device_id` values are valid to pass to
3715/// [`offload`]. Devices are numbered from `0` to the returned value minus one.
3716///
3717/// Returns `0` if no offloading devices are present.
3718#[rustc_nounwind]
3719#[rustc_intrinsic]
3720pub const fn offload_get_num_devices() -> i32;
3721
3722/// Inform Miri that a given pointer definitely has a certain alignment.
3723#[cfg(miri)]
3724#[rustc_allow_const_fn_unstable(const_eval_select)]
3725pub(crate) const fn miri_promise_symbolic_alignment(ptr: *const (), align: usize) {
3726 unsafe extern "Rust" {
3727 /// Miri-provided extern function to promise that a given pointer is properly aligned for
3728 /// "symbolic" alignment checks. Will fail if the pointer is not actually aligned or `align` is
3729 /// not a power of two. Has no effect when alignment checks are concrete (which is the default).
3730 fn miri_promise_symbolic_alignment(ptr: *const (), align: usize);
3731 }
3732
3733 const_eval_select!(
3734 @capture { ptr: *const (), align: usize}:
3735 if const {
3736 // Do nothing.
3737 } else {
3738 // SAFETY: this call is always safe.
3739 unsafe {
3740 miri_promise_symbolic_alignment(ptr, align);
3741 }
3742 }
3743 )
3744}
3745
3746/// Loads an argument of type `T` from the `va_list` `ap` and increment the
3747/// argument `ap` points to.
3748///
3749/// # Safety
3750///
3751/// This function is only sound to call when:
3752///
3753/// - there is a next variable argument available.
3754/// - the next argument's type must be ABI-compatible with the type `T`.
3755/// - the next argument must have a properly initialized value of type `T`.
3756///
3757/// Calling this function with an incompatible type, an invalid value, or when there
3758/// are no more variable arguments, is unsound.
3759///
3760#[rustc_intrinsic]
3761#[rustc_nounwind]
3762pub const unsafe fn va_arg<T: VaArgSafe>(ap: &mut VaList<'_>) -> T;
3763
3764/// Duplicates a variable argument list. The returned list is initially at the same position as
3765/// the one in `src`, but can be advanced independently.
3766///
3767/// Codegen backends should not have custom behavior for this intrinsic, they should always use
3768/// this fallback implementation. This intrinsic *does not* map to the LLVM `va_copy` intrinsic.
3769///
3770/// This intrinsic exists only as a hook for Miri and constant evaluation, and is used to detect UB
3771/// when a variable argument list is used incorrectly.
3772#[rustc_intrinsic]
3773#[rustc_nounwind]
3774pub const fn va_copy<'f>(src: &VaList<'f>) -> VaList<'f> {
3775 // This fallback body exploits the fact that our codegen backends all just use
3776 // a plain memcpy to duplicate VaList. This assumption is wrong for Miri.
3777 assert!(!cfg!(miri), "fallback body is incorrect under Miri");
3778
3779 src.duplicate()
3780}
3781
3782/// Destroy the variable argument list `ap` after initialization with `va_start` (part of the
3783/// desugaring of `...`) or `va_copy`.
3784///
3785/// Code generation backends should not provide a custom implementation for this intrinsic. This
3786/// intrinsic *does not* map to the LLVM `va_end` intrinsic.
3787///
3788/// This function is a no-op on all current targets, but used as a hook for const evaluation to
3789/// detect UB when a variable argument list is used incorrectly.
3790///
3791/// # Safety
3792///
3793/// `ap` must not be used to access variable arguments after this call.
3794///
3795#[rustc_intrinsic]
3796#[rustc_nounwind]
3797pub const unsafe fn va_end(ap: &mut VaList<'_>) {
3798 /* deliberately does nothing */
3799}
3800
3801/// 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.
3802/// Returning an accurate value is a quality-of-implementation concern, but no hard guarantees are
3803/// made about the return value: formally, the intrinsic non-deterministically returns
3804/// an arbitrary pointer without provenance.
3805///
3806/// 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.
3807/// Other forms of the corresponding gcc or llvm intrinsic (which can have wildly unpredictable results or even crash at runtime) are not exposed.
3808#[rustc_intrinsic]
3809#[rustc_nounwind]
3810pub fn return_address() -> *const () {
3811 core::ptr::null()
3812}