Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 89fe961

Browse files
committed
Auto merge of #148478 - RalfJung:rotating-funnel, r=Mark-Simulacrum
use funnel shift as fallback impl for rotating shifts That lets us remove this gnarly implementation from Miri and const-eval. However, `rotate_left`/`rotate_right` are stable as const fn, so to do this we have to `rustc_allow_const_fn_unstable` a bunch of const trait stuff. Is that a bad idea? Cc `@oli-obk` `@fee1-dead`
2 parents 69d4d5f + a00db66 commit 89fe961

6 files changed

Lines changed: 47 additions & 44 deletions

File tree

‎compiler/rustc_codegen_llvm/src/intrinsic.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -378,8 +378,6 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
378378
| sym::ctpop
379379
| sym::bswap
380380
| sym::bitreverse
381-
| sym::rotate_left
382-
| sym::rotate_right
383381
| sym::saturating_add
384382
| sym::saturating_sub
385383
| sym::unchecked_funnel_shl
@@ -424,19 +422,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
424422
sym::bitreverse => {
425423
self.call_intrinsic("llvm.bitreverse",&[llty],&[args[0].immediate()])
426424
}
427-
sym::rotate_left
428-
| sym::rotate_right
429-
| sym::unchecked_funnel_shl
430-
| sym::unchecked_funnel_shr => {
431-
let is_left = name == sym::rotate_left || name == sym::unchecked_funnel_shl;
425+
sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => {
426+
let is_left = name == sym::unchecked_funnel_shl;
432427
let lhs = args[0].immediate();
433-
let(rhs, raw_shift) =
434-
if name == sym::rotate_left || name == sym::rotate_right {
435-
// rotate = funnel shift with first two args the same
436-
(lhs, args[1].immediate())
437-
}else{
438-
(args[1].immediate(), args[2].immediate())
439-
};
428+
let rhs = args[1].immediate();
429+
let raw_shift = args[2].immediate();
440430
let llvm_name = format!("llvm.fsh{}",if is_left {'l'} else {'r'});
441431

442432
// llvm expects shift to be the same type as the values, but rust

‎compiler/rustc_const_eval/src/interpret/intrinsics.rs‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -333,29 +333,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
333333
let r = self.read_immediate(&args[1])?;
334334
self.exact_div(&l,&r, dest)?;
335335
}
336-
sym::rotate_left | sym::rotate_right => {
337-
// rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
338-
// rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
339-
let layout_val = self.layout_of(instance_args.type_at(0))?;
340-
let val = self.read_scalar(&args[0])?;
341-
let val_bits = val.to_bits(layout_val.size)?;// sign is ignored here
342-
343-
let layout_raw_shift = self.layout_of(self.tcx.types.u32)?;
344-
let raw_shift = self.read_scalar(&args[1])?;
345-
let raw_shift_bits = raw_shift.to_bits(layout_raw_shift.size)?;
346-
347-
let width_bits = u128::from(layout_val.size.bits());
348-
let shift_bits = raw_shift_bits % width_bits;
349-
let inv_shift_bits = (width_bits - shift_bits) % width_bits;
350-
let result_bits = if intrinsic_name == sym::rotate_left {
351-
(val_bits << shift_bits) | (val_bits >> inv_shift_bits)
352-
}else{
353-
(val_bits >> shift_bits) | (val_bits << inv_shift_bits)
354-
};
355-
let truncated_bits = layout_val.size.truncate(result_bits);
356-
let result = Scalar::from_uint(truncated_bits, layout_val.size);
357-
self.write_scalar(result, dest)?;
358-
}
359336
sym::copy => {
360337
self.copy_intrinsic(&args[0],&args[1],&args[2],/*nonoverlapping*/false)?;
361338
}

‎library/core/src/intrinsics/mod.rs‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
usecrate::ffi::va_list::{VaArgSafe,VaListImpl};
5858
usecrate::marker::{ConstParamTy,Destruct,DiscriminantKind,PointeeSized,Tuple};
59-
usecrate::ptr;
59+
usecrate::{mem,ptr};
6060

6161
mod bounds;
6262
pubmod fallback;
@@ -2013,7 +2013,14 @@ pub const unsafe fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
20132013
#[rustc_intrinsic_const_stable_indirect]
20142014
#[rustc_nounwind]
20152015
#[rustc_intrinsic]
2016-
pubconstfnrotate_left<T:Copy>(x:T,shift:u32) -> T;
2016+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2017+
#[miri::intrinsic_fallback_is_spec]
2018+
pubconstfnrotate_left<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2019+
// Make sure to call the intrinsic for `funnel_shl`, not the fallback impl.
2020+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2021+
// `T` in bits.
2022+
unsafe{unchecked_funnel_shl(x, x, shift % (mem::size_of::<T>()asu32*8))}
2023+
}
20172024

20182025
/// Performs rotate right.
20192026
///
@@ -2028,7 +2035,14 @@ pub const fn rotate_left<T: Copy>(x: T, shift: u32) -> T;
20282035
#[rustc_intrinsic_const_stable_indirect]
20292036
#[rustc_nounwind]
20302037
#[rustc_intrinsic]
2031-
pubconstfnrotate_right<T:Copy>(x:T,shift:u32) -> T;
2038+
#[rustc_allow_const_fn_unstable(const_trait_impl, funnel_shifts)]
2039+
#[miri::intrinsic_fallback_is_spec]
2040+
pubconstfnrotate_right<T:[const] fallback::FunnelShift>(x:T,shift:u32) -> T{
2041+
// Make sure to call the intrinsic for `funnel_shr`, not the fallback impl.
2042+
// SAFETY: we modulo `shift` so that the result is definitely less than the size of
2043+
// `T` in bits.
2044+
unsafe{unchecked_funnel_shr(x, x, shift % (mem::size_of::<T>()asu32*8))}
2045+
}
20322046

20332047
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
20342048
///

‎library/core/src/num/int_macros.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ macro_rules! int_impl {
275275
/// Shifts the bits to the left by a specified amount, `n`,
276276
/// wrapping the truncated bits to the end of the resulting integer.
277277
///
278+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
279+
/// particular, a rotation by the number of bits in `self` returns the input value
280+
/// unchanged.
281+
///
278282
/// Please note this isn't the same operation as the `<<` shifting operator!
279283
///
280284
/// # Examples
@@ -284,6 +288,7 @@ macro_rules! int_impl {
284288
#[doc = concat!("let m = ", $rot_result,";")]
285289
///
286290
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
291+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
287292
/// ```
288293
#[stable(feature = "rust1", since = "1.0.0")]
289294
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
@@ -298,6 +303,10 @@ macro_rules! int_impl {
298303
/// wrapping the truncated bits to the beginning of the resulting
299304
/// integer.
300305
///
306+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
307+
/// particular, a rotation by the number of bits in `self` returns the input value
308+
/// unchanged.
309+
///
301310
/// Please note this isn't the same operation as the `>>` shifting operator!
302311
///
303312
/// # Examples
@@ -307,6 +316,7 @@ macro_rules! int_impl {
307316
#[doc = concat!("let m = ", $rot_op,";")]
308317
///
309318
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
319+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
310320
/// ```
311321
#[stable(feature = "rust1", since = "1.0.0")]
312322
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]

‎library/core/src/num/uint_macros.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,10 @@ macro_rules! uint_impl {
336336
/// Shifts the bits to the left by a specified amount, `n`,
337337
/// wrapping the truncated bits to the end of the resulting integer.
338338
///
339+
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340+
/// particular, a rotation by the number of bits in `self` returns the input value
341+
/// unchanged.
342+
///
339343
/// Please note this isn't the same operation as the `<<` shifting operator!
340344
///
341345
/// # Examples
@@ -345,12 +349,14 @@ macro_rules! uint_impl {
345349
#[doc = concat!("let m = ", $rot_result,";")]
346350
///
347351
#[doc = concat!("assert_eq!(n.rotate_left(", $rot,"), m);")]
352+
#[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
348353
/// ```
349354
#[stable(feature = "rust1", since = "1.0.0")]
350355
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
351356
#[must_use = "this returns the result of the operation, \
352357
without modifying the original"]
353358
#[inline(always)]
359+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
354360
pubconstfn rotate_left(self, n:u32) -> Self{
355361
return intrinsics::rotate_left(self, n);
356362
}
@@ -359,6 +365,10 @@ macro_rules! uint_impl {
359365
/// wrapping the truncated bits to the beginning of the resulting
360366
/// integer.
361367
///
368+
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369+
/// particular, a rotation by the number of bits in `self` returns the input value
370+
/// unchanged.
371+
///
362372
/// Please note this isn't the same operation as the `>>` shifting operator!
363373
///
364374
/// # Examples
@@ -368,12 +378,14 @@ macro_rules! uint_impl {
368378
#[doc = concat!("let m = ", $rot_op,";")]
369379
///
370380
#[doc = concat!("assert_eq!(n.rotate_right(", $rot,"), m);")]
381+
#[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
371382
/// ```
372383
#[stable(feature = "rust1", since = "1.0.0")]
373384
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
374385
#[must_use = "this returns the result of the operation, \
375386
without modifying the original"]
376387
#[inline(always)]
388+
#[rustc_allow_const_fn_unstable(const_trait_impl)]// for the intrinsic fallback
377389
pubconstfn rotate_right(self, n:u32) -> Self{
378390
return intrinsics::rotate_right(self, n);
379391
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//@ compile-flags: -C no-prepopulate-passes
1+
//@ compile-flags: -O
22

33
#![crate_type = "lib"]
44
#![feature(core_intrinsics)]
@@ -9,7 +9,7 @@ use std::intrinsics::rotate_left;
99
#[no_mangle]
1010
pubunsafefnrotate_left_u16(x:u16,shift:u32) -> u16{
1111
// CHECK: %[[tmp:.*]] = trunc i32 %shift to i16
12-
// CHECK: call i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
12+
// CHECK: call noundef i16 @llvm.fshl.i16(i16 %x, i16 %x, i16 %[[tmp]])
1313
rotate_left(x, shift)
1414
}
1515

@@ -18,14 +18,14 @@ pub unsafe fn rotate_left_u16(x: u16, shift: u32) -> u16 {
1818
pubunsafefnrotate_left_u32(x:u32,shift:u32) -> u32{
1919
// CHECK-NOT: trunc
2020
// CHECK-NOT: zext
21-
// CHECK: call i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
21+
// CHECK: call noundef i32 @llvm.fshl.i32(i32 %x, i32 %x, i32 %shift)
2222
rotate_left(x, shift)
2323
}
2424

2525
// CHECK-LABEL: @rotate_left_u64
2626
#[no_mangle]
2727
pubunsafefnrotate_left_u64(x:u64,shift:u32) -> u64{
2828
// CHECK: %[[tmp:.*]] = zext i32 %shift to i64
29-
// CHECK: call i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
29+
// CHECK: call noundef i64 @llvm.fshl.i64(i64 %x, i64 %x, i64 %[[tmp]])
3030
rotate_left(x, shift)
3131
}

0 commit comments

Comments
 (0)