Skip to main content

core/intrinsics/
mod.rs

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