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