Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions compiler/rustc_const_eval/src/interpret/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ use rustc_apfloat::ieee::{Double, Half, Quad, Single};
use rustc_ast::{IntTy, UintTy};
use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint};
use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic};
use rustc_middle::ty;
use rustc_middle::ty::layout::TyAndLayout;
use rustc_middle::ty::{FloatTy, Ty, TyCtxt, TypeVisitableExt};
use rustc_middle::ty::{self, FloatTy, ScalarInt, Ty, TyCtxt, TypeVisitableExt};
use rustc_span::{Symbol, bug, span_bug, sym};
use tracing::trace;

Expand Down Expand Up @@ -376,6 +375,17 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
let r = self.read_immediate(&args[1])?;
self.exact_div(&l, &r, dest)?;
}
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
let shift_left = intrinsic_name == sym::unchecked_funnel_shl;

let l = self.read_immediate(&args[0])?;
let r = self.read_immediate(&args[1])?;
let shift = self.read_immediate(&args[2])?;

let result = self.funnel_shift(&l, &r, &shift, shift_left)?;
self.write_scalar(result, dest)?;
}

sym::copy => {
self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?;
}
Expand Down Expand Up @@ -969,6 +979,50 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
})
}

pub fn funnel_shift(
&self,
left: &ImmTy<'tcx, M::Provenance>,
right: &ImmTy<'tcx, M::Provenance>,
shift_bits: &ImmTy<'tcx, M::Provenance>,
shift_left: bool,
) -> InterpResult<'tcx, Scalar<M::Provenance>> {
let size = left.layout.size;
let left = left.to_scalar().to_bits(size)?;
let right = right.to_scalar().to_bits(size)?;
let shift_bits = shift_bits.to_scalar().to_bits(shift_bits.layout.size)?; // can have different size

if shift_bits >= size.bits().into() {
throw_ub_format!(
"overflowing shift by {shift_bits} in {} funnel shift",
if shift_left { "left" } else { "right" }
);
}
let inv_shift_bits = u32::try_from(u128::from(size.bits()) - shift_bits).unwrap();

// A funnel shift left by S can be implemented as `(x << S) | y.unbounded_shr(SIZE - S)`.
// The `unbounded_shr` is needed because otherwise if `S = 0`, it would be `x | y`
// when it should be `x`.
//
// This selects the least-significant `SIZE - S` bits of `x`, followed by the `S` most
// significant bits of `y`. As `left` and `right` both occupy the lower `SIZE` bits,
// we can treat the lower `SIZE` bits as an integer of the right width and use
// the same implementation, but on a zero-extended `x` and `y`. This works because
// `x << S` just pushes the `SIZE-S` MSBs out, and `y >> (SIZE - S)` shifts in
// zeros, as it is zero-extended. To the lower `SIZE` bits, this looks just like a
// funnel shift left.
//
// Note that the `unbounded_sh{l,r}`s are needed only in case we are using this on
// `u128xN` and `inv_shift_bits == 128`.
let result_bits = if shift_left {
(left << shift_bits) | right.unbounded_shr(inv_shift_bits)
} else {
left.unbounded_shl(inv_shift_bits) | (right >> shift_bits)
};

let (result, _overflow) = ScalarInt::truncate_from_uint(result_bits, size);
interp_ok(result.into())
}

/// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its
/// allocation.
pub fn ptr_offset_inbounds(
Expand Down
70 changes: 23 additions & 47 deletions compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use rustc_abi::{BackendRepr, Endian};
use rustc_apfloat::ieee::{Double, Half, Quad, Single};
use rustc_apfloat::{Float, Round};
use rustc_middle::mir::interpret::{InterpErrorKind, Pointer, UndefinedBehaviorInfo};
use rustc_middle::ty::{FloatTy, ScalarInt, SimdAlign};
use rustc_middle::ty::{FloatTy, SimdAlign};
use rustc_middle::{err_ub_format, mir, throw_unsup_format, ty};
use rustc_span::{Symbol, bug, span_bug, sym};
use tracing::trace;
Expand Down Expand Up @@ -758,54 +758,30 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
}
}
sym::simd_funnel_shl | sym::simd_funnel_shr => {
let (left, _) = self.project_to_simd(&args[0])?;
let (right, _) = self.project_to_simd(&args[1])?;
let (shift, _) = self.project_to_simd(&args[2])?;
let (dest, _) = self.project_to_simd(&dest)?;

let (len, elem_ty) = args[0].layout.ty.simd_size_and_type(*self.tcx);
let (elem_size, _signed) = elem_ty.int_size_and_signed(*self.tcx);
let elem_size_bits = u128::from(elem_size.bits());

let is_left = intrinsic_name == sym::simd_funnel_shl;

for i in 0..len {
let left =
self.read_scalar(&self.project_index(&left, i)?)?.to_bits(elem_size)?;
let right =
self.read_scalar(&self.project_index(&right, i)?)?.to_bits(elem_size)?;
let shift_bits =
self.read_scalar(&self.project_index(&shift, i)?)?.to_bits(elem_size)?;

if shift_bits >= elem_size_bits {
throw_ub_format!(
"overflowing shift by {shift_bits} in `{intrinsic_name}` in lane {i}"
);
}
let inv_shift_bits = u32::try_from(elem_size_bits - shift_bits).unwrap();

// A funnel shift left by S can be implemented as `(x << S) | y.unbounded_shr(SIZE - S)`.
// The `unbounded_shr` is needed because otherwise if `S = 0`, it would be `x | y`
// when it should be `x`.
//
// This selects the least-significant `SIZE - S` bits of `x`, followed by the `S` most
// significant bits of `y`. As `left` and `right` both occupy the lower `SIZE` bits,
// we can treat the lower `SIZE` bits as an integer of the right width and use
// the same implementation, but on a zero-extended `x` and `y`. This works because
// `x << S` just pushes the `SIZE-S` MSBs out, and `y >> (SIZE - S)` shifts in
// zeros, as it is zero-extended. To the lower `SIZE` bits, this looks just like a
// funnel shift left.
//
// Note that the `unbounded_sh{l,r}`s are needed only in case we are using this on
// `u128xN` and `inv_shift_bits == 128`.
let result_bits = if is_left {
(left << shift_bits) | right.unbounded_shr(inv_shift_bits)
} else {
left.unbounded_shl(inv_shift_bits) | (right >> shift_bits)
};
let (result, _overflow) = ScalarInt::truncate_from_uint(result_bits, elem_size);
let shift_left = intrinsic_name == sym::simd_funnel_shl;

let (left, left_len) = self.project_to_simd(&args[0])?;
let (right, right_len) = self.project_to_simd(&args[1])?;
let (shift, shift_len) = self.project_to_simd(&args[2])?;
let (dest, dest_len) = self.project_to_simd(&dest)?;

assert_eq!(dest_len, left_len);
assert_eq!(dest_len, right_len);
assert_eq!(dest_len, shift_len);

for i in 0..dest_len {
let left = self.read_immediate(&self.project_index(&left, i)?)?;
let right = self.read_immediate(&self.project_index(&right, i)?)?;
let shift_bits = self.read_immediate(&self.project_index(&shift, i)?)?;
let dest = self.project_index(&dest, i)?;

let result = self.funnel_shift(&left, &right, &shift_bits, shift_left)
.map_err_kind(|_err| {
err_ub_format!(
"overflowing shift by {shift_bits} in `{intrinsic_name}` in lane {i}"
)
})?;

self.write_scalar(result, &dest)?;
}
}
Expand Down
14 changes: 2 additions & 12 deletions library/core/src/intrinsics/fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,7 @@ impl_disjoint_bitor! {
i8, i16, i32, i64, i128, isize,
}

#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
pub const trait FunnelShift: Copy + 'static {
pub trait FunnelShift: Copy + 'static {
/// We just need the trait indirection to handle different types
/// since calling intrinsics with generics doesn't work.
///
Expand All @@ -175,14 +174,9 @@ pub const trait FunnelShift: Copy + 'static {

macro_rules! impl_funnel_shifts {
($($type:ident),*) => {$(
#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")]
const impl FunnelShift for $type {
#[cfg_attr(miri, track_caller)]
impl FunnelShift for $type {
#[inline]
unsafe fn unchecked_funnel_shl(self, right: Self, shift: u32) -> Self {
// This implementation is also used by Miri so we have to check the precondition.
// SAFETY: this is guaranteed by the caller
unsafe { super::assume(shift < $type::BITS) };
if shift == 0 {
self
} else {
Expand All @@ -202,12 +196,8 @@ macro_rules! impl_funnel_shifts {
}
}

#[cfg_attr(miri, track_caller)]
#[inline]
unsafe fn unchecked_funnel_shr(self, right: Self, shift: u32) -> Self {
// This implementation is also used by Miri so we have to check the precondition.
// SAFETY: this is guaranteed by the caller
unsafe { super::assume(shift < $type::BITS) };
if shift == 0 {
right
} else {
Expand Down
35 changes: 12 additions & 23 deletions library/core/src/intrinsics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2122,8 +2122,9 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
#[rustc_nounwind]
#[rustc_intrinsic]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
#[cfg_attr(miri, track_caller)]

@RalfJung RalfJung Oct 29, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes a pre-existing issue for Miri backtraces, making sure they point at where rotate_left is called rather than inside its fallback body.

View changes since the review

#[miri::intrinsic_fallback_is_spec]
pub const fn rotate_left<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
pub const fn rotate_left<T: fallback::FunnelShift>(x: T, shift: u32) -> T {
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
// `T` in bits.
Expand All @@ -2144,8 +2145,9 @@ pub const fn rotate_left<T: [const] fallback::FunnelShift>(x: T, shift: u32) ->
#[rustc_nounwind]
#[rustc_intrinsic]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
#[cfg_attr(miri, track_caller)]
#[miri::intrinsic_fallback_is_spec]
pub const fn rotate_right<T: [const] fallback::FunnelShift>(x: T, shift: u32) -> T {
pub const fn rotate_right<T: fallback::FunnelShift>(x: T, shift: u32) -> T {
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
// `T` in bits.
Expand Down Expand Up @@ -2239,17 +2241,11 @@ pub const fn saturating_sub<T: Copy>(a: T, b: T) -> T;
///
/// Safe versions of this intrinsic are available on the integer primitives
/// via the `funnel_shl` method. For example, [`u32::funnel_shl`].
#[rustc_intrinsic_const_stable_indirect]
#[rustc_intrinsic]
#[rustc_nounwind]
#[track_caller]
#[rustc_allow_const_fn_unstable(const_trait_impl, core_intrinsics_fallbacks)]
#[miri::intrinsic_fallback_is_spec]
pub const unsafe fn unchecked_funnel_shl<T: [const] fallback::FunnelShift>(
a: T,
b: T,
shift: u32,
) -> T {
#[rustc_intrinsic_const_stable_indirect]
#[rustc_do_not_const_check] // Use built-in impl to avoid const-checks in the fallback body.

@oli-obk oli-obk Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unrelated to this PR: do we ensure nowadays that ctfe doesn't interpret rustc_do_not_const_check bodies?

View changes since the review

@RalfJung RalfJung Oct 29, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we have ensured this for >5 years already. See tests/ui/consts/const-eval/do_not_const_check.rs.

pub const unsafe fn unchecked_funnel_shl<T: fallback::FunnelShift>(a: T, b: T, shift: u32) -> T {
// SAFETY: caller ensures that `shift` is in-range
unsafe { a.unchecked_funnel_shl(b, shift) }
}
Expand All @@ -2267,17 +2263,11 @@ pub const unsafe fn unchecked_funnel_shl<T: [const] fallback::FunnelShift>(
///
/// Safer versions of this intrinsic are available on the integer primitives
/// via the `funnel_shr` method. For example, [`u32::funnel_shr`]
#[rustc_intrinsic_const_stable_indirect]
#[rustc_intrinsic]
#[rustc_nounwind]
#[track_caller]
#[rustc_allow_const_fn_unstable(const_trait_impl, core_intrinsics_fallbacks)]
#[miri::intrinsic_fallback_is_spec]
pub const unsafe fn unchecked_funnel_shr<T: [const] fallback::FunnelShift>(
a: T,
b: T,
shift: u32,
) -> T {
#[rustc_intrinsic_const_stable_indirect]
#[rustc_do_not_const_check] // Ise built-in impl to avoid const-checks in the fallback body.
pub const unsafe fn unchecked_funnel_shr<T: fallback::FunnelShift>(a: T, b: T, shift: u32) -> T {
// SAFETY: caller ensures that `shift` is in-range
unsafe { a.unchecked_funnel_shr(b, shift) }
}
Expand Down Expand Up @@ -3489,11 +3479,10 @@ pub const fn maximumf128(x: f128, y: f128) -> f128 {
/// The stabilized versions of this intrinsic are available on the float
/// primitives via the `abs` method. For example, [`f32::abs`].
#[rustc_nounwind]
#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")]
#[rustc_intrinsic_const_stable_indirect]
#[rustc_intrinsic]
#[rustc_intrinsic_const_stable_indirect]
#[rustc_do_not_const_check] // Use built-in impl to avoid const-checks in the fallback body.
#[miri::intrinsic_fallback_is_spec]
#[rustc_do_not_const_check] // use built-in impl to avoid const-checks in the fallback body.
pub const fn fabs<T: bounds::FloatPrimitive>(x: T) -> T {
T::from_bits(x.to_bits() & !T::SIGN_MASK)
}
Expand Down
2 changes: 1 addition & 1 deletion src/tools/miri/tests/fail/intrinsics/funnel_shl.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: Undefined Behavior: `assume` called with `false`
error: Undefined Behavior: overflowing shift by 32 in left funnel shift
--> tests/fail/intrinsics/funnel_shl.rs:LL:CC
|
LL | std::intrinsics::unchecked_funnel_shl(1_u32, 2, 32);
Expand Down
2 changes: 1 addition & 1 deletion src/tools/miri/tests/fail/intrinsics/funnel_shr.stderr
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: Undefined Behavior: `assume` called with `false`
error: Undefined Behavior: overflowing shift by 32 in right funnel shift
--> tests/fail/intrinsics/funnel_shr.rs:LL:CC
|
LL | std::intrinsics::unchecked_funnel_shr(1_u32, 2, 32);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ fn main() {
unsafe {
let x = i32x2::from_array([1, 1]);
let y = i32x2::from_array([100, 0]);
simd_funnel_shl(x, x, y); //~ERROR: overflowing shift by 100 in `simd_funnel_shl` in lane 0
simd_funnel_shl(x, x, y); //~ERROR: overflowing shift by 100_i32 in `simd_funnel_shl` in lane 0
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: Undefined Behavior: overflowing shift by 100 in `simd_funnel_shl` in lane 0
error: Undefined Behavior: overflowing shift by 100_i32 in `simd_funnel_shl` in lane 0
--> tests/fail/intrinsics/simd-funnel_shl-too-far.rs:LL:CC
|
LL | simd_funnel_shl(x, x, y);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ fn main() {
unsafe {
let x = i32x2::from_array([1, 1]);
let y = i32x2::from_array([20, 40]);
simd_funnel_shr(x, x, y); //~ERROR: overflowing shift by 40 in `simd_funnel_shr` in lane 1
simd_funnel_shr(x, x, y); //~ERROR: overflowing shift by 40_i32 in `simd_funnel_shr` in lane 1
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: Undefined Behavior: overflowing shift by 40 in `simd_funnel_shr` in lane 1
error: Undefined Behavior: overflowing shift by 40_i32 in `simd_funnel_shr` in lane 1
--> tests/fail/intrinsics/simd-funnel_shr-too-far.rs:LL:CC
|
LL | simd_funnel_shr(x, x, y);
Expand Down
Loading