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