diff options
Diffstat (limited to 'compiler/rustc_middle/src/mir/mod.rs')
-rw-r--r-- | compiler/rustc_middle/src/mir/mod.rs | 221 |
1 files changed, 106 insertions, 115 deletions
diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 28c505878..9ef3a1b30 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -12,7 +12,7 @@ use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::visit::TypeVisitableExt; use crate::ty::{self, List, Ty, TyCtxt}; use crate::ty::{AdtDef, InstanceDef, ScalarInt, UserTypeAnnotationIndex}; -use crate::ty::{GenericArg, InternalSubsts, SubstsRef}; +use crate::ty::{GenericArg, GenericArgs, GenericArgsRef}; use rustc_data_structures::captures::Captures; use rustc_errors::{DiagnosticArgValue, DiagnosticMessage, ErrorGuaranteed, IntoDiagnosticArg}; @@ -619,7 +619,7 @@ impl<D: TyDecoder, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> { let val = T::decode(d); ClearCrossCrate::Set(val) } - tag => panic!("Invalid tag for ClearCrossCrate: {:?}", tag), + tag => panic!("Invalid tag for ClearCrossCrate: {tag:?}"), } } } @@ -706,9 +706,7 @@ pub enum BindingForm<'tcx> { RefForGuard, } -TrivialTypeTraversalAndLiftImpls! { - BindingForm<'tcx>, -} +TrivialTypeTraversalAndLiftImpls! { BindingForm<'tcx> } mod binding_form_impl { use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; @@ -1048,12 +1046,12 @@ pub enum VarDebugInfoContents<'tcx> { impl<'tcx> Debug for VarDebugInfoContents<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { match self { - VarDebugInfoContents::Const(c) => write!(fmt, "{}", c), - VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p), + VarDebugInfoContents::Const(c) => write!(fmt, "{c}"), + VarDebugInfoContents::Place(p) => write!(fmt, "{p:?}"), VarDebugInfoContents::Composite { ty, fragments } => { - write!(fmt, "{:?}{{ ", ty)?; + write!(fmt, "{ty:?}{{ ")?; for f in fragments.iter() { - write!(fmt, "{:?}, ", f)?; + write!(fmt, "{f:?}, ")?; } write!(fmt, "}}") } @@ -1111,10 +1109,6 @@ pub struct VarDebugInfo<'tcx> { /// originated from (starting from 1). Note, if MIR inlining is enabled, then this is the /// argument number in the original function before it was inlined. pub argument_index: Option<u16>, - - /// The data represents `name` dereferenced `references` times, - /// and not the direct value. - pub references: u8, } /////////////////////////////////////////////////////////////////////////// @@ -1317,55 +1311,47 @@ impl<O> AssertKind<O> { match self { BoundsCheck { ref len, ref index } => write!( f, - "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}", - len, index + "\"index out of bounds: the length is {{}} but the index is {{}}\", {len:?}, {index:?}" ), OverflowNeg(op) => { - write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op) + write!(f, "\"attempt to negate `{{}}`, which would overflow\", {op:?}") } - DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op), + DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {op:?}"), RemainderByZero(op) => write!( f, - "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}", - op + "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {op:?}" ), Overflow(BinOp::Add, l, r) => write!( f, - "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} + {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Sub, l, r) => write!( f, - "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} - {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Mul, l, r) => write!( f, - "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} * {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Div, l, r) => write!( f, - "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute `{{}} / {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Rem, l, r) => write!( f, - "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}", - l, r + "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {l:?}, {r:?}" ), Overflow(BinOp::Shr, _, r) => { - write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r) + write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {r:?}") } Overflow(BinOp::Shl, _, r) => { - write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r) + write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {r:?}") } MisalignedPointerDereference { required, found } => { write!( f, - "\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {:?}, {:?}", - required, found + "\"misaligned pointer dereference: address must be a multiple of {{}} but is {{}}\", {required:?}, {found:?}" ) } _ => write!(f, "\"{}\"", self.description()), @@ -1461,9 +1447,9 @@ impl Debug for Statement<'_> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::StatementKind::*; match self.kind { - Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv), + Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"), FakeRead(box (ref cause, ref place)) => { - write!(fmt, "FakeRead({:?}, {:?})", cause, place) + write!(fmt, "FakeRead({cause:?}, {place:?})") } Retag(ref kind, ref place) => write!( fmt, @@ -1476,20 +1462,20 @@ impl Debug for Statement<'_> { }, place, ), - StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place), - StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place), + StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"), + StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"), SetDiscriminant { ref place, variant_index } => { - write!(fmt, "discriminant({:?}) = {:?}", place, variant_index) + write!(fmt, "discriminant({place:?}) = {variant_index:?}") } - Deinit(ref place) => write!(fmt, "Deinit({:?})", place), + Deinit(ref place) => write!(fmt, "Deinit({place:?})"), PlaceMention(ref place) => { - write!(fmt, "PlaceMention({:?})", place) + write!(fmt, "PlaceMention({place:?})") } AscribeUserType(box (ref place, ref c_ty), ref variance) => { - write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty) + write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})") } Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => { - write!(fmt, "Coverage::{:?} for {:?}", kind, rgn) + write!(fmt, "Coverage::{kind:?} for {rgn:?}") } Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind), Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"), @@ -1602,14 +1588,13 @@ impl<'tcx> Place<'tcx> { self.projection.iter().any(|elem| elem.is_indirect()) } - /// If MirPhase >= Derefered and if projection contains Deref, - /// It's guaranteed to be in the first place - pub fn has_deref(&self) -> bool { - // To make sure this is not accidentally used in wrong mir phase - debug_assert!( - self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref) - ); - self.projection.first() == Some(&PlaceElem::Deref) + /// Returns `true` if this `Place`'s first projection is `Deref`. + /// + /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later, + /// `Deref` projections can only occur as the first projection. In that case this method + /// is equivalent to `is_indirect`, but faster. + pub fn is_indirect_first_projection(&self) -> bool { + self.as_ref().is_indirect_first_projection() } /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or @@ -1682,9 +1667,16 @@ impl<'tcx> PlaceRef<'tcx> { self.projection.iter().any(|elem| elem.is_indirect()) } - /// If MirPhase >= Derefered and if projection contains Deref, - /// It's guaranteed to be in the first place - pub fn has_deref(&self) -> bool { + /// Returns `true` if this `Place`'s first projection is `Deref`. + /// + /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later, + /// `Deref` projections can only occur as the first projection. In that case this method + /// is equivalent to `is_indirect`, but faster. + pub fn is_indirect_first_projection(&self) -> bool { + // To make sure this is not accidentally used in wrong mir phase + debug_assert!( + self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref) + ); self.projection.first() == Some(&PlaceElem::Deref) } @@ -1769,13 +1761,13 @@ impl Debug for Place<'_> { for elem in self.projection.iter() { match elem { ProjectionElem::OpaqueCast(ty) => { - write!(fmt, " as {})", ty)?; + write!(fmt, " as {ty})")?; } ProjectionElem::Downcast(Some(name), _index) => { - write!(fmt, " as {})", name)?; + write!(fmt, " as {name})")?; } ProjectionElem::Downcast(None, index) => { - write!(fmt, " as variant#{:?})", index)?; + write!(fmt, " as variant#{index:?})")?; } ProjectionElem::Deref => { write!(fmt, ")")?; @@ -1784,25 +1776,25 @@ impl Debug for Place<'_> { write!(fmt, ".{:?}: {:?})", field.index(), ty)?; } ProjectionElem::Index(ref index) => { - write!(fmt, "[{:?}]", index)?; + write!(fmt, "[{index:?}]")?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => { - write!(fmt, "[{:?} of {:?}]", offset, min_length)?; + write!(fmt, "[{offset:?} of {min_length:?}]")?; } ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => { - write!(fmt, "[-{:?} of {:?}]", offset, min_length)?; + write!(fmt, "[-{offset:?} of {min_length:?}]")?; } ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => { - write!(fmt, "[{:?}:]", from)?; + write!(fmt, "[{from:?}:]")?; } ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => { - write!(fmt, "[:-{:?}]", to)?; + write!(fmt, "[:-{to:?}]")?; } ProjectionElem::Subslice { from, to, from_end: true } => { - write!(fmt, "[{:?}:-{:?}]", from, to)?; + write!(fmt, "[{from:?}:-{to:?}]")?; } ProjectionElem::Subslice { from, to, from_end: false } => { - write!(fmt, "[{:?}..{:?}]", from, to)?; + write!(fmt, "[{from:?}..{to:?}]")?; } } } @@ -1896,24 +1888,24 @@ impl<'tcx> Debug for Operand<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { use self::Operand::*; match *self { - Constant(ref a) => write!(fmt, "{:?}", a), - Copy(ref place) => write!(fmt, "{:?}", place), - Move(ref place) => write!(fmt, "move {:?}", place), + Constant(ref a) => write!(fmt, "{a:?}"), + Copy(ref place) => write!(fmt, "{place:?}"), + Move(ref place) => write!(fmt, "move {place:?}"), } } } impl<'tcx> Operand<'tcx> { /// Convenience helper to make a constant that refers to the fn - /// with given `DefId` and substs. Since this is used to synthesize + /// with given `DefId` and args. Since this is used to synthesize /// MIR, assumes `user_ty` is None. pub fn function_handle( tcx: TyCtxt<'tcx>, def_id: DefId, - substs: impl IntoIterator<Item = GenericArg<'tcx>>, + args: impl IntoIterator<Item = GenericArg<'tcx>>, span: Span, ) -> Self { - let ty = Ty::new_fn_def(tcx, def_id, substs); + let ty = Ty::new_fn_def(tcx, def_id, args); Operand::Constant(Box::new(Constant { span, user_ty: None, @@ -1937,11 +1929,11 @@ impl<'tcx> Operand<'tcx> { let param_env_and_ty = ty::ParamEnv::empty().and(ty); let type_size = tcx .layout_of(param_env_and_ty) - .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e)) + .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}")) .size; let scalar_size = match val { Scalar::Int(int) => int.size(), - _ => panic!("Invalid scalar type {:?}", val), + _ => panic!("Invalid scalar type {val:?}"), }; scalar_size == type_size }); @@ -1981,9 +1973,9 @@ impl<'tcx> Operand<'tcx> { /// /// While this is unlikely in general, it's the normal case of what you'll /// find as the `func` in a [`TerminatorKind::Call`]. - pub fn const_fn_def(&self) -> Option<(DefId, SubstsRef<'tcx>)> { + pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> { let const_ty = self.constant()?.literal.ty(); - if let ty::FnDef(def_id, substs) = *const_ty.kind() { Some((def_id, substs)) } else { None } + if let ty::FnDef(def_id, args) = *const_ty.kind() { Some((def_id, args)) } else { None } } } @@ -2057,26 +2049,26 @@ impl<'tcx> Debug for Rvalue<'tcx> { use self::Rvalue::*; match *self { - Use(ref place) => write!(fmt, "{:?}", place), + Use(ref place) => write!(fmt, "{place:?}"), Repeat(ref a, b) => { - write!(fmt, "[{:?}; ", a)?; + write!(fmt, "[{a:?}; ")?; pretty_print_const(b, fmt, false)?; write!(fmt, "]") } - Len(ref a) => write!(fmt, "Len({:?})", a), + Len(ref a) => write!(fmt, "Len({a:?})"), Cast(ref kind, ref place, ref ty) => { - write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind) + write!(fmt, "{place:?} as {ty:?} ({kind:?})") } - BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b), + BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"), CheckedBinaryOp(ref op, box (ref a, ref b)) => { - write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b) + write!(fmt, "Checked{op:?}({a:?}, {b:?})") } - UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a), - Discriminant(ref place) => write!(fmt, "discriminant({:?})", place), + UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"), + Discriminant(ref place) => write!(fmt, "discriminant({place:?})"), NullaryOp(ref op, ref t) => match op { - NullOp::SizeOf => write!(fmt, "SizeOf({:?})", t), - NullOp::AlignOf => write!(fmt, "AlignOf({:?})", t), - NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({:?}, {:?})", t, fields), + NullOp::SizeOf => write!(fmt, "SizeOf({t:?})"), + NullOp::AlignOf => write!(fmt, "AlignOf({t:?})"), + NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t:?}, {fields:?})"), }, ThreadLocalRef(did) => ty::tls::with(|tcx| { let muta = tcx.static_mutability(did).unwrap().prefix_str(); @@ -2103,10 +2095,10 @@ impl<'tcx> Debug for Rvalue<'tcx> { // Do not even print 'static String::new() }; - write!(fmt, "&{}{}{:?}", region, kind_str, place) + write!(fmt, "&{region}{kind_str}{place:?}") } - CopyForDeref(ref place) => write!(fmt, "deref_copy {:#?}", place), + CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"), AddressOf(mutability, ref place) => { let kind_str = match mutability { @@ -2114,7 +2106,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { Mutability::Not => "const", }; - write!(fmt, "&raw {} {:?}", kind_str, place) + write!(fmt, "&raw {kind_str} {place:?}") } Aggregate(ref kind, ref places) => { @@ -2127,7 +2119,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { }; match **kind { - AggregateKind::Array(_) => write!(fmt, "{:?}", places), + AggregateKind::Array(_) => write!(fmt, "{places:?}"), AggregateKind::Tuple => { if places.is_empty() { @@ -2137,12 +2129,12 @@ impl<'tcx> Debug for Rvalue<'tcx> { } } - AggregateKind::Adt(adt_did, variant, substs, _user_ty, _) => { + AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => { ty::tls::with(|tcx| { let variant_def = &tcx.adt_def(adt_did).variant(variant); - let substs = tcx.lift(substs).expect("could not lift for printing"); + let args = tcx.lift(args).expect("could not lift for printing"); let name = FmtPrinter::new(tcx, Namespace::ValueNS) - .print_def_path(variant_def.def_id, substs)? + .print_def_path(variant_def.def_id, args)? .into_buffer(); match variant_def.ctor_kind() { @@ -2159,10 +2151,10 @@ impl<'tcx> Debug for Rvalue<'tcx> { }) } - AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| { + AggregateKind::Closure(def_id, args) => ty::tls::with(|tcx| { let name = if tcx.sess.opts.unstable_opts.span_free_formats { - let substs = tcx.lift(substs).unwrap(); - format!("[closure@{}]", tcx.def_path_str_with_substs(def_id, substs),) + let args = tcx.lift(args).unwrap(); + format!("[closure@{}]", tcx.def_path_str_with_args(def_id, args),) } else { let span = tcx.def_span(def_id); format!( @@ -2213,7 +2205,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { } ShallowInitBox(ref place, ref ty) => { - write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty) + write!(fmt, "ShallowInitBox({place:?}, {ty:?})") } } } @@ -2493,7 +2485,7 @@ impl<'tcx> ConstantKind<'tcx> { }; debug!("expr.kind: {:?}", expr.kind); - let ty = tcx.type_of(def).subst_identity(); + let ty = tcx.type_of(def).instantiate_identity(); debug!(?ty); // FIXME(const_generics): We currently have to special case parameters because `min_const_generics` @@ -2521,23 +2513,22 @@ impl<'tcx> ConstantKind<'tcx> { } let hir_id = tcx.hir().local_def_id_to_hir_id(def); - let parent_substs = if let Some(parent_hir_id) = tcx.hir().opt_parent_id(hir_id) + let parent_args = if let Some(parent_hir_id) = tcx.hir().opt_parent_id(hir_id) && let Some(parent_did) = parent_hir_id.as_owner() { - InternalSubsts::identity_for_item(tcx, parent_did) + GenericArgs::identity_for_item(tcx, parent_did) } else { List::empty() }; - debug!(?parent_substs); + debug!(?parent_args); let did = def.to_def_id(); - let child_substs = InternalSubsts::identity_for_item(tcx, did); - let substs = - tcx.mk_substs_from_iter(parent_substs.into_iter().chain(child_substs.into_iter())); - debug!(?substs); + let child_args = GenericArgs::identity_for_item(tcx, did); + let args = tcx.mk_args_from_iter(parent_args.into_iter().chain(child_args.into_iter())); + debug!(?args); let span = tcx.def_span(def); - let uneval = UnevaluatedConst::new(did, substs); + let uneval = UnevaluatedConst::new(did, args); debug!(?span, ?param_env); match tcx.const_eval_resolve(param_env, uneval, Some(span)) { @@ -2552,7 +2543,7 @@ impl<'tcx> ConstantKind<'tcx> { Self::Unevaluated( UnevaluatedConst { def: did, - substs: InternalSubsts::identity_for_item(tcx, did), + args: GenericArgs::identity_for_item(tcx, did), promoted: None, }, ty, @@ -2578,7 +2569,7 @@ impl<'tcx> ConstantKind<'tcx> { #[derive(Hash, HashStable, TypeFoldable, TypeVisitable)] pub struct UnevaluatedConst<'tcx> { pub def: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, pub promoted: Option<Promoted>, } @@ -2586,14 +2577,14 @@ impl<'tcx> UnevaluatedConst<'tcx> { #[inline] pub fn shrink(self) -> ty::UnevaluatedConst<'tcx> { assert_eq!(self.promoted, None); - ty::UnevaluatedConst { def: self.def, substs: self.substs } + ty::UnevaluatedConst { def: self.def, args: self.args } } } impl<'tcx> UnevaluatedConst<'tcx> { #[inline] - pub fn new(def: DefId, substs: SubstsRef<'tcx>) -> UnevaluatedConst<'tcx> { - UnevaluatedConst { def, substs, promoted: Default::default() } + pub fn new(def: DefId, args: GenericArgsRef<'tcx>) -> UnevaluatedConst<'tcx> { + UnevaluatedConst { def, args, promoted: Default::default() } } } @@ -2758,7 +2749,7 @@ rustc_index::newtype_index! { impl<'tcx> Debug for Constant<'tcx> { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { - write!(fmt, "{}", self) + write!(fmt, "{self}") } } @@ -2834,7 +2825,7 @@ fn pretty_print_const_value<'tcx>( let ty = tcx.lift(ty).unwrap(); if tcx.sess.verbose() { - fmt.write_str(&format!("ConstValue({:?}: {})", ct, ty))?; + fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?; return Ok(()); } @@ -2904,17 +2895,17 @@ fn pretty_print_const_value<'tcx>( fmt.write_str(")")?; } ty::Adt(def, _) if def.variants().is_empty() => { - fmt.write_str(&format!("{{unreachable(): {}}}", ty))?; + fmt.write_str(&format!("{{unreachable(): {ty}}}"))?; } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let variant_idx = contents .variant .expect("destructed mir constant of adt without variant idx"); let variant_def = &def.variant(variant_idx); - let substs = tcx.lift(substs).unwrap(); + let args = tcx.lift(args).unwrap(); let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); cx.print_alloc_ids = true; - let cx = cx.print_value_path(variant_def.def_id, substs)?; + let cx = cx.print_value_path(variant_def.def_id, args)?; fmt.write_str(&cx.into_buffer())?; match variant_def.ctor_kind() { |