From 158894464c5e4b143c7b307f932d9eb51afc24ee Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 12 Dec 2022 11:10:19 +0100 Subject: interpret: add read_machine_[ui]size convenience methods --- compiler/rustc_const_eval/src/interpret/intrinsics.rs | 8 ++++---- compiler/rustc_const_eval/src/interpret/operand.rs | 11 +++++++++++ compiler/rustc_const_eval/src/interpret/projection.rs | 4 ++-- 3 files changed, 17 insertions(+), 6 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index b9be7fa4800..7031a0b45d6 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -305,7 +305,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } sym::offset => { let ptr = self.read_pointer(&args[0])?; - let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?; + let offset_count = self.read_machine_isize(&args[1])?; let pointee_ty = substs.type_at(0); let offset_ptr = self.ptr_offset_inbounds(ptr, pointee_ty, offset_count)?; @@ -313,7 +313,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } sym::arith_offset => { let ptr = self.read_pointer(&args[0])?; - let offset_count = self.read_scalar(&args[1])?.to_machine_isize(self)?; + let offset_count = self.read_machine_isize(&args[1])?; let pointee_ty = substs.type_at(0); let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap(); @@ -670,7 +670,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { count: &OpTy<'tcx, >::Provenance>, nonoverlapping: bool, ) -> InterpResult<'tcx> { - let count = self.read_scalar(&count)?.to_machine_usize(self)?; + let count = self.read_machine_usize(&count)?; let layout = self.layout_of(src.layout.ty.builtin_deref(true).unwrap().ty)?; let (size, align) = (layout.size, layout.align.abi); // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max), @@ -698,7 +698,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let dst = self.read_pointer(&dst)?; let byte = self.read_scalar(&byte)?.to_u8()?; - let count = self.read_scalar(&count)?.to_machine_usize(self)?; + let count = self.read_machine_usize(&count)?; // `checked_mul` enforces a too small bound (the correct one would probably be machine_isize_max), // but no actual allocation can be big enough for the difference to be noticeable. diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 221e359d24a..68a3318ab4e 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -407,6 +407,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { Ok(self.read_immediate(op)?.to_scalar()) } + // Pointer-sized reads are fairly common and need target layout access, so we wrap them in + // convenience functions. + /// Read a pointer from a place. pub fn read_pointer( &self, @@ -414,6 +417,14 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ) -> InterpResult<'tcx, Pointer>> { self.read_scalar(op)?.to_pointer(self) } + /// Read a pointer-sized unsigned integer from a place. + pub fn read_machine_usize(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx, u64> { + self.read_scalar(op)?.to_machine_usize(self) + } + /// Read a pointer-sized signed integer from a place. + pub fn read_machine_isize(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx, i64> { + self.read_scalar(op)?.to_machine_isize(self) + } /// Turn the wide MPlace into a string (must already be dereferenced!) pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx, &str> { diff --git a/compiler/rustc_const_eval/src/interpret/projection.rs b/compiler/rustc_const_eval/src/interpret/projection.rs index 2ffd73eef3e..291464ab58a 100644 --- a/compiler/rustc_const_eval/src/interpret/projection.rs +++ b/compiler/rustc_const_eval/src/interpret/projection.rs @@ -363,7 +363,7 @@ where Index(local) => { let layout = self.layout_of(self.tcx.types.usize)?; let n = self.local_to_op(self.frame(), local, Some(layout))?; - let n = self.read_scalar(&n)?.to_machine_usize(self)?; + let n = self.read_machine_usize(&n)?; self.place_index(base, n)? } ConstantIndex { offset, min_length, from_end } => { @@ -392,7 +392,7 @@ where Index(local) => { let layout = self.layout_of(self.tcx.types.usize)?; let n = self.local_to_op(self.frame(), local, Some(layout))?; - let n = self.read_scalar(&n)?.to_machine_usize(self)?; + let n = self.read_machine_usize(&n)?; self.operand_index(base, n)? } ConstantIndex { offset, min_length, from_end } => { -- cgit 1.4.1-3-g733a5 From 8b2a7da3b0d5ef813c3ecbdde2a550eedef27712 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Mon, 12 Dec 2022 15:47:32 +0100 Subject: Rename `assert_uninit_valid` intrinsic It's not about "uninit" anymore but about "filling with 0x01 bytes" so the name should at least try to reflect that. --- compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs | 6 ++++-- compiler/rustc_codegen_ssa/src/mir/block.rs | 6 +++--- compiler/rustc_const_eval/src/interpret/intrinsics.rs | 6 ++++-- compiler/rustc_hir_analysis/src/check/intrinsic.rs | 8 ++++---- compiler/rustc_span/src/symbol.rs | 2 +- library/core/src/intrinsics.rs | 7 ++++--- library/core/src/mem/mod.rs | 3 ++- src/test/ui/consts/assert-type-intrinsics.rs | 2 +- src/test/ui/consts/assert-type-intrinsics.stderr | 4 ++-- 9 files changed, 25 insertions(+), 19 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 0302b843aa2..e4a27f1bb6d 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -713,7 +713,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let res = CValue::by_val(swap(&mut fx.bcx, val), arg.layout()); ret.write_cvalue(fx, res); } - sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => { + sym::assert_inhabited | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => { intrinsic_args!(fx, args => (); intrinsic); let layout = fx.layout_of(substs.type_at(0)); @@ -742,7 +742,9 @@ fn codegen_regular_intrinsic_call<'tcx>( return; } - if intrinsic == sym::assert_uninit_valid && !fx.tcx.permits_uninit_init(layout) { + if intrinsic == sym::assert_mem_uninitialized_valid + && !fx.tcx.permits_uninit_init(layout) + { with_no_trimmed_paths!({ crate::base::codegen_panic( fx, diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index f3f5ddb52d6..a1cd43f749e 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -666,12 +666,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { enum AssertIntrinsic { Inhabited, ZeroValid, - UninitValid, + MemUninitializedValid, } let panic_intrinsic = intrinsic.and_then(|i| match i { sym::assert_inhabited => Some(AssertIntrinsic::Inhabited), sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid), - sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid), + sym::assert_mem_uninitialized_valid => Some(AssertIntrinsic::MemUninitializedValid), _ => None, }); if let Some(intrinsic) = panic_intrinsic { @@ -682,7 +682,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let do_panic = match intrinsic { Inhabited => layout.abi.is_uninhabited(), ZeroValid => !bx.tcx().permits_zero_init(layout), - UninitValid => !bx.tcx().permits_uninit_init(layout), + MemUninitializedValid => !bx.tcx().permits_uninit_init(layout), }; Some(if do_panic { let msg_str = with_no_visible_paths!({ diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 7940efcd2b1..27abc2b97b0 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -432,7 +432,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { sym::transmute => { self.copy_op(&args[0], dest, /*allow_transmute*/ true)?; } - sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => { + sym::assert_inhabited + | sym::assert_zero_valid + | sym::assert_mem_uninitialized_valid => { let ty = instance.substs.type_at(0); let layout = self.layout_of(ty)?; @@ -464,7 +466,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } } - if intrinsic_name == sym::assert_uninit_valid { + if intrinsic_name == sym::assert_mem_uninitialized_valid { let should_panic = !self.tcx.permits_uninit_init(layout); if should_panic { diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 69e54b41d4c..598dc2dca5c 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -75,7 +75,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: DefId) -> hir sym::abort | sym::assert_inhabited | sym::assert_zero_valid - | sym::assert_uninit_valid + | sym::assert_mem_uninitialized_valid | sym::size_of | sym::min_align_of | sym::needs_drop @@ -193,9 +193,9 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { } sym::rustc_peek => (1, vec![param(0)], param(0)), sym::caller_location => (0, vec![], tcx.caller_location_ty()), - sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => { - (1, Vec::new(), tcx.mk_unit()) - } + sym::assert_inhabited + | sym::assert_zero_valid + | sym::assert_mem_uninitialized_valid => (1, Vec::new(), tcx.mk_unit()), sym::forget => (1, vec![param(0)], tcx.mk_unit()), sym::transmute => (2, vec![param(0)], param(1)), sym::prefetch_read_data diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 1fcf8c7a8bf..c97340983c0 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -377,9 +377,9 @@ symbols! { assert_eq_macro, assert_inhabited, assert_macro, + assert_mem_uninitialized_valid, assert_ne_macro, assert_receiver_is_total_eq, - assert_uninit_valid, assert_zero_valid, asserting, associated_const_equality, diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 7ed7d767f2f..ed58a7f1799 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -959,13 +959,14 @@ extern "rust-intrinsic" { #[rustc_safe_intrinsic] pub fn assert_zero_valid(); - /// A guard for unsafe functions that cannot ever be executed if `T` has invalid - /// bit patterns: This will statically either panic, or do nothing. + /// A guard for `std::mem::uninitialized`. Checks whether a repeated bit pattern `0x01` + /// is legal for `T`: This will statically either panic, or do nothing. /// /// This intrinsic does not have a stable counterpart. #[rustc_const_unstable(feature = "const_assert_type2", issue = "none")] #[rustc_safe_intrinsic] - pub fn assert_uninit_valid(); + #[cfg(not(bootstrap))] + pub fn assert_mem_uninitialized_valid(); /// Gets a reference to a static `Location` indicating where it was called. /// diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index 383bdc7b6e2..5e01ccc07d8 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -682,7 +682,8 @@ pub unsafe fn zeroed() -> T { pub unsafe fn uninitialized() -> T { // SAFETY: the caller must guarantee that an uninitialized value is valid for `T`. unsafe { - intrinsics::assert_uninit_valid::(); + #[cfg(not(bootstrap))] // If the compiler hits this itself then it deserves the UB. + intrinsics::assert_mem_uninitialized_valid::(); let mut val = MaybeUninit::::uninit(); // Fill memory with 0x01, as an imperfect mitigation for old code that uses this function on diff --git a/src/test/ui/consts/assert-type-intrinsics.rs b/src/test/ui/consts/assert-type-intrinsics.rs index 263d1ae6a3e..b4fd423becd 100644 --- a/src/test/ui/consts/assert-type-intrinsics.rs +++ b/src/test/ui/consts/assert-type-intrinsics.rs @@ -13,7 +13,7 @@ fn main() { //~^ERROR: evaluation of constant value failed }; const _BAD2: () = { - intrinsics::assert_uninit_valid::<&'static i32>(); + intrinsics::assert_mem_uninitialized_valid::<&'static i32>(); //~^ERROR: evaluation of constant value failed }; const _BAD3: () = { diff --git a/src/test/ui/consts/assert-type-intrinsics.stderr b/src/test/ui/consts/assert-type-intrinsics.stderr index f92f9fda069..70aec91e226 100644 --- a/src/test/ui/consts/assert-type-intrinsics.stderr +++ b/src/test/ui/consts/assert-type-intrinsics.stderr @@ -7,8 +7,8 @@ LL | MaybeUninit::::uninit().assume_init(); error[E0080]: evaluation of constant value failed --> $DIR/assert-type-intrinsics.rs:16:9 | -LL | intrinsics::assert_uninit_valid::<&'static i32>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ aborted execution: attempted to leave type `&i32` uninitialized, which is invalid +LL | intrinsics::assert_mem_uninitialized_valid::<&'static i32>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ aborted execution: attempted to leave type `&i32` uninitialized, which is invalid error[E0080]: evaluation of constant value failed --> $DIR/assert-type-intrinsics.rs:20:9 -- cgit 1.4.1-3-g733a5 From c1181e12243f078b1cc562249569e6766d90f8f6 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 17 Dec 2022 22:32:57 +0000 Subject: Ensure param-env is const before calling eval_to_valtree --- compiler/rustc_const_eval/src/interpret/operand.rs | 6 ++-- src/test/ui/consts/issue-104396.rs | 36 ++++++++++++++++++++++ src/test/ui/consts/issue-104396.stderr | 11 +++++++ 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/test/ui/consts/issue-104396.rs create mode 100644 src/test/ui/consts/issue-104396.stderr (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 221e359d24a..5bc2e3dd4fc 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -569,8 +569,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ty::ConstKind::Unevaluated(uv) => { let instance = self.resolve(uv.def, uv.substs)?; let cid = GlobalId { instance, promoted: None }; - self.ctfe_query(span, |tcx| tcx.eval_to_valtree(self.param_env.and(cid)))? - .unwrap_or_else(|| bug!("unable to create ValTree for {uv:?}")) + self.ctfe_query(span, |tcx| { + tcx.eval_to_valtree(self.param_env.with_const().and(cid)) + })? + .unwrap_or_else(|| bug!("unable to create ValTree for {uv:?}")) } ty::ConstKind::Bound(..) | ty::ConstKind::Infer(..) => { span_bug!(self.cur_span(), "unexpected ConstKind in ctfe: {val:?}") diff --git a/src/test/ui/consts/issue-104396.rs b/src/test/ui/consts/issue-104396.rs new file mode 100644 index 00000000000..315b0cf0fd6 --- /dev/null +++ b/src/test/ui/consts/issue-104396.rs @@ -0,0 +1,36 @@ +// compile-flags: -Zmir-opt-level=3 +// check-pass + +#![feature(generic_const_exprs)] +//~^ WARN the feature `generic_const_exprs` is incomplete + +#[inline(always)] +fn from_fn_1 f32>(mut f: F) -> [f32; N] { + let mut result = [0.0; N]; + let mut i = 0; + while i < N { + result[i] = f(i); + i += 1; + } + result +} + +pub struct TestArray +where + [(); N / 2]:, +{ + array: [f32; N / 2], +} + +impl TestArray +where + [(); N / 2]:, +{ + fn from_fn_2 f32>(f: F) -> Self { + Self { array: from_fn_1(f) } + } +} + +fn main() { + TestArray::<4>::from_fn_2(|i| 0.0); +} diff --git a/src/test/ui/consts/issue-104396.stderr b/src/test/ui/consts/issue-104396.stderr new file mode 100644 index 00000000000..5856bee09a3 --- /dev/null +++ b/src/test/ui/consts/issue-104396.stderr @@ -0,0 +1,11 @@ +warning: the feature `generic_const_exprs` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/issue-104396.rs:4:12 + | +LL | #![feature(generic_const_exprs)] + | ^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #76560 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + -- cgit 1.4.1-3-g733a5 From 0aa4cde747bccb1d1277f9203cfe2021feec341f Mon Sep 17 00:00:00 2001 From: Matthias Krüger Date: Sun, 18 Dec 2022 15:01:26 +0100 Subject: avoid .into() conversion to identical types --- compiler/rustc_builtin_macros/src/test.rs | 3 +-- compiler/rustc_const_eval/src/interpret/operand.rs | 11 ++++------- compiler/rustc_const_eval/src/interpret/operator.rs | 2 +- compiler/rustc_const_eval/src/interpret/place.rs | 2 +- compiler/rustc_infer/src/infer/mod.rs | 2 +- compiler/rustc_middle/src/ty/vtable.rs | 4 ++-- compiler/rustc_mir_build/src/build/expr/as_place.rs | 2 +- compiler/rustc_mir_transform/src/const_prop.rs | 4 ++-- compiler/rustc_parse/src/parser/mod.rs | 8 ++------ compiler/rustc_passes/src/lang_items.rs | 2 -- .../rustc_trait_selection/src/traits/error_reporting/mod.rs | 4 ++-- 11 files changed, 17 insertions(+), 27 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index f5f02fc772a..729ae4071e2 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -239,8 +239,7 @@ pub fn expand_test_or_bench( cx.attr_nested_word(sym::cfg, sym::test, attr_sp), // #[rustc_test_marker = "test_case_sort_key"] cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp), - ] - .into(), + ], // const $ident: test::TestDescAndFn = ast::ItemKind::Const( ast::Defaultness::Final, diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 221e359d24a..f9e3a2bdc06 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -39,7 +39,7 @@ pub enum Immediate { impl From> for Immediate { #[inline(always)] fn from(val: Scalar) -> Self { - Immediate::Scalar(val.into()) + Immediate::Scalar(val) } } @@ -53,7 +53,7 @@ impl Immediate { } pub fn new_slice(val: Scalar, len: u64, cx: &impl HasDataLayout) -> Self { - Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into()) + Immediate::ScalarPair(val, Scalar::from_machine_usize(len, cx)) } pub fn new_dyn_trait( @@ -61,7 +61,7 @@ impl Immediate { vtable: Pointer>, cx: &impl HasDataLayout, ) -> Self { - Immediate::ScalarPair(val.into(), Scalar::from_maybe_pointer(vtable, cx)) + Immediate::ScalarPair(val, Scalar::from_maybe_pointer(vtable, cx)) } #[inline] @@ -341,10 +341,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { alloc_range(b_offset, b_size), /*read_provenance*/ b.is_ptr(), )?; - Some(ImmTy { - imm: Immediate::ScalarPair(a_val.into(), b_val.into()), - layout: mplace.layout, - }) + Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout }) } _ => { // Neither a scalar nor scalar pair. diff --git a/compiler/rustc_const_eval/src/interpret/operator.rs b/compiler/rustc_const_eval/src/interpret/operator.rs index 949f95c5fa8..e8ff70e3a40 100644 --- a/compiler/rustc_const_eval/src/interpret/operator.rs +++ b/compiler/rustc_const_eval/src/interpret/operator.rs @@ -36,7 +36,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { if let Abi::ScalarPair(..) = dest.layout.abi { // We can use the optimized path and avoid `place_field` (which might do // `force_allocation`). - let pair = Immediate::ScalarPair(val.into(), Scalar::from_bool(overflowed).into()); + let pair = Immediate::ScalarPair(val, Scalar::from_bool(overflowed)); self.write_immediate(pair, dest)?; } else { assert!(self.tcx.sess.opts.unstable_opts.randomize_layout); diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index 905eb71bb18..97a73e98abc 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -141,7 +141,7 @@ impl MemPlace { match self.meta { MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)), MemPlaceMeta::Meta(meta) => { - Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx).into(), meta.into()) + Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx), meta) } } } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 996148a7090..268b3bf1dcd 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1920,7 +1920,7 @@ impl<'tcx> TypeTrace<'tcx> { ) -> TypeTrace<'tcx> { TypeTrace { cause: cause.clone(), - values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a.into(), b.into())), + values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)), } } diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index 802925dfb04..f77bd9f0c6f 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -88,8 +88,8 @@ pub(super) fn vtable_allocation_provider<'tcx>( let fn_ptr = Pointer::from(fn_alloc_id); Scalar::from_pointer(fn_ptr, &tcx) } - VtblEntry::MetadataSize => Scalar::from_uint(size, ptr_size).into(), - VtblEntry::MetadataAlign => Scalar::from_uint(align, ptr_size).into(), + VtblEntry::MetadataSize => Scalar::from_uint(size, ptr_size), + VtblEntry::MetadataAlign => Scalar::from_uint(align, ptr_size), VtblEntry::Vacant => continue, VtblEntry::Method(instance) => { // Prepare the fn ptr we write into the vtable. diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index 8a35478dd8b..23a4f85386b 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -356,7 +356,7 @@ impl<'tcx> PlaceBuilder<'tcx> { match self { PlaceBuilder::Local { local, projection } => PlaceBuilder::Local { local: *local, - projection: Vec::from_iter(projection.iter().copied().chain([elem.into()])), + projection: Vec::from_iter(projection.iter().copied().chain([elem])), }, PlaceBuilder::Upvar { upvar, projection } => PlaceBuilder::Upvar { upvar: *upvar, diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index 044b7ce65bd..e384cfe1659 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -701,8 +701,8 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { BinOp::Mul if const_arg.layout.ty.is_integral() && arg_value == 0 => { if let Rvalue::CheckedBinaryOp(_, _) = rvalue { let val = Immediate::ScalarPair( - const_arg.to_scalar().into(), - Scalar::from_bool(false).into(), + const_arg.to_scalar(), + Scalar::from_bool(false), ); this.ecx.write_immediate(val, &dest) } else { diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index bebb012660a..40b88788caa 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -25,7 +25,7 @@ use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::util::case::Case; use rustc_ast::AttrId; use rustc_ast::DUMMY_NODE_ID; -use rustc_ast::{self as ast, AnonConst, AttrStyle, AttrVec, Const, DelimArgs, Extern}; +use rustc_ast::{self as ast, AnonConst, AttrStyle, Const, DelimArgs, Extern}; use rustc_ast::{Async, AttrArgs, AttrArgsEq, Expr, ExprKind, MacDelimiter, Mutability, StrLit}; use rustc_ast::{HasAttrs, HasTokens, Unsafe, Visibility, VisibilityKind}; use rustc_ast_pretty::pprust; @@ -1217,11 +1217,7 @@ impl<'a> Parser<'a> { value: self.mk_expr(blk.span, ExprKind::Block(blk, None)), }; let blk_span = anon_const.value.span; - Ok(self.mk_expr_with_attrs( - span.to(blk_span), - ExprKind::ConstBlock(anon_const), - AttrVec::from(attrs), - )) + Ok(self.mk_expr_with_attrs(span.to(blk_span), ExprKind::ConstBlock(anon_const), attrs)) } /// Parses mutability (`mut` or nothing). diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index 99efed0b7fb..9a40b847d85 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -83,7 +83,6 @@ impl<'tcx> LanguageItemCollector<'tcx> { .map(|p| p.display().to_string()) .collect::>() .join(", ") - .into() }; let first_defined_span = self.tcx.hir().span_if_local(original_def_id); let mut orig_crate_name = Empty; @@ -98,7 +97,6 @@ impl<'tcx> LanguageItemCollector<'tcx> { .map(|p| p.display().to_string()) .collect::>() .join(", ") - .into() }; if first_defined_span.is_none() { orig_crate_name = self.tcx.crate_name(original_def_id.krate); diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index 2dd2c568bab..3b1be1a7f99 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -1735,8 +1735,8 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { values.map(|(_, is_normalized_ty_expected, normalized_ty, expected_ty)| { infer::ValuePairs::Terms(ExpectedFound::new( is_normalized_ty_expected, - normalized_ty.into(), - expected_ty.into(), + normalized_ty, + expected_ty, )) }), err, -- cgit 1.4.1-3-g733a5 From a108d55ce634b6f71462c82966b791f18136360e Mon Sep 17 00:00:00 2001 From: Matthias Krüger Date: Sun, 18 Dec 2022 17:01:58 +0100 Subject: don't restuct references just to reborrow --- compiler/rustc_codegen_llvm/src/back/lto.rs | 2 +- compiler/rustc_codegen_ssa/src/back/link.rs | 2 +- compiler/rustc_codegen_ssa/src/back/linker.rs | 2 +- compiler/rustc_const_eval/src/interpret/cast.rs | 2 +- compiler/rustc_expand/src/mbe/macro_check.rs | 4 ++-- compiler/rustc_expand/src/mbe/macro_rules.rs | 2 +- compiler/rustc_hir_typeck/src/demand.rs | 10 +++++----- compiler/rustc_hir_typeck/src/expr.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs | 2 +- compiler/rustc_incremental/src/assert_dep_graph.rs | 2 +- compiler/rustc_infer/src/traits/project.rs | 2 +- compiler/rustc_lint/src/context.rs | 10 +++++----- compiler/rustc_lint/src/unused.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 ++-- compiler/rustc_middle/src/mir/tcx.rs | 2 +- compiler/rustc_middle/src/ty/flags.rs | 4 ++-- compiler/rustc_middle/src/ty/relate.rs | 2 +- compiler/rustc_mir_build/src/build/matches/test.rs | 17 ++++++++--------- compiler/rustc_passes/src/hir_stats.rs | 4 ++-- compiler/rustc_resolve/src/build_reduced_graph.rs | 2 +- compiler/rustc_session/src/session.rs | 2 +- .../src/traits/error_reporting/mod.rs | 2 +- 22 files changed, 41 insertions(+), 42 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index e20dc906bce..6c0faf37a63 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -425,7 +425,7 @@ fn thin_lto( info!("going for that thin, thin LTO"); let green_modules: FxHashMap<_, _> = - cached_modules.iter().map(|&(_, ref wp)| (wp.cgu_name.clone(), wp.clone())).collect(); + cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect(); let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len(); let mut thin_buffers = Vec::with_capacity(modules.len()); diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index fe2e4b36cd0..a1c77ec0cfc 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -722,7 +722,7 @@ fn link_natively<'a>( linker::disable_localization(&mut cmd); - for &(ref k, ref v) in sess.target.link_env.as_ref() { + for (k, v) in sess.target.link_env.as_ref() { cmd.env(k.as_ref(), v.as_ref()); } for k in sess.target.link_env_remove.as_ref() { diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs index f087d903e55..0268659d3b9 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker.rs @@ -108,7 +108,7 @@ pub fn get_linker<'a>( if sess.target.is_like_msvc { if let Some(ref tool) = msvc_tool { cmd.args(tool.args()); - for &(ref k, ref v) in tool.env() { + for (k, v) in tool.env() { if k == "PATH" { new_path.extend(env::split_paths(v)); msvc_changed_path = true; diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index b1fdeb01b10..986b6d65530 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -332,7 +332,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { Immediate::new_slice(ptr, length.eval_usize(*self.tcx, self.param_env), self); self.write_immediate(val, dest) } - (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => { + (ty::Dynamic(data_a, ..), ty::Dynamic(data_b, ..)) => { let val = self.read_immediate(src)?; if data_a.principal() == data_b.principal() { // A NOP cast that doesn't actually change anything, should be allowed even with mismatching vtables. diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 8994a2f7891..0b8847f827d 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -468,7 +468,7 @@ fn check_nested_occurrences( // We check that the meta-variable is correctly used. check_occurrences(sess, node_id, tt, macros, binders, ops, valid); } - (NestedMacroState::MacroName, &TokenTree::Delimited(_, ref del)) + (NestedMacroState::MacroName, TokenTree::Delimited(_, del)) if del.delim == Delimiter::Parenthesis => { state = NestedMacroState::MacroNameParen; @@ -483,7 +483,7 @@ fn check_nested_occurrences( valid, ); } - (NestedMacroState::MacroNameParen, &TokenTree::Delimited(_, ref del)) + (NestedMacroState::MacroNameParen, TokenTree::Delimited(_, del)) if del.delim == Delimiter::Brace => { state = NestedMacroState::Empty; diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 2dbb90e2190..320c533a66e 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -792,7 +792,7 @@ impl<'tt> FirstSets<'tt> { TokenTree::Sequence(sp, ref seq_rep) => { let subfirst_owned; let subfirst = match self.first.get(&sp.entire()) { - Some(&Some(ref subfirst)) => subfirst, + Some(Some(subfirst)) => subfirst, Some(&None) => { subfirst_owned = self.first(&seq_rep.tts); &subfirst_owned diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 6763e06c0cf..87abd01c7fd 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -1275,7 +1275,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; match (&expected_ty.kind(), &checked_ty.kind()) { - (&ty::Int(ref exp), &ty::Int(ref found)) => { + (ty::Int(exp), ty::Int(found)) => { let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width()) { (Some(exp), Some(found)) if exp < found => (true, false), @@ -1288,7 +1288,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible); true } - (&ty::Uint(ref exp), &ty::Uint(ref found)) => { + (ty::Uint(exp), ty::Uint(found)) => { let (f2e_is_fallible, e2f_is_fallible) = match (exp.bit_width(), found.bit_width()) { (Some(exp), Some(found)) if exp < found => (true, false), @@ -1321,7 +1321,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { suggest_to_change_suffix_or_into(err, f2e_is_fallible, e2f_is_fallible); true } - (&ty::Float(ref exp), &ty::Float(ref found)) => { + (ty::Float(exp), ty::Float(found)) => { if found.bit_width() < exp.bit_width() { suggest_to_change_suffix_or_into(err, false, true); } else if literal_is_ty_suffixed(expr) { @@ -1357,7 +1357,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } true } - (&ty::Float(ref exp), &ty::Uint(ref found)) => { + (ty::Float(exp), ty::Uint(found)) => { // if `found` is `None` (meaning found is `usize`), don't suggest `.into()` if exp.bit_width() > found.bit_width().unwrap_or(256) { err.multipart_suggestion_verbose( @@ -1386,7 +1386,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } true } - (&ty::Float(ref exp), &ty::Int(ref found)) => { + (ty::Float(exp), ty::Int(found)) => { // if `found` is `None` (meaning found is `isize`), don't suggest `.into()` if exp.bit_width() > found.bit_width().unwrap_or(256) { err.multipart_suggestion_verbose( diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 866090260b2..edbbb7272ac 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1874,7 +1874,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // I don't use 'is_range_literal' because only double-sided, half-open ranges count. if let ExprKind::Struct( QPath::LangItem(LangItem::Range, ..), - &[ref range_start, ref range_end], + [range_start, range_end], _, ) = last_expr_field.expr.kind && let variant_field = diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 407d6ac8544..ca4c50c49aa 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -754,7 +754,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return true } } - &hir::FnRetTy::Return(ref ty) => { + hir::FnRetTy::Return(ty) => { // Only point to return type if the expected type is the return type, as if they // are not, the expectation must have been caused by something else. debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind); diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 69e482ce854..b4bf9f4bcc7 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -249,7 +249,7 @@ fn dump_graph(query: &DepGraphQuery) { // dump a .txt file with just the edges: let txt_path = format!("{}.txt", path); let mut file = BufWriter::new(File::create(&txt_path).unwrap()); - for &(ref source, ref target) in &edges { + for (source, target) in &edges { write!(file, "{:?} -> {:?}\n", source, target).unwrap(); } } diff --git a/compiler/rustc_infer/src/traits/project.rs b/compiler/rustc_infer/src/traits/project.rs index aade57be9fe..ac455055b43 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -200,7 +200,7 @@ impl<'tcx> ProjectionCache<'_, 'tcx> { pub fn complete(&mut self, key: ProjectionCacheKey<'tcx>, result: EvaluationResult) { let mut map = self.map(); match map.get(&key) { - Some(&ProjectionCacheEntry::NormalizedTy { ref ty, complete: _ }) => { + Some(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => { info!("ProjectionCacheEntry::complete({:?}) - completing {:?}", key, ty); let mut ty = ty.clone(); if result.must_apply_considering_regions() { diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 40b2588388d..0417f375588 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -438,18 +438,18 @@ impl LintStore { return CheckLintNameResult::Tool(Ok(&lint_ids)); } }, - Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))), + Some(Id(id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))), // If the lint was registered as removed or renamed by the lint tool, we don't need // to treat tool_lints and rustc lints different and can use the code below. _ => {} } } match self.by_name.get(&complete_name) { - Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning( + Some(Renamed(new_name, _)) => CheckLintNameResult::Warning( format!("lint `{}` has been renamed to `{}`", complete_name, new_name), Some(new_name.to_owned()), ), - Some(&Removed(ref reason)) => CheckLintNameResult::Warning( + Some(Removed(reason)) => CheckLintNameResult::Warning( format!("lint `{}` has been removed: {}", complete_name, reason), None, ), @@ -470,7 +470,7 @@ impl LintStore { CheckLintNameResult::Ok(&lint_ids) } }, - Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)), + Some(Id(id)) => CheckLintNameResult::Ok(slice::from_ref(id)), Some(&Ignored) => CheckLintNameResult::Ok(&[]), } } @@ -513,7 +513,7 @@ impl LintStore { CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name))) } }, - Some(&Id(ref id)) => { + Some(Id(id)) => { CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name))) } Some(other) => { diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index d628a18dd01..3b8df61a0ea 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1279,7 +1279,7 @@ impl UnusedImportBraces { fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) { if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { // Recursively check nested UseTrees - for &(ref tree, _) in items { + for (tree, _) in items { self.check_use_tree(cx, tree, item); } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 856f5bc4645..96f15a6f758 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1849,7 +1849,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // the assumption that they are numbered 1 to n. // FIXME (#2166): This is not nearly enough to support correct versioning // but is enough to get transitive crate dependencies working. - self.lazy_array(deps.iter().map(|&(_, ref dep)| dep)) + self.lazy_array(deps.iter().map(|(_, dep)| dep)) } fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option)> { @@ -1986,7 +1986,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.lazy_array( exported_symbols .iter() - .filter(|&&(ref exported_symbol, _)| match *exported_symbol { + .filter(|&(exported_symbol, _)| match *exported_symbol { ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, _ => true, }) diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index e3ca1f41d7e..1e289fc4abe 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -235,7 +235,7 @@ impl<'tcx> Operand<'tcx> { { match self { &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty, - &Operand::Constant(ref c) => c.literal.ty(), + Operand::Constant(c) => c.literal.ty(), } } } diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index d283ccc3ad8..042b89bc4b0 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -95,7 +95,7 @@ impl FlagComputation { self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); } - &ty::Generator(_, ref substs, _) => { + ty::Generator(_, substs, _) => { let substs = substs.as_generator(); let should_remove_further_specializable = !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); @@ -186,7 +186,7 @@ impl FlagComputation { &ty::Slice(tt) => self.add_ty(tt), - &ty::RawPtr(ref m) => { + ty::RawPtr(m) => { self.add_ty(m.ty); } diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index c4116558bd2..4d34ca3d66b 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -428,7 +428,7 @@ pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>( Ok(a) } - (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a), + (ty::Param(a_p), ty::Param(b_p)) if a_p.index == b_p.index => Ok(a), (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a), diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index 65a027111d7..6c10704c5db 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -551,16 +551,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // // FIXME(#29623) we could use PatKind::Range to rule // things out here, in some cases. - ( - &TestKind::SwitchInt { switch_ty: _, ref options }, - &PatKind::Constant { ref value }, - ) if is_switch_ty(match_pair.pattern.ty) => { + (TestKind::SwitchInt { switch_ty: _, options }, PatKind::Constant { value }) + if is_switch_ty(match_pair.pattern.ty) => + { let index = options.get_index_of(value).unwrap(); self.candidate_without_match_pair(match_pair_index, candidate); Some(index) } - (&TestKind::SwitchInt { switch_ty: _, ref options }, &PatKind::Range(ref range)) => { + (TestKind::SwitchInt { switch_ty: _, options }, PatKind::Range(range)) => { let not_contained = self.values_not_contained_in_range(&*range, options).unwrap_or(false); @@ -578,7 +577,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ( &TestKind::Len { len: test_len, op: BinOp::Eq }, - &PatKind::Slice { ref prefix, ref slice, ref suffix }, + PatKind::Slice { prefix, slice, suffix }, ) => { let pat_len = (prefix.len() + suffix.len()) as u64; match (test_len.cmp(&pat_len), slice) { @@ -615,7 +614,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ( &TestKind::Len { len: test_len, op: BinOp::Ge }, - &PatKind::Slice { ref prefix, ref slice, ref suffix }, + PatKind::Slice { prefix, slice, suffix }, ) => { // the test is `$actual_len >= test_len` let pat_len = (prefix.len() + suffix.len()) as u64; @@ -651,7 +650,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - (&TestKind::Range(ref test), &PatKind::Range(ref pat)) => { + (TestKind::Range(test), PatKind::Range(pat)) => { use std::cmp::Ordering::*; if test == pat { @@ -678,7 +677,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { no_overlap } - (&TestKind::Range(ref range), &PatKind::Constant { value }) => { + (TestKind::Range(range), &PatKind::Constant { value }) => { if let Some(false) = self.const_range_contains(&*range, value) { // `value` is not contained in the testing range, // so `value` can be matched only if this test fails. diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index a7854cd4998..272386f313e 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -121,7 +121,7 @@ impl<'k> StatCollector<'k> { fn print(&self, title: &str, prefix: &str) { let mut nodes: Vec<_> = self.nodes.iter().collect(); - nodes.sort_by_key(|&(_, ref node)| node.stats.count * node.stats.size); + nodes.sort_by_key(|(_, node)| node.stats.count * node.stats.size); let total_size = nodes.iter().map(|(_, node)| node.stats.count * node.stats.size).sum(); @@ -147,7 +147,7 @@ impl<'k> StatCollector<'k> { ); if !node.subnodes.is_empty() { let mut subnodes: Vec<_> = node.subnodes.iter().collect(); - subnodes.sort_by_key(|&(_, ref subnode)| subnode.count * subnode.size); + subnodes.sort_by_key(|(_, subnode)| subnode.count * subnode.size); for (label, subnode) in subnodes { let size = subnode.count * subnode.size; diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index f4a6a08df1c..cf635996268 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -576,7 +576,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { // Ensure there is at most one `self` in the list let self_spans = items .iter() - .filter_map(|&(ref use_tree, _)| { + .filter_map(|(use_tree, _)| { if let ast::UseTreeKind::Simple(..) = use_tree.kind { if use_tree.ident().name == kw::SelfLower { return Some(use_tree.span); diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index fdd883fbeed..01a9b100088 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1323,7 +1323,7 @@ pub fn build_session( let warnings_allow = sopts .lint_opts .iter() - .rfind(|&&(ref key, _)| *key == "warnings") + .rfind(|&(key, _)| *key == "warnings") .map_or(false, |&(_, level)| level == lint::Allow); let cap_lints_allow = sopts.lint_cap.map_or(false, |cap| cap == lint::Allow); let can_emit_warnings = !(warnings_allow || cap_lints_allow); diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index 2dd2c568bab..d0c842a0b89 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -226,7 +226,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { let arg_length = arguments.len(); let distinct = matches!(other, &[ArgKind::Tuple(..)]); match (arg_length, arguments.get(0)) { - (1, Some(&ArgKind::Tuple(_, ref fields))) => { + (1, Some(ArgKind::Tuple(_, fields))) => { format!("a single {}-tuple as argument", fields.len()) } _ => format!( -- cgit 1.4.1-3-g733a5 From cb2c7bb833f439c224457442c83c3dfcba1709d6 Mon Sep 17 00:00:00 2001 From: Jakob Degen Date: Wed, 21 Dec 2022 10:30:38 -0800 Subject: Clarify that raw retags are not permitted in Mir --- compiler/rustc_const_eval/src/transform/validate.rs | 9 ++++++--- compiler/rustc_middle/src/mir/syntax.rs | 7 +++++-- compiler/rustc_mir_build/src/build/custom/parse/instruction.rs | 3 --- library/core/src/intrinsics/mir.rs | 1 - .../mir-opt/building/custom/references.immut_ref.built.after.mir | 7 +++---- .../mir-opt/building/custom/references.mut_ref.built.after.mir | 7 +++---- src/test/mir-opt/building/custom/references.rs | 2 -- 7 files changed, 17 insertions(+), 19 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index bb897b95b2c..eb247a4cebe 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -9,8 +9,8 @@ use rustc_middle::mir::visit::{PlaceContext, Visitor}; use rustc_middle::mir::{ traversal, AggregateKind, BasicBlock, BinOp, Body, BorrowKind, CastKind, CopyNonOverlapping, Local, Location, MirPass, MirPhase, NonDivergingIntrinsic, Operand, Place, PlaceElem, PlaceRef, - ProjectionElem, RuntimePhase, Rvalue, SourceScope, Statement, StatementKind, Terminator, - TerminatorKind, UnOp, START_BLOCK, + ProjectionElem, RetagKind, RuntimePhase, Rvalue, SourceScope, Statement, StatementKind, + Terminator, TerminatorKind, UnOp, START_BLOCK, }; use rustc_middle::ty::{self, InstanceDef, ParamEnv, Ty, TyCtxt, TypeVisitable}; use rustc_mir_dataflow::impls::MaybeStorageLive; @@ -667,10 +667,13 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.fail(location, "`Deinit`is not allowed until deaggregation"); } } - StatementKind::Retag(_, _) => { + StatementKind::Retag(kind, _) => { // FIXME(JakobDegen) The validator should check that `self.mir_phase < // DropsLowered`. However, this causes ICEs with generation of drop shims, which // seem to fail to set their `MirPhase` correctly. + if *kind == RetagKind::Raw { + self.fail(location, "explicit `RetagKind::Raw` is forbidden"); + } } StatementKind::StorageLive(..) | StatementKind::StorageDead(..) diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 99e59c770d7..bbb8148f5bc 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -320,8 +320,11 @@ pub enum StatementKind<'tcx> { /// for /// more details. /// - /// For code that is not specific to stacked borrows, you should consider retags to read - /// and modify the place in an opaque way. + /// For code that is not specific to stacked borrows, you should consider retags to read and + /// modify the place in an opaque way. + /// + /// Explicit `RetagKind::Raw` is not permitted - it is implicit as a part of + /// `Rvalue::AddressOf`. Retag(RetagKind, Box>), /// Encodes a user's type ascription. These need to be preserved diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs index 7c39a93a8eb..dca4906c07d 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs @@ -15,9 +15,6 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { @call("mir_retag", args) => { Ok(StatementKind::Retag(RetagKind::Default, Box::new(self.parse_place(args[0])?))) }, - @call("mir_retag_raw", args) => { - Ok(StatementKind::Retag(RetagKind::Raw, Box::new(self.parse_place(args[0])?))) - }, @call("mir_set_discriminant", args) => { let place = self.parse_place(args[0])?; let var = self.parse_integer_literal(args[1])? as u32; diff --git a/library/core/src/intrinsics/mir.rs b/library/core/src/intrinsics/mir.rs index e08a15571fc..9e7099ddfd1 100644 --- a/library/core/src/intrinsics/mir.rs +++ b/library/core/src/intrinsics/mir.rs @@ -259,7 +259,6 @@ define!("mir_drop", fn Drop(place: T, goto: BasicBlock)); define!("mir_drop_and_replace", fn DropAndReplace(place: T, value: T, goto: BasicBlock)); define!("mir_call", fn Call(place: T, goto: BasicBlock, call: T)); define!("mir_retag", fn Retag(place: T)); -define!("mir_retag_raw", fn RetagRaw(place: T)); define!("mir_move", fn Move(place: T) -> T); define!("mir_static", fn Static(s: T) -> &'static T); define!("mir_static_mut", fn StaticMut(s: T) -> *mut T); diff --git a/src/test/mir-opt/building/custom/references.immut_ref.built.after.mir b/src/test/mir-opt/building/custom/references.immut_ref.built.after.mir index 4d38d45c0f4..f5ee1126235 100644 --- a/src/test/mir-opt/building/custom/references.immut_ref.built.after.mir +++ b/src/test/mir-opt/building/custom/references.immut_ref.built.after.mir @@ -6,9 +6,8 @@ fn immut_ref(_1: &i32) -> &i32 { bb0: { _2 = &raw const (*_1); // scope 0 at $DIR/references.rs:+5:13: +5:29 - Retag([raw] _2); // scope 0 at $DIR/references.rs:+6:13: +6:24 - _0 = &(*_2); // scope 0 at $DIR/references.rs:+7:13: +7:23 - Retag(_0); // scope 0 at $DIR/references.rs:+8:13: +8:23 - return; // scope 0 at $DIR/references.rs:+9:13: +9:21 + _0 = &(*_2); // scope 0 at $DIR/references.rs:+6:13: +6:23 + Retag(_0); // scope 0 at $DIR/references.rs:+7:13: +7:23 + return; // scope 0 at $DIR/references.rs:+8:13: +8:21 } } diff --git a/src/test/mir-opt/building/custom/references.mut_ref.built.after.mir b/src/test/mir-opt/building/custom/references.mut_ref.built.after.mir index 01bc8a9cd35..8e2ffc33b1a 100644 --- a/src/test/mir-opt/building/custom/references.mut_ref.built.after.mir +++ b/src/test/mir-opt/building/custom/references.mut_ref.built.after.mir @@ -6,9 +6,8 @@ fn mut_ref(_1: &mut i32) -> &mut i32 { bb0: { _2 = &raw mut (*_1); // scope 0 at $DIR/references.rs:+5:13: +5:33 - Retag([raw] _2); // scope 0 at $DIR/references.rs:+6:13: +6:24 - _0 = &mut (*_2); // scope 0 at $DIR/references.rs:+7:13: +7:26 - Retag(_0); // scope 0 at $DIR/references.rs:+8:13: +8:23 - return; // scope 0 at $DIR/references.rs:+9:13: +9:21 + _0 = &mut (*_2); // scope 0 at $DIR/references.rs:+6:13: +6:26 + Retag(_0); // scope 0 at $DIR/references.rs:+7:13: +7:23 + return; // scope 0 at $DIR/references.rs:+8:13: +8:21 } } diff --git a/src/test/mir-opt/building/custom/references.rs b/src/test/mir-opt/building/custom/references.rs index c93f6ec624b..a1c896de04c 100644 --- a/src/test/mir-opt/building/custom/references.rs +++ b/src/test/mir-opt/building/custom/references.rs @@ -12,7 +12,6 @@ pub fn mut_ref(x: &mut i32) -> &mut i32 { { t = addr_of_mut!(*x); - RetagRaw(t); RET = &mut *t; Retag(RET); Return() @@ -28,7 +27,6 @@ pub fn immut_ref(x: &i32) -> &i32 { { t = addr_of!(*x); - RetagRaw(t); RET = & *t; Retag(RET); Return() -- cgit 1.4.1-3-g733a5 From 7c4c62047504aff1e17d4b2686116fb4de04797c Mon Sep 17 00:00:00 2001 From: Jakob Degen Date: Wed, 21 Dec 2022 11:46:13 -0800 Subject: Forbid `RetagKind::TwoPhase` as well --- compiler/rustc_const_eval/src/transform/validate.rs | 4 ++-- compiler/rustc_middle/src/mir/syntax.rs | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index eb247a4cebe..94e1b95a0eb 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -671,8 +671,8 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { // FIXME(JakobDegen) The validator should check that `self.mir_phase < // DropsLowered`. However, this causes ICEs with generation of drop shims, which // seem to fail to set their `MirPhase` correctly. - if *kind == RetagKind::Raw { - self.fail(location, "explicit `RetagKind::Raw` is forbidden"); + if *kind == RetagKind::Raw || *kind == RetagKind::TwoPhase { + self.fail(location, format!("explicit `{:?}` is forbidden", kind)); } } StatementKind::StorageLive(..) diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index bbb8148f5bc..bb03359b138 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -323,8 +323,7 @@ pub enum StatementKind<'tcx> { /// For code that is not specific to stacked borrows, you should consider retags to read and /// modify the place in an opaque way. /// - /// Explicit `RetagKind::Raw` is not permitted - it is implicit as a part of - /// `Rvalue::AddressOf`. + /// Only `RetagKind::Default` and `RetagKind::FnEntry` are permitted. Retag(RetagKind, Box>), /// Encodes a user's type ascription. These need to be preserved -- cgit 1.4.1-3-g733a5 From 0229281d03d92eec1b167377fec1e9978af1f704 Mon Sep 17 00:00:00 2001 From: Jakob Degen Date: Wed, 21 Dec 2022 15:22:17 -0800 Subject: Don't run `Drop` terminators on types that do not have drop glue in const eval --- compiler/rustc_const_eval/src/interpret/terminator.rs | 15 ++++++++++++--- compiler/rustc_middle/src/mir/syntax.rs | 15 +++++++-------- .../tests/fail/stacked_borrows/drop_in_place_retag.rs | 4 ++-- 3 files changed, 21 insertions(+), 13 deletions(-) (limited to 'compiler/rustc_const_eval/src') diff --git a/compiler/rustc_const_eval/src/interpret/terminator.rs b/compiler/rustc_const_eval/src/interpret/terminator.rs index 0e7ffcdffc9..550c7a44c41 100644 --- a/compiler/rustc_const_eval/src/interpret/terminator.rs +++ b/compiler/rustc_const_eval/src/interpret/terminator.rs @@ -119,11 +119,20 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } Drop { place, target, unwind } => { + let frame = self.frame(); + let ty = place.ty(&frame.body.local_decls, *self.tcx).ty; + let ty = self.subst_from_frame_and_normalize_erasing_regions(frame, ty)?; + let instance = Instance::resolve_drop_in_place(*self.tcx, ty); + if let ty::InstanceDef::DropGlue(_, None) = instance.def { + // This is the branch we enter if and only if the dropped type has no drop glue + // whatsoever. This can happen as a result of monomorphizing a drop of a + // generic. In order to make sure that generic and non-generic code behaves + // roughly the same (and in keeping with Mir semantics) we do nothing here. + self.go_to_block(target); + return Ok(()); + } let place = self.eval_place(place)?; - let ty = place.layout.ty; trace!("TerminatorKind::drop: {:?}, type {}", place, ty); - - let instance = Instance::resolve_drop_in_place(*self.tcx, ty); self.drop_in_place(&place, instance, target, unwind)?; } diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 99e59c770d7..6e7d84410da 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -562,14 +562,13 @@ pub enum TerminatorKind<'tcx> { Unreachable, /// The behavior of this statement differs significantly before and after drop elaboration. - /// After drop elaboration, `Drop` executes the drop glue for the specified place, after which - /// it continues execution/unwinds at the given basic blocks. It is possible that executing drop - /// glue is special - this would be part of Rust's memory model. (**FIXME**: due we have an - /// issue tracking if drop glue has any interesting semantics in addition to those of a function - /// call?) - /// - /// `Drop` before drop elaboration is a *conditional* execution of the drop glue. Specifically, the - /// `Drop` will be executed if... + /// + /// After drop elaboration: `Drop` terminators are a complete nop for types that have no drop + /// glue. For other types, `Drop` terminators behave exactly like a call to + /// `core::mem::drop_in_place` with a pointer to the given place. + /// + /// `Drop` before drop elaboration is a *conditional* execution of the drop glue. Specifically, + /// the `Drop` will be executed if... /// /// **Needs clarification**: End of that sentence. This in effect should document the exact /// behavior of drop elaboration. The following sounds vaguely right, but I'm not quite sure: diff --git a/src/tools/miri/tests/fail/stacked_borrows/drop_in_place_retag.rs b/src/tools/miri/tests/fail/stacked_borrows/drop_in_place_retag.rs index e7d256b686d..8180e2f03a7 100644 --- a/src/tools/miri/tests/fail/stacked_borrows/drop_in_place_retag.rs +++ b/src/tools/miri/tests/fail/stacked_borrows/drop_in_place_retag.rs @@ -1,5 +1,5 @@ -//! Test that drop_in_place mutably retags the entire place, -//! ensuring it is writeable +//! Test that drop_in_place mutably retags the entire place, even for a type that does not need +//! dropping, ensuring among other things that it is writeable //@error-pattern: /retag .* for Unique permission .* only grants SharedReadOnly permission/ -- cgit 1.4.1-3-g733a5