1
Fork 0

Move mir::Fieldabi::FieldIdx

The first PR for https://github.com/rust-lang/compiler-team/issues/606

This is just the move-and-rename, because it's plenty big-and-bitrotty already.  Future PRs will start using `FieldIdx` more broadly, and concomitantly removing `FieldIdx::new`s.
This commit is contained in:
Scott McMurray 2023-03-28 12:32:57 -07:00
parent acd27bb557
commit 5bbaeadc01
46 changed files with 192 additions and 157 deletions

View file

@ -1057,6 +1057,32 @@ impl Scalar {
} }
} }
rustc_index::newtype_index! {
/// The *source-order* index of a field in a variant.
///
/// This is how most code after type checking refers to fields, rather than
/// using names (as names have hygiene complications and more complex lookup).
///
/// Particularly for `repr(Rust)` types, this may not be the same as *layout* order.
/// (It is for `repr(C)` `struct`s, however.)
///
/// For example, in the following types,
/// ```rust
/// # enum Never {}
/// # #[repr(u16)]
/// enum Demo1 {
/// Variant0 { a: Never, b: i32 } = 100,
/// Variant1 { c: u8, d: u64 } = 10,
/// }
/// struct Demo2 { e: u8, f: u16, g: u8 }
/// ```
/// `b` is `FieldIdx(1)` in `VariantIdx(0)`,
/// `d` is `FieldIdx(1)` in `VariantIdx(1)`, and
/// `f` is `FieldIdx(1)` in `VariantIdx(0)`.
#[derive(HashStable_Generic)]
pub struct FieldIdx {}
}
/// Describes how the fields of a type are located in memory. /// Describes how the fields of a type are located in memory.
#[derive(PartialEq, Eq, Hash, Clone, Debug)] #[derive(PartialEq, Eq, Hash, Clone, Debug)]
#[cfg_attr(feature = "nightly", derive(HashStable_Generic))] #[cfg_attr(feature = "nightly", derive(HashStable_Generic))]

View file

@ -9,15 +9,15 @@ use rustc_hir::GeneratorKind;
use rustc_infer::infer::{LateBoundRegionConversionTime, TyCtxtInferExt}; use rustc_infer::infer::{LateBoundRegionConversionTime, TyCtxtInferExt};
use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::{ use rustc_middle::mir::{
AggregateKind, Constant, FakeReadCause, Field, Local, LocalInfo, LocalKind, Location, Operand, AggregateKind, Constant, FakeReadCause, Local, LocalInfo, LocalKind, Location, Operand, Place,
Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind,
}; };
use rustc_middle::ty::print::Print; use rustc_middle::ty::print::Print;
use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult}; use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult};
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP}; use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP};
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use rustc_trait_selection::traits::{ use rustc_trait_selection::traits::{
type_known_to_meet_bound_modulo_regions, Obligation, ObligationCause, type_known_to_meet_bound_modulo_regions, Obligation, ObligationCause,
@ -302,7 +302,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn describe_field( fn describe_field(
&self, &self,
place: PlaceRef<'tcx>, place: PlaceRef<'tcx>,
field: Field, field: FieldIdx,
including_tuple_field: IncludingTupleField, including_tuple_field: IncludingTupleField,
) -> Option<String> { ) -> Option<String> {
let place_ty = match place { let place_ty = match place {
@ -331,7 +331,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn describe_field_from_ty( fn describe_field_from_ty(
&self, &self,
ty: Ty<'_>, ty: Ty<'_>,
field: Field, field: FieldIdx,
variant_index: Option<VariantIdx>, variant_index: Option<VariantIdx>,
including_tuple_field: IncludingTupleField, including_tuple_field: IncludingTupleField,
) -> Option<String> { ) -> Option<String> {

View file

@ -12,6 +12,7 @@ use rustc_middle::{
use rustc_span::source_map::DesugaringKind; use rustc_span::source_map::DesugaringKind;
use rustc_span::symbol::{kw, Symbol}; use rustc_span::symbol::{kw, Symbol};
use rustc_span::{sym, BytePos, Span}; use rustc_span::{sym, BytePos, Span};
use rustc_target::abi::FieldIdx;
use crate::diagnostics::BorrowedContentSource; use crate::diagnostics::BorrowedContentSource;
use crate::MirBorrowckCtxt; use crate::MirBorrowckCtxt;
@ -1275,7 +1276,7 @@ fn is_closure_or_generator(ty: Ty<'_>) -> bool {
fn get_mut_span_in_struct_field<'tcx>( fn get_mut_span_in_struct_field<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
field: mir::Field, field: FieldIdx,
) -> Option<Span> { ) -> Option<Span> {
// Expect our local to be a reference to a struct of some kind. // Expect our local to be a reference to a struct of some kind.
if let ty::Ref(_, ty, _) = ty.kind() if let ty::Ref(_, ty, _) = ty.kind()

View file

@ -33,12 +33,13 @@ use rustc_middle::mir::{
Place, PlaceElem, PlaceRef, VarDebugInfoContents, Place, PlaceElem, PlaceRef, VarDebugInfoContents,
}; };
use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind}; use rustc_middle::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
use rustc_middle::mir::{Field, ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind}; use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
use rustc_middle::mir::{ProjectionElem, Promoted, Rvalue, Statement, StatementKind};
use rustc_middle::ty::query::Providers; use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt}; use rustc_middle::ty::{self, CapturedPlace, ParamEnv, RegionVid, TyCtxt};
use rustc_session::lint::builtin::UNUSED_MUT; use rustc_session::lint::builtin::UNUSED_MUT;
use rustc_span::{Span, Symbol}; use rustc_span::{Span, Symbol};
use rustc_target::abi::FieldIdx;
use either::Either; use either::Either;
use smallvec::SmallVec; use smallvec::SmallVec;
@ -597,7 +598,7 @@ struct MirBorrowckCtxt<'cx, 'tcx> {
used_mut: FxIndexSet<Local>, used_mut: FxIndexSet<Local>,
/// If the function we're checking is a closure, then we'll need to report back the list of /// If the function we're checking is a closure, then we'll need to report back the list of
/// mutable upvars that have been used. This field keeps track of them. /// mutable upvars that have been used. This field keeps track of them.
used_mut_upvars: SmallVec<[Field; 8]>, used_mut_upvars: SmallVec<[FieldIdx; 8]>,
/// Region inference context. This contains the results from region inference and lets us e.g. /// Region inference context. This contains the results from region inference and lets us e.g.
/// find out which CFG points are contained in each borrow region. /// find out which CFG points are contained in each borrow region.
regioncx: Rc<RegionInferenceContext<'tcx>>, regioncx: Rc<RegionInferenceContext<'tcx>>,
@ -2277,7 +2278,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
/// then returns the index of the field being projected. Note that this closure will always /// then returns the index of the field being projected. Note that this closure will always
/// be `self` in the current MIR, because that is the only time we directly access the fields /// be `self` in the current MIR, because that is the only time we directly access the fields
/// of a closure type. /// of a closure type.
fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<Field> { fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option<FieldIdx> {
path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body()) path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body())
} }

View file

@ -7,8 +7,9 @@ use crate::BorrowIndex;
use crate::Upvar; use crate::Upvar;
use rustc_data_structures::graph::dominators::Dominators; use rustc_data_structures::graph::dominators::Dominators;
use rustc_middle::mir::BorrowKind; use rustc_middle::mir::BorrowKind;
use rustc_middle::mir::{BasicBlock, Body, Field, Location, Place, PlaceRef, ProjectionElem}; use rustc_middle::mir::{BasicBlock, Body, Location, Place, PlaceRef, ProjectionElem};
use rustc_middle::ty::TyCtxt; use rustc_middle::ty::TyCtxt;
use rustc_target::abi::FieldIdx;
/// Returns `true` if the borrow represented by `kind` is /// Returns `true` if the borrow represented by `kind` is
/// allowed to be split into separate Reservation and /// allowed to be split into separate Reservation and
@ -148,7 +149,7 @@ pub(crate) fn is_upvar_field_projection<'tcx>(
upvars: &[Upvar<'tcx>], upvars: &[Upvar<'tcx>],
place_ref: PlaceRef<'tcx>, place_ref: PlaceRef<'tcx>,
body: &Body<'tcx>, body: &Body<'tcx>,
) -> Option<Field> { ) -> Option<FieldIdx> {
let mut place_ref = place_ref; let mut place_ref = place_ref;
let mut by_ref = false; let mut by_ref = false;

View file

@ -36,7 +36,7 @@ use rustc_middle::ty::{
}; };
use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::def_id::CRATE_DEF_ID;
use rustc_span::{Span, DUMMY_SP}; use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::FIRST_VARIANT; use rustc_target::abi::{FieldIdx, FIRST_VARIANT};
use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints; use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp; use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
@ -786,7 +786,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
&mut self, &mut self,
parent: &dyn fmt::Debug, parent: &dyn fmt::Debug,
base_ty: PlaceTy<'tcx>, base_ty: PlaceTy<'tcx>,
field: Field, field: FieldIdx,
location: Location, location: Location,
) -> Result<Ty<'tcx>, FieldAccessError> { ) -> Result<Ty<'tcx>, FieldAccessError> {
let tcx = self.tcx(); let tcx = self.tcx();

View file

@ -327,7 +327,7 @@ pub(crate) fn codegen_fn_prelude<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, start_
ArgKind::Spread(params) => { ArgKind::Spread(params) => {
for (i, param) in params.into_iter().enumerate() { for (i, param) in params.into_iter().enumerate() {
if let Some(param) = param { if let Some(param) = param {
place.place_field(fx, mir::Field::new(i)).write_cvalue(fx, param); place.place_field(fx, FieldIdx::new(i)).write_cvalue(fx, param);
} }
} }
} }
@ -460,7 +460,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
args.push(self_arg); args.push(self_arg);
for i in 0..tupled_arguments.len() { for i in 0..tupled_arguments.len() {
args.push(CallArgument { args.push(CallArgument {
value: pack_arg.value.value_field(fx, mir::Field::new(i)), value: pack_arg.value.value_field(fx, FieldIdx::new(i)),
is_owned: pack_arg.is_owned, is_owned: pack_arg.is_owned,
}); });
} }

View file

@ -797,7 +797,7 @@ fn codegen_stmt<'tcx>(
let index = fx.bcx.ins().iconst(fx.pointer_type, field_index as i64); let index = fx.bcx.ins().iconst(fx.pointer_type, field_index as i64);
variant_dest.place_index(fx, index) variant_dest.place_index(fx, index)
} else { } else {
variant_dest.place_field(fx, mir::Field::new(field_index)) variant_dest.place_field(fx, FieldIdx::new(field_index))
}; };
to.write_cvalue(fx, operand); to.write_cvalue(fx, operand);
} }

View file

@ -26,7 +26,7 @@ pub(crate) fn codegen_set_discriminant<'tcx>(
tag_encoding: TagEncoding::Direct, tag_encoding: TagEncoding::Direct,
variants: _, variants: _,
} => { } => {
let ptr = place.place_field(fx, mir::Field::new(tag_field)); let ptr = place.place_field(fx, FieldIdx::new(tag_field));
let to = layout.ty.discriminant_for_variant(fx.tcx, variant_index).unwrap().val; let to = layout.ty.discriminant_for_variant(fx.tcx, variant_index).unwrap().val;
let to = if ptr.layout().abi.is_signed() { let to = if ptr.layout().abi.is_signed() {
ty::ScalarInt::try_from_int( ty::ScalarInt::try_from_int(
@ -47,7 +47,7 @@ pub(crate) fn codegen_set_discriminant<'tcx>(
variants: _, variants: _,
} => { } => {
if variant_index != untagged_variant { if variant_index != untagged_variant {
let niche = place.place_field(fx, mir::Field::new(tag_field)); let niche = place.place_field(fx, FieldIdx::new(tag_field));
let niche_type = fx.clif_type(niche.layout().ty).unwrap(); let niche_type = fx.clif_type(niche.layout().ty).unwrap();
let niche_value = variant_index.as_u32() - niche_variants.start().as_u32(); let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
let niche_value = (niche_value as u128).wrapping_add(niche_start); let niche_value = (niche_value as u128).wrapping_add(niche_start);
@ -107,7 +107,7 @@ pub(crate) fn codegen_get_discriminant<'tcx>(
let cast_to = fx.clif_type(dest_layout.ty).unwrap(); let cast_to = fx.clif_type(dest_layout.ty).unwrap();
// Read the tag/niche-encoded discriminant from memory. // Read the tag/niche-encoded discriminant from memory.
let tag = value.value_field(fx, mir::Field::new(tag_field)); let tag = value.value_field(fx, FieldIdx::new(tag_field));
let tag = tag.load_scalar(fx); let tag = tag.load_scalar(fx);
// Decode the discriminant (specifically if it's niche-encoded). // Decode the discriminant (specifically if it's niche-encoded).

View file

@ -179,8 +179,8 @@ fn llvm_add_sub<'tcx>(
// c + carry -> c + first intermediate carry or borrow respectively // c + carry -> c + first intermediate carry or borrow respectively
let int0 = crate::num::codegen_checked_int_binop(fx, bin_op, a, b); let int0 = crate::num::codegen_checked_int_binop(fx, bin_op, a, b);
let c = int0.value_field(fx, mir::Field::new(0)); let c = int0.value_field(fx, FieldIdx::new(0));
let cb0 = int0.value_field(fx, mir::Field::new(1)).load_scalar(fx); let cb0 = int0.value_field(fx, FieldIdx::new(1)).load_scalar(fx);
// c + carry -> c + second intermediate carry or borrow respectively // c + carry -> c + second intermediate carry or borrow respectively
let cb_in_as_u64 = fx.bcx.ins().uextend(types::I64, cb_in); let cb_in_as_u64 = fx.bcx.ins().uextend(types::I64, cb_in);

View file

@ -253,7 +253,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
} }
ret.write_cvalue(fx, base); ret.write_cvalue(fx, base);
let ret_lane = ret.place_field(fx, mir::Field::new(idx.try_into().unwrap())); let ret_lane = ret.place_field(fx, FieldIdx::new(idx.try_into().unwrap()));
ret_lane.write_cvalue(fx, val); ret_lane.write_cvalue(fx, val);
} }

View file

@ -86,7 +86,7 @@ mod prelude {
self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut, self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
TypeFoldable, TypeVisitableExt, UintTy, TypeFoldable, TypeVisitableExt, UintTy,
}; };
pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx, FIRST_VARIANT}; pub(crate) use rustc_target::abi::{Abi, FieldIdx, Scalar, Size, VariantIdx, FIRST_VARIANT};
pub(crate) use rustc_data_structures::fx::FxHashMap; pub(crate) use rustc_data_structures::fx::FxHashMap;

View file

@ -147,8 +147,8 @@ pub(crate) fn coerce_unsized_into<'tcx>(
assert_eq!(def_a, def_b); assert_eq!(def_a, def_b);
for i in 0..def_a.variant(FIRST_VARIANT).fields.len() { for i in 0..def_a.variant(FIRST_VARIANT).fields.len() {
let src_f = src.value_field(fx, mir::Field::new(i)); let src_f = src.value_field(fx, FieldIdx::new(i));
let dst_f = dst.place_field(fx, mir::Field::new(i)); let dst_f = dst.place_field(fx, FieldIdx::new(i));
if dst_f.layout().is_zst() { if dst_f.layout().is_zst() {
continue; continue;

View file

@ -10,7 +10,7 @@ fn codegen_field<'tcx>(
base: Pointer, base: Pointer,
extra: Option<Value>, extra: Option<Value>,
layout: TyAndLayout<'tcx>, layout: TyAndLayout<'tcx>,
field: mir::Field, field: FieldIdx,
) -> (Pointer, TyAndLayout<'tcx>) { ) -> (Pointer, TyAndLayout<'tcx>) {
let field_offset = layout.fields.offset(field.index()); let field_offset = layout.fields.offset(field.index());
let field_layout = layout.field(&*fx, field.index()); let field_layout = layout.field(&*fx, field.index());
@ -210,7 +210,7 @@ impl<'tcx> CValue<'tcx> {
pub(crate) fn value_field( pub(crate) fn value_field(
self, self,
fx: &mut FunctionCx<'_, '_, 'tcx>, fx: &mut FunctionCx<'_, '_, 'tcx>,
field: mir::Field, field: FieldIdx,
) -> CValue<'tcx> { ) -> CValue<'tcx> {
let layout = self.1; let layout = self.1;
match self.0 { match self.0 {
@ -687,7 +687,7 @@ impl<'tcx> CPlace<'tcx> {
pub(crate) fn place_field( pub(crate) fn place_field(
self, self,
fx: &mut FunctionCx<'_, '_, 'tcx>, fx: &mut FunctionCx<'_, '_, 'tcx>,
field: mir::Field, field: FieldIdx,
) -> CPlace<'tcx> { ) -> CPlace<'tcx> {
let layout = self.layout(); let layout = self.layout();

View file

@ -50,7 +50,7 @@ pub(crate) fn get_ptr_and_method_ref<'tcx>(
if let Abi::Scalar(_) = arg.layout().abi { if let Abi::Scalar(_) = arg.layout().abi {
'descend_newtypes: while !arg.layout().ty.is_unsafe_ptr() && !arg.layout().ty.is_ref() { 'descend_newtypes: while !arg.layout().ty.is_unsafe_ptr() && !arg.layout().ty.is_ref() {
for i in 0..arg.layout().fields.count() { for i in 0..arg.layout().fields.count() {
let field = arg.value_field(fx, mir::Field::new(i)); let field = arg.value_field(fx, FieldIdx::new(i));
if !field.layout().is_zst() { if !field.layout().is_zst() {
// we found the one non-zero-sized field that is allowed // we found the one non-zero-sized field that is allowed
// now find *its* non-zero-sized field, or stop if it's a // now find *its* non-zero-sized field, or stop if it's a
@ -68,9 +68,9 @@ pub(crate) fn get_ptr_and_method_ref<'tcx>(
if ty.is_dyn_star() { if ty.is_dyn_star() {
let inner_layout = fx.layout_of(arg.layout().ty.builtin_deref(true).unwrap().ty); let inner_layout = fx.layout_of(arg.layout().ty.builtin_deref(true).unwrap().ty);
let dyn_star = CPlace::for_ptr(Pointer::new(arg.load_scalar(fx)), inner_layout); let dyn_star = CPlace::for_ptr(Pointer::new(arg.load_scalar(fx)), inner_layout);
let ptr = dyn_star.place_field(fx, mir::Field::new(0)).to_ptr(); let ptr = dyn_star.place_field(fx, FieldIdx::new(0)).to_ptr();
let vtable = let vtable =
dyn_star.place_field(fx, mir::Field::new(1)).to_cvalue(fx).load_scalar(fx); dyn_star.place_field(fx, FieldIdx::new(1)).to_cvalue(fx).load_scalar(fx);
break 'block (ptr, vtable); break 'block (ptr, vtable);
} }
} }

View file

@ -6,7 +6,7 @@ use rustc_hir::def::CtorKind;
use rustc_index::vec::IndexVec; use rustc_index::vec::IndexVec;
use rustc_middle::{ use rustc_middle::{
bug, bug,
mir::{Field, GeneratorLayout, GeneratorSavedLocal}, mir::{GeneratorLayout, GeneratorSavedLocal},
ty::{ ty::{
self, self,
layout::{IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout}, layout::{IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout},
@ -14,7 +14,9 @@ use rustc_middle::{
}, },
}; };
use rustc_span::Symbol; use rustc_span::Symbol;
use rustc_target::abi::{HasDataLayout, Integer, Primitive, TagEncoding, VariantIdx, Variants}; use rustc_target::abi::{
FieldIdx, HasDataLayout, Integer, Primitive, TagEncoding, VariantIdx, Variants,
};
use std::borrow::Cow; use std::borrow::Cow;
use crate::{ use crate::{
@ -353,7 +355,7 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>(
let state_specific_fields: SmallVec<_> = (0..variant_layout.fields.count()) let state_specific_fields: SmallVec<_> = (0..variant_layout.fields.count())
.map(|field_index| { .map(|field_index| {
let generator_saved_local = generator_layout.variant_fields[variant_index] let generator_saved_local = generator_layout.variant_fields[variant_index]
[Field::from_usize(field_index)]; [FieldIdx::from_usize(field_index)];
let field_name_maybe = state_specific_upvar_names[generator_saved_local]; let field_name_maybe = state_specific_upvar_names[generator_saved_local];
let field_name = field_name_maybe let field_name = field_name_maybe
.as_ref() .as_ref()

View file

@ -8,7 +8,7 @@ use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
use rustc_session::config::DebugInfo; use rustc_session::config::DebugInfo;
use rustc_span::symbol::{kw, Symbol}; use rustc_span::symbol::{kw, Symbol};
use rustc_span::{BytePos, Span}; use rustc_span::{BytePos, Span};
use rustc_target::abi::{Abi, Size, VariantIdx}; use rustc_target::abi::{Abi, FieldIdx, Size, VariantIdx};
use super::operand::{OperandRef, OperandValue}; use super::operand::{OperandRef, OperandValue};
use super::place::PlaceRef; use super::place::PlaceRef;
@ -79,7 +79,7 @@ impl<'tcx, S: Copy, L: Copy> DebugScope<S, L> {
trait DebugInfoOffsetLocation<'tcx, Bx> { trait DebugInfoOffsetLocation<'tcx, Bx> {
fn deref(&self, bx: &mut Bx) -> Self; fn deref(&self, bx: &mut Bx) -> Self;
fn layout(&self) -> TyAndLayout<'tcx>; fn layout(&self) -> TyAndLayout<'tcx>;
fn project_field(&self, bx: &mut Bx, field: mir::Field) -> Self; fn project_field(&self, bx: &mut Bx, field: FieldIdx) -> Self;
fn downcast(&self, bx: &mut Bx, variant: VariantIdx) -> Self; fn downcast(&self, bx: &mut Bx, variant: VariantIdx) -> Self;
} }
@ -94,7 +94,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> DebugInfoOffsetLocation<'tcx, Bx>
self.layout self.layout
} }
fn project_field(&self, bx: &mut Bx, field: mir::Field) -> Self { fn project_field(&self, bx: &mut Bx, field: FieldIdx) -> Self {
PlaceRef::project_field(*self, bx, field.index()) PlaceRef::project_field(*self, bx, field.index())
} }
@ -116,7 +116,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> DebugInfoOffsetLocation<'tcx, Bx>
*self *self
} }
fn project_field(&self, bx: &mut Bx, field: mir::Field) -> Self { fn project_field(&self, bx: &mut Bx, field: FieldIdx) -> Self {
self.field(bx.cx(), field.index()) self.field(bx.cx(), field.index())
} }

View file

@ -21,7 +21,7 @@ use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
use rustc_hir::{self, GeneratorKind, ImplicitSelfKind}; use rustc_hir::{self, GeneratorKind, ImplicitSelfKind};
use rustc_hir::{self as hir, HirId}; use rustc_hir::{self as hir, HirId};
use rustc_session::Session; use rustc_session::Session;
use rustc_target::abi::{Size, VariantIdx}; use rustc_target::abi::{FieldIdx, Size, VariantIdx};
use polonius_engine::Atom; use polonius_engine::Atom;
pub use rustc_ast::Mutability; pub use rustc_ast::Mutability;
@ -1512,7 +1512,7 @@ impl<V, T> ProjectionElem<V, T> {
} }
/// Returns `true` if this is a `Field` projection with the given index. /// Returns `true` if this is a `Field` projection with the given index.
pub fn is_field_to(&self, f: Field) -> bool { pub fn is_field_to(&self, f: FieldIdx) -> bool {
matches!(*self, Self::Field(x, _) if x == f) matches!(*self, Self::Field(x, _) if x == f)
} }
} }
@ -1521,22 +1521,6 @@ impl<V, T> ProjectionElem<V, T> {
/// need neither the `V` parameter for `Index` nor the `T` for `Field`. /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
pub type ProjectionKind = ProjectionElem<(), ()>; pub type ProjectionKind = ProjectionElem<(), ()>;
rustc_index::newtype_index! {
/// A [newtype'd][wrapper] index type in the MIR [control-flow graph][CFG]
///
/// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
/// rustc can identify that a field projection refers to either two different regions of memory
/// or the same one between the base and the 'projection element'.
/// Read more about projections in the [rustc-dev-guide][mir-datatypes]
///
/// [wrapper]: https://rustc-dev-guide.rust-lang.org/appendix/glossary.html#newtype
/// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
/// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
#[derive(HashStable)]
#[debug_format = "field[{}]"]
pub struct Field {}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PlaceRef<'tcx> { pub struct PlaceRef<'tcx> {
pub local: Local, pub local: Local,
@ -2685,12 +2669,17 @@ impl<'tcx> UserTypeProjections {
self.map_projections(|pat_ty_proj| pat_ty_proj.deref()) self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
} }
pub fn leaf(self, field: Field) -> Self { pub fn leaf(self, field: FieldIdx) -> Self {
self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field)) self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
} }
pub fn variant(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx, field: Field) -> Self { pub fn variant(
self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field)) self,
adt_def: AdtDef<'tcx>,
variant_index: VariantIdx,
field_index: FieldIdx,
) -> Self {
self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field_index))
} }
} }
@ -2733,7 +2722,7 @@ impl UserTypeProjection {
self self
} }
pub(crate) fn leaf(mut self, field: Field) -> Self { pub(crate) fn leaf(mut self, field: FieldIdx) -> Self {
self.projs.push(ProjectionElem::Field(field, ())); self.projs.push(ProjectionElem::Field(field, ()));
self self
} }
@ -2742,13 +2731,13 @@ impl UserTypeProjection {
mut self, mut self,
adt_def: AdtDef<'_>, adt_def: AdtDef<'_>,
variant_index: VariantIdx, variant_index: VariantIdx,
field: Field, field_index: FieldIdx,
) -> Self { ) -> Self {
self.projs.push(ProjectionElem::Downcast( self.projs.push(ProjectionElem::Downcast(
Some(adt_def.variant(variant_index).name), Some(adt_def.variant(variant_index).name),
variant_index, variant_index,
)); ));
self.projs.push(ProjectionElem::Field(field, ())); self.projs.push(ProjectionElem::Field(field_index, ()));
self self
} }
} }

View file

@ -10,12 +10,12 @@ use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_index::bit_set::BitMatrix; use rustc_index::bit_set::BitMatrix;
use rustc_index::vec::{Idx, IndexVec}; use rustc_index::vec::{Idx, IndexVec};
use rustc_span::Span; use rustc_span::Span;
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use smallvec::SmallVec; use smallvec::SmallVec;
use std::cell::Cell; use std::cell::Cell;
use std::fmt::{self, Debug}; use std::fmt::{self, Debug};
use super::{Field, SourceInfo}; use super::SourceInfo;
#[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)] #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
pub enum UnsafetyViolationKind { pub enum UnsafetyViolationKind {
@ -152,7 +152,7 @@ pub struct GeneratorLayout<'tcx> {
/// Which of the above fields are in each variant. Note that one field may /// Which of the above fields are in each variant. Note that one field may
/// be stored in multiple variants. /// be stored in multiple variants.
pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>, pub variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, GeneratorSavedLocal>>,
/// The source that led to each variant being created (usually, a yield or /// The source that led to each variant being created (usually, a yield or
/// await). /// await).
@ -229,7 +229,7 @@ pub struct BorrowCheckResult<'tcx> {
/// unerased regions. /// unerased regions.
pub concrete_opaque_types: FxIndexMap<LocalDefId, OpaqueHiddenType<'tcx>>, pub concrete_opaque_types: FxIndexMap<LocalDefId, OpaqueHiddenType<'tcx>>,
pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>, pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
pub used_mut_upvars: SmallVec<[Field; 8]>, pub used_mut_upvars: SmallVec<[FieldIdx; 8]>,
pub tainted_by_errors: Option<ErrorGuaranteed>, pub tainted_by_errors: Option<ErrorGuaranteed>,
} }
@ -353,7 +353,7 @@ pub enum ConstraintCategory<'tcx> {
/// like `Foo { field: my_val }`) /// like `Foo { field: my_val }`)
Usage, Usage,
OpaqueType, OpaqueType,
ClosureUpvar(Field), ClosureUpvar(FieldIdx),
/// A constraint from a user-written predicate /// A constraint from a user-written predicate
/// with the provided span, written on the item /// with the provided span, written on the item
@ -375,7 +375,7 @@ pub enum ConstraintCategory<'tcx> {
#[derive(TyEncodable, TyDecodable, HashStable, TypeVisitable, TypeFoldable)] #[derive(TyEncodable, TyDecodable, HashStable, TypeVisitable, TypeFoldable)]
pub enum ReturnConstraint { pub enum ReturnConstraint {
Normal, Normal,
ClosureUpvar(Field), ClosureUpvar(FieldIdx),
} }
/// The subject of a `ClosureOutlivesRequirement` -- that is, the thing /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing

View file

@ -3,7 +3,7 @@
//! This is in a dedicated file so that changes to this file can be reviewed more carefully. //! This is in a dedicated file so that changes to this file can be reviewed more carefully.
//! The intention is that this file only contains datatype declarations, no code. //! The intention is that this file only contains datatype declarations, no code.
use super::{BasicBlock, Constant, Field, Local, SwitchTargets, UserTypeProjection}; use super::{BasicBlock, Constant, Local, SwitchTargets, UserTypeProjection};
use crate::mir::coverage::{CodeRegion, CoverageKind}; use crate::mir::coverage::{CodeRegion, CoverageKind};
use crate::traits::Reveal; use crate::traits::Reveal;
@ -16,7 +16,7 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::{self as hir}; use rustc_hir::{self as hir};
use rustc_hir::{self, GeneratorKind}; use rustc_hir::{self, GeneratorKind};
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use rustc_ast::Mutability; use rustc_ast::Mutability;
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
@ -888,7 +888,15 @@ pub struct Place<'tcx> {
#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)] #[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
pub enum ProjectionElem<V, T> { pub enum ProjectionElem<V, T> {
Deref, Deref,
Field(Field, T),
/// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
/// rustc can identify that a field projection refers to either two different regions of memory
/// or the same one between the base and the 'projection element'.
/// Read more about projections in the [rustc-dev-guide][mir-datatypes]
///
/// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
Field(FieldIdx, T),
/// Index into a slice/array. /// Index into a slice/array.
/// ///
/// Note that this does not also dereference, and so it does not exactly correspond to slice /// Note that this does not also dereference, and so it does not exactly correspond to slice

View file

@ -6,7 +6,7 @@
use crate::mir::*; use crate::mir::*;
use crate::ty::{self, Ty, TyCtxt}; use crate::ty::{self, Ty, TyCtxt};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)] #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
pub struct PlaceTy<'tcx> { pub struct PlaceTy<'tcx> {
@ -33,7 +33,7 @@ impl<'tcx> PlaceTy<'tcx> {
/// ///
/// Note that the resulting type has not been normalized. /// Note that the resulting type has not been normalized.
#[instrument(level = "debug", skip(tcx), ret)] #[instrument(level = "debug", skip(tcx), ret)]
pub fn field_ty(self, tcx: TyCtxt<'tcx>, f: Field) -> Ty<'tcx> { pub fn field_ty(self, tcx: TyCtxt<'tcx>, f: FieldIdx) -> Ty<'tcx> {
match self.ty.kind() { match self.ty.kind() {
ty::Adt(adt_def, substs) => { ty::Adt(adt_def, substs) => {
let variant_def = match self.variant_index { let variant_def = match self.variant_index {
@ -61,14 +61,14 @@ impl<'tcx> PlaceTy<'tcx> {
/// `place_ty.projection_ty_core(tcx, elem, |...| { ... })` /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
/// projects `place_ty` onto `elem`, returning the appropriate /// projects `place_ty` onto `elem`, returning the appropriate
/// `Ty` or downcast variant corresponding to that projection. /// `Ty` or downcast variant corresponding to that projection.
/// The `handle_field` callback must map a `Field` to its `Ty`, /// The `handle_field` callback must map a `FieldIdx` to its `Ty`,
/// (which should be trivial when `T` = `Ty`). /// (which should be trivial when `T` = `Ty`).
pub fn projection_ty_core<V, T>( pub fn projection_ty_core<V, T>(
self, self,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
elem: &ProjectionElem<V, T>, elem: &ProjectionElem<V, T>,
mut handle_field: impl FnMut(&Self, Field, T) -> Ty<'tcx>, mut handle_field: impl FnMut(&Self, FieldIdx, T) -> Ty<'tcx>,
mut handle_opaque_cast: impl FnMut(&Self, T) -> Ty<'tcx>, mut handle_opaque_cast: impl FnMut(&Self, T) -> Ty<'tcx>,
) -> PlaceTy<'tcx> ) -> PlaceTy<'tcx>
where where

View file

@ -12,6 +12,7 @@ use rustc_hir::hir_id::{HirId, OwnerId};
use rustc_query_system::query::{DefaultCacheSelector, SingleCacheSelector, VecCacheSelector}; use rustc_query_system::query::{DefaultCacheSelector, SingleCacheSelector, VecCacheSelector};
use rustc_span::symbol::{Ident, Symbol}; use rustc_span::symbol::{Ident, Symbol};
use rustc_span::{Span, DUMMY_SP}; use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::FieldIdx;
/// Placeholder for `CrateNum`'s "local" counterpart /// Placeholder for `CrateNum`'s "local" counterpart
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
@ -332,7 +333,7 @@ impl<'tcx> Key for (ty::ParamEnv<'tcx>, ty::PolyTraitRef<'tcx>) {
} }
} }
impl<'tcx> Key for (ty::Const<'tcx>, mir::Field) { impl<'tcx> Key for (ty::Const<'tcx>, FieldIdx) {
type CacheSelector = DefaultCacheSelector<Self>; type CacheSelector = DefaultCacheSelector<Self>;
fn default_span(&self, _: TyCtxt<'_>) -> Span { fn default_span(&self, _: TyCtxt<'_>) -> Span {

View file

@ -17,14 +17,14 @@ use rustc_index::newtype_index;
use rustc_index::vec::IndexVec; use rustc_index::vec::IndexVec;
use rustc_middle::middle::region; use rustc_middle::middle::region;
use rustc_middle::mir::interpret::AllocId; use rustc_middle::mir::interpret::AllocId;
use rustc_middle::mir::{self, BinOp, BorrowKind, FakeReadCause, Field, Mutability, UnOp}; use rustc_middle::mir::{self, BinOp, BorrowKind, FakeReadCause, Mutability, UnOp};
use rustc_middle::ty::adjustment::PointerCast; use rustc_middle::ty::adjustment::PointerCast;
use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, AdtDef, FnSig, Ty, UpvarSubsts}; use rustc_middle::ty::{self, AdtDef, FnSig, Ty, UpvarSubsts};
use rustc_middle::ty::{CanonicalUserType, CanonicalUserTypeAnnotation}; use rustc_middle::ty::{CanonicalUserType, CanonicalUserTypeAnnotation};
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
use rustc_span::{sym, Span, Symbol, DUMMY_SP}; use rustc_span::{sym, Span, Symbol, DUMMY_SP};
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use rustc_target::asm::InlineAsmRegOrRegClass; use rustc_target::asm::InlineAsmRegOrRegClass;
use std::fmt; use std::fmt;
use std::ops::Index; use std::ops::Index;
@ -366,7 +366,7 @@ pub enum ExprKind<'tcx> {
/// Variant containing the field. /// Variant containing the field.
variant_index: VariantIdx, variant_index: VariantIdx,
/// This can be a named (`.foo`) or unnamed (`.0`) field. /// This can be a named (`.foo`) or unnamed (`.0`) field.
name: Field, name: FieldIdx,
}, },
/// A *non-overloaded* indexing operation. /// A *non-overloaded* indexing operation.
Index { Index {
@ -491,7 +491,7 @@ pub enum ExprKind<'tcx> {
/// This is used in struct constructors. /// This is used in struct constructors.
#[derive(Clone, Debug, HashStable)] #[derive(Clone, Debug, HashStable)]
pub struct FieldExpr { pub struct FieldExpr {
pub name: Field, pub name: FieldIdx,
pub expr: ExprId, pub expr: ExprId,
} }
@ -570,7 +570,7 @@ pub enum BindingMode {
#[derive(Clone, Debug, HashStable)] #[derive(Clone, Debug, HashStable)]
pub struct FieldPat<'tcx> { pub struct FieldPat<'tcx> {
pub field: Field, pub field: FieldIdx,
pub pattern: Box<Pat<'tcx>>, pub pattern: Box<Pat<'tcx>>,
} }

View file

@ -12,9 +12,7 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
use crate::middle::resolve_bound_vars; use crate::middle::resolve_bound_vars;
use crate::middle::stability; use crate::middle::stability;
use crate::mir::interpret::{self, Allocation, ConstAllocation}; use crate::mir::interpret::{self, Allocation, ConstAllocation};
use crate::mir::{ use crate::mir::{Body, BorrowCheckResult, Local, Place, PlaceElem, ProjectionKind, Promoted};
Body, BorrowCheckResult, Field, Local, Place, PlaceElem, ProjectionKind, Promoted,
};
use crate::query::LocalCrate; use crate::query::LocalCrate;
use crate::thir::Thir; use crate::thir::Thir;
use crate::traits; use crate::traits;
@ -65,7 +63,7 @@ use rustc_span::def_id::{DefPathHash, StableCrateId};
use rustc_span::source_map::SourceMap; use rustc_span::source_map::SourceMap;
use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{Span, DUMMY_SP}; use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::{Layout, LayoutS, TargetDataLayout, VariantIdx}; use rustc_target::abi::{FieldIdx, Layout, LayoutS, TargetDataLayout, VariantIdx};
use rustc_target::spec::abi; use rustc_target::spec::abi;
use rustc_type_ir::sty::TyKind::*; use rustc_type_ir::sty::TyKind::*;
use rustc_type_ir::WithCachedTypeInfo; use rustc_type_ir::WithCachedTypeInfo;
@ -2125,7 +2123,7 @@ impl<'tcx> TyCtxt<'tcx> {
} }
} }
pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { pub fn mk_place_field(self, place: Place<'tcx>, f: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
self.mk_place_elem(place, PlaceElem::Field(f, ty)) self.mk_place_elem(place, PlaceElem::Field(f, ty))
} }

View file

@ -4,7 +4,7 @@
//! to help with the tedium. //! to help with the tedium.
use crate::mir::interpret; use crate::mir::interpret;
use crate::mir::{Field, ProjectionKind}; use crate::mir::ProjectionKind;
use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable}; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable};
use crate::ty::print::{with_no_trimmed_paths, FmtPrinter, Printer}; use crate::ty::print::{with_no_trimmed_paths, FmtPrinter, Printer};
use crate::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; use crate::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
@ -217,6 +217,7 @@ CloneLiftImpls! {
// implementation and traversal implementations (the latter only for // implementation and traversal implementations (the latter only for
// TyCtxt<'_> interners). // TyCtxt<'_> interners).
TrivialTypeTraversalAndLiftImpls! { TrivialTypeTraversalAndLiftImpls! {
::rustc_target::abi::FieldIdx,
::rustc_target::abi::VariantIdx, ::rustc_target::abi::VariantIdx,
crate::middle::region::Scope, crate::middle::region::Scope,
crate::ty::FloatTy, crate::ty::FloatTy,
@ -268,7 +269,6 @@ TrivialTypeTraversalAndLiftImpls! {
::rustc_span::Span, ::rustc_span::Span,
::rustc_span::symbol::Ident, ::rustc_span::symbol::Ident,
::rustc_errors::ErrorGuaranteed, ::rustc_errors::ErrorGuaranteed,
Field,
interpret::Scalar, interpret::Scalar,
rustc_target::abi::Size, rustc_target::abi::Size,
ty::BoundVar, ty::BoundVar,

View file

@ -3,7 +3,7 @@ use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::ty::cast::mir_cast_kind; use rustc_middle::ty::cast::mir_cast_kind;
use rustc_middle::{mir::*, thir::*, ty}; use rustc_middle::{mir::*, thir::*, ty};
use rustc_span::Span; use rustc_span::Span;
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use crate::build::custom::ParseError; use crate::build::custom::ParseError;
use crate::build::expr::as_constant::as_constant_inner; use crate::build::expr::as_constant::as_constant_inner;
@ -223,7 +223,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
let (parent, proj) = parse_by_kind!(self, expr_id, expr, "place", let (parent, proj) = parse_by_kind!(self, expr_id, expr, "place",
@call("mir_field", args) => { @call("mir_field", args) => {
let (parent, ty) = self.parse_place_inner(args[0])?; let (parent, ty) = self.parse_place_inner(args[0])?;
let field = Field::from_u32(self.parse_integer_literal(args[1])? as u32); let field = FieldIdx::from_u32(self.parse_integer_literal(args[1])? as u32);
let field_ty = ty.field_ty(self.tcx, field); let field_ty = ty.field_ty(self.tcx, field);
let proj = PlaceElem::Field(field, field_ty); let proj = PlaceElem::Field(field, field_ty);
let place = parent.project_deeper(&[proj], self.tcx); let place = parent.project_deeper(&[proj], self.tcx);

View file

@ -13,7 +13,7 @@ use rustc_middle::thir::*;
use rustc_middle::ty::AdtDef; use rustc_middle::ty::AdtDef;
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, Variance}; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, Variance};
use rustc_span::Span; use rustc_span::Span;
use rustc_target::abi::{VariantIdx, FIRST_VARIANT}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT};
use std::assert_matches::assert_matches; use std::assert_matches::assert_matches;
use std::iter; use std::iter;
@ -293,7 +293,7 @@ impl<'tcx> PlaceBuilder<'tcx> {
&self.projection &self.projection
} }
pub(crate) fn field(self, f: Field, ty: Ty<'tcx>) -> Self { pub(crate) fn field(self, f: FieldIdx, ty: Ty<'tcx>) -> Self {
self.project(PlaceElem::Field(f, ty)) self.project(PlaceElem::Field(f, ty))
} }

View file

@ -17,6 +17,7 @@ use rustc_middle::thir::*;
use rustc_middle::ty::cast::{mir_cast_kind, CastTy}; use rustc_middle::ty::cast::{mir_cast_kind, CastTy};
use rustc_middle::ty::{self, Ty, UpvarSubsts}; use rustc_middle::ty::{self, Ty, UpvarSubsts};
use rustc_span::Span; use rustc_span::Span;
use rustc_target::abi::FieldIdx;
impl<'a, 'tcx> Builder<'a, 'tcx> { impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Returns an rvalue suitable for use until the end of the current /// Returns an rvalue suitable for use until the end of the current
@ -553,8 +554,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
result_value, result_value,
Rvalue::CheckedBinaryOp(op, Box::new((lhs.to_copy(), rhs.to_copy()))), Rvalue::CheckedBinaryOp(op, Box::new((lhs.to_copy(), rhs.to_copy()))),
); );
let val_fld = Field::new(0); let val_fld = FieldIdx::new(0);
let of_fld = Field::new(1); let of_fld = FieldIdx::new(1);
let tcx = self.tcx; let tcx = self.tcx;
let val = tcx.mk_place_field(result_value, val_fld, ty); let val = tcx.mk_place_field(result_value, val_fld, ty);

View file

@ -10,6 +10,7 @@ use rustc_index::vec::Idx;
use rustc_middle::mir::*; use rustc_middle::mir::*;
use rustc_middle::thir::*; use rustc_middle::thir::*;
use rustc_middle::ty::CanonicalUserTypeAnnotation; use rustc_middle::ty::CanonicalUserTypeAnnotation;
use rustc_target::abi::FieldIdx;
use std::iter; use std::iter;
impl<'a, 'tcx> Builder<'a, 'tcx> { impl<'a, 'tcx> Builder<'a, 'tcx> {
@ -344,7 +345,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
.collect(); .collect();
let field_names: Vec<_> = let field_names: Vec<_> =
(0..adt_def.variant(variant_index).fields.len()).map(Field::new).collect(); (0..adt_def.variant(variant_index).fields.len()).map(FieldIdx::new).collect();
let fields: Vec<_> = if let Some(FruInfo { base, field_types }) = base { let fields: Vec<_> = if let Some(FruInfo { base, field_types }) = base {
let place_builder = let place_builder =

View file

@ -25,6 +25,7 @@ use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
use rustc_span::symbol::sym; use rustc_span::symbol::sym;
use rustc_span::Span; use rustc_span::Span;
use rustc_span::Symbol; use rustc_span::Symbol;
use rustc_target::abi::FieldIdx;
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
use super::lints; use super::lints;
@ -793,7 +794,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let mutability = captured_place.mutability; let mutability = captured_place.mutability;
let mut projs = closure_env_projs.clone(); let mut projs = closure_env_projs.clone();
projs.push(ProjectionElem::Field(Field::new(i), ty)); projs.push(ProjectionElem::Field(FieldIdx::new(i), ty));
match capture { match capture {
ty::UpvarCapture::ByValue => {} ty::UpvarCapture::ByValue => {}
ty::UpvarCapture::ByRef(..) => { ty::UpvarCapture::ByRef(..) => {

View file

@ -10,7 +10,7 @@ use rustc_middle::hir::place::Place as HirPlace;
use rustc_middle::hir::place::PlaceBase as HirPlaceBase; use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
use rustc_middle::hir::place::ProjectionKind as HirProjectionKind; use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
use rustc_middle::middle::region; use rustc_middle::middle::region;
use rustc_middle::mir::{self, BinOp, BorrowKind, Field, UnOp}; use rustc_middle::mir::{self, BinOp, BorrowKind, UnOp};
use rustc_middle::thir::*; use rustc_middle::thir::*;
use rustc_middle::ty::adjustment::{ use rustc_middle::ty::adjustment::{
Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast, Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast,
@ -20,7 +20,7 @@ use rustc_middle::ty::{
self, AdtKind, InlineConstSubsts, InlineConstSubstsParts, ScalarInt, Ty, UpvarSubsts, UserType, self, AdtKind, InlineConstSubsts, InlineConstSubstsParts, ScalarInt, Ty, UpvarSubsts, UserType,
}; };
use rustc_span::{sym, Span}; use rustc_span::{sym, Span};
use rustc_target::abi::FIRST_VARIANT; use rustc_target::abi::{FieldIdx, FIRST_VARIANT};
impl<'tcx> Cx<'tcx> { impl<'tcx> Cx<'tcx> {
pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId { pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId {
@ -379,7 +379,7 @@ impl<'tcx> Cx<'tcx> {
.iter() .iter()
.enumerate() .enumerate()
.map(|(idx, e)| FieldExpr { .map(|(idx, e)| FieldExpr {
name: Field::new(idx), name: FieldIdx::new(idx),
expr: self.mirror_expr(e), expr: self.mirror_expr(e),
}) })
.collect(); .collect();
@ -733,7 +733,7 @@ impl<'tcx> Cx<'tcx> {
hir::ExprKind::Field(ref source, ..) => ExprKind::Field { hir::ExprKind::Field(ref source, ..) => ExprKind::Field {
lhs: self.mirror_expr(source), lhs: self.mirror_expr(source),
variant_index: FIRST_VARIANT, variant_index: FIRST_VARIANT,
name: Field::new(self.typeck_results.field_index(expr.hir_id)), name: FieldIdx::new(self.typeck_results.field_index(expr.hir_id)),
}, },
hir::ExprKind::Cast(ref source, ref cast_ty) => { hir::ExprKind::Cast(ref source, ref cast_ty) => {
// Check for a user-given type annotation on this `cast` // Check for a user-given type annotation on this `cast`
@ -1053,7 +1053,7 @@ impl<'tcx> Cx<'tcx> {
HirProjectionKind::Field(field, variant_index) => ExprKind::Field { HirProjectionKind::Field(field, variant_index) => ExprKind::Field {
lhs: self.thir.exprs.push(captured_place_expr), lhs: self.thir.exprs.push(captured_place_expr),
variant_index, variant_index,
name: Field::new(field as usize), name: FieldIdx::new(field as usize),
}, },
HirProjectionKind::Index | HirProjectionKind::Subslice => { HirProjectionKind::Index | HirProjectionKind::Subslice => {
// We don't capture these projections, so we can ignore them here // We don't capture these projections, so we can ignore them here
@ -1107,7 +1107,7 @@ impl<'tcx> Cx<'tcx> {
fields fields
.iter() .iter()
.map(|field| FieldExpr { .map(|field| FieldExpr {
name: Field::new(self.typeck_results.field_index(field.hir_id)), name: FieldIdx::new(self.typeck_results.field_index(field.hir_id)),
expr: self.mirror_expr(field.expr), expr: self.mirror_expr(field.expr),
}) })
.collect() .collect()

View file

@ -2,11 +2,12 @@ use rustc_hir as hir;
use rustc_index::vec::Idx; use rustc_index::vec::Idx;
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
use rustc_infer::traits::Obligation; use rustc_infer::traits::Obligation;
use rustc_middle::mir::{self, Field}; use rustc_middle::mir;
use rustc_middle::thir::{FieldPat, Pat, PatKind}; use rustc_middle::thir::{FieldPat, Pat, PatKind};
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_session::lint; use rustc_session::lint;
use rustc_span::Span; use rustc_span::Span;
use rustc_target::abi::FieldIdx;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
use rustc_trait_selection::traits::{self, ObligationCause}; use rustc_trait_selection::traits::{self, ObligationCause};
@ -218,7 +219,7 @@ impl<'tcx> ConstToPat<'tcx> {
) -> Result<Vec<FieldPat<'tcx>>, FallbackToConstRef> { ) -> Result<Vec<FieldPat<'tcx>>, FallbackToConstRef> {
vals.enumerate() vals.enumerate()
.map(|(idx, val)| { .map(|(idx, val)| {
let field = Field::new(idx); let field = FieldIdx::new(idx);
Ok(FieldPat { field, pattern: self.recur(val, false)? }) Ok(FieldPat { field, pattern: self.recur(val, false)? })
}) })
.collect() .collect()

View file

@ -53,14 +53,14 @@ use smallvec::{smallvec, SmallVec};
use rustc_data_structures::captures::Captures; use rustc_data_structures::captures::Captures;
use rustc_hir::{HirId, RangeEnd}; use rustc_hir::{HirId, RangeEnd};
use rustc_index::vec::Idx; use rustc_index::vec::Idx;
use rustc_middle::mir::{self, Field}; use rustc_middle::mir;
use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange}; use rustc_middle::thir::{FieldPat, Pat, PatKind, PatRange};
use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::layout::IntegerExt;
use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef}; use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef};
use rustc_middle::{middle::stability::EvalResult, mir::interpret::ConstValue}; use rustc_middle::{middle::stability::EvalResult, mir::interpret::ConstValue};
use rustc_session::lint; use rustc_session::lint;
use rustc_span::{Span, DUMMY_SP}; use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::{Integer, Size, VariantIdx, FIRST_VARIANT}; use rustc_target::abi::{FieldIdx, Integer, Size, VariantIdx, FIRST_VARIANT};
use self::Constructor::*; use self::Constructor::*;
use self::SliceKind::*; use self::SliceKind::*;
@ -1126,7 +1126,7 @@ impl<'tcx> SplitWildcard<'tcx> {
/// Note that the number of fields of a constructor may not match the fields declared in the /// Note that the number of fields of a constructor may not match the fields declared in the
/// original struct/variant. This happens if a private or `non_exhaustive` field is uninhabited, /// original struct/variant. This happens if a private or `non_exhaustive` field is uninhabited,
/// because the code mustn't observe that it is uninhabited. In that case that field is not /// because the code mustn't observe that it is uninhabited. In that case that field is not
/// included in `fields`. For that reason, when you have a `mir::Field` you must use /// included in `fields`. For that reason, when you have a `FieldIdx` you must use
/// `index_with_declared_idx`. /// `index_with_declared_idx`.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub(super) struct Fields<'p, 'tcx> { pub(super) struct Fields<'p, 'tcx> {
@ -1165,7 +1165,7 @@ impl<'p, 'tcx> Fields<'p, 'tcx> {
cx: &'a MatchCheckCtxt<'p, 'tcx>, cx: &'a MatchCheckCtxt<'p, 'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
variant: &'a VariantDef, variant: &'a VariantDef,
) -> impl Iterator<Item = (Field, Ty<'tcx>)> + Captures<'a> + Captures<'p> { ) -> impl Iterator<Item = (FieldIdx, Ty<'tcx>)> + Captures<'a> + Captures<'p> {
let ty::Adt(adt, substs) = ty.kind() else { bug!() }; let ty::Adt(adt, substs) = ty.kind() else { bug!() };
// Whether we must not match the fields of this variant exhaustively. // Whether we must not match the fields of this variant exhaustively.
let is_non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did().is_local(); let is_non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did().is_local();
@ -1180,7 +1180,7 @@ impl<'p, 'tcx> Fields<'p, 'tcx> {
if is_uninhabited && (!is_visible || is_non_exhaustive) { if is_uninhabited && (!is_visible || is_non_exhaustive) {
None None
} else { } else {
Some((Field::new(i), ty)) Some((FieldIdx::new(i), ty))
} }
}) })
} }
@ -1438,7 +1438,7 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> {
ty::Tuple(..) => PatKind::Leaf { ty::Tuple(..) => PatKind::Leaf {
subpatterns: subpatterns subpatterns: subpatterns
.enumerate() .enumerate()
.map(|(i, pattern)| FieldPat { field: Field::new(i), pattern }) .map(|(i, pattern)| FieldPat { field: FieldIdx::new(i), pattern })
.collect(), .collect(),
}, },
ty::Adt(adt_def, _) if adt_def.is_box() => { ty::Adt(adt_def, _) if adt_def.is_box() => {

View file

@ -21,12 +21,13 @@ use rustc_middle::mir::interpret::{
ConstValue, ErrorHandled, LitToConstError, LitToConstInput, Scalar, ConstValue, ErrorHandled, LitToConstError, LitToConstInput, Scalar,
}; };
use rustc_middle::mir::{self, UserTypeProjection}; use rustc_middle::mir::{self, UserTypeProjection};
use rustc_middle::mir::{BorrowKind, Field, Mutability}; use rustc_middle::mir::{BorrowKind, Mutability};
use rustc_middle::thir::{Ascription, BindingMode, FieldPat, LocalVarId, Pat, PatKind, PatRange}; use rustc_middle::thir::{Ascription, BindingMode, FieldPat, LocalVarId, Pat, PatKind, PatRange};
use rustc_middle::ty::subst::{GenericArg, SubstsRef}; use rustc_middle::ty::subst::{GenericArg, SubstsRef};
use rustc_middle::ty::CanonicalUserTypeAnnotation; use rustc_middle::ty::CanonicalUserTypeAnnotation;
use rustc_middle::ty::{self, AdtDef, ConstKind, Region, Ty, TyCtxt, UserType}; use rustc_middle::ty::{self, AdtDef, ConstKind, Region, Ty, TyCtxt, UserType};
use rustc_span::{Span, Symbol}; use rustc_span::{Span, Symbol};
use rustc_target::abi::FieldIdx;
use std::cmp::Ordering; use std::cmp::Ordering;
@ -356,7 +357,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
let subpatterns = fields let subpatterns = fields
.iter() .iter()
.map(|field| FieldPat { .map(|field| FieldPat {
field: Field::new(self.typeck_results.field_index(field.hir_id)), field: FieldIdx::new(self.typeck_results.field_index(field.hir_id)),
pattern: self.lower_pattern(&field.pat), pattern: self.lower_pattern(&field.pat),
}) })
.collect(); .collect();
@ -379,7 +380,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
pats.iter() pats.iter()
.enumerate_and_adjust(expected_len, gap_pos) .enumerate_and_adjust(expected_len, gap_pos)
.map(|(i, subpattern)| FieldPat { .map(|(i, subpattern)| FieldPat {
field: Field::new(i), field: FieldIdx::new(i),
pattern: self.lower_pattern(subpattern), pattern: self.lower_pattern(subpattern),
}) })
.collect() .collect()
@ -723,7 +724,7 @@ macro_rules! ClonePatternFoldableImpls {
} }
ClonePatternFoldableImpls! { <'tcx> ClonePatternFoldableImpls! { <'tcx>
Span, Field, Mutability, Symbol, LocalVarId, usize, Span, FieldIdx, Mutability, Symbol, LocalVarId, usize,
Region<'tcx>, Ty<'tcx>, BindingMode, AdtDef<'tcx>, Region<'tcx>, Ty<'tcx>, BindingMode, AdtDef<'tcx>,
SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>, SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
UserTypeProjection, CanonicalUserTypeAnnotation<'tcx> UserTypeProjection, CanonicalUserTypeAnnotation<'tcx>

View file

@ -7,7 +7,7 @@ use rustc_middle::traits::Reveal;
use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::util::IntTypeExt;
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_target::abi::{VariantIdx, FIRST_VARIANT}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT};
use std::{fmt, iter}; use std::{fmt, iter};
/// The value of an inserted drop flag. /// The value of an inserted drop flag.
@ -129,7 +129,7 @@ pub trait DropElaborator<'a, 'tcx>: fmt::Debug {
/// Returns the subpath of a field of `path` (or `None` if there is no dedicated subpath). /// Returns the subpath of a field of `path` (or `None` if there is no dedicated subpath).
/// ///
/// If this returns `None`, `field` will not get a dedicated drop flag. /// If this returns `None`, `field` will not get a dedicated drop flag.
fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path>; fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path>;
/// Returns the subpath of a dereference of `path` (or `None` if there is no dedicated subpath). /// Returns the subpath of a dereference of `path` (or `None` if there is no dedicated subpath).
/// ///
@ -269,7 +269,7 @@ where
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, f)| { .map(|(i, f)| {
let field = Field::new(i); let field = FieldIdx::new(i);
let subpath = self.elaborator.field_subpath(variant_path, field); let subpath = self.elaborator.field_subpath(variant_path, field);
let tcx = self.tcx(); let tcx = self.tcx();
@ -397,8 +397,8 @@ where
.enumerate() .enumerate()
.map(|(i, &ty)| { .map(|(i, &ty)| {
( (
self.tcx().mk_place_field(self.place, Field::new(i), ty), self.tcx().mk_place_field(self.place, FieldIdx::new(i), ty),
self.elaborator.field_subpath(self.path, Field::new(i)), self.elaborator.field_subpath(self.path, FieldIdx::new(i)),
) )
}) })
.collect(); .collect();
@ -416,9 +416,9 @@ where
unique_ty.ty_adt_def().unwrap().non_enum_variant().fields[0].ty(self.tcx(), substs); unique_ty.ty_adt_def().unwrap().non_enum_variant().fields[0].ty(self.tcx(), substs);
let ptr_ty = self.tcx().mk_imm_ptr(substs[0].expect_ty()); let ptr_ty = self.tcx().mk_imm_ptr(substs[0].expect_ty());
let unique_place = self.tcx().mk_place_field(self.place, Field::new(0), unique_ty); let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::new(0), unique_ty);
let nonnull_place = self.tcx().mk_place_field(unique_place, Field::new(0), nonnull_ty); let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::new(0), nonnull_ty);
let ptr_place = self.tcx().mk_place_field(nonnull_place, Field::new(0), ptr_ty); let ptr_place = self.tcx().mk_place_field(nonnull_place, FieldIdx::new(0), ptr_ty);
let interior = self.tcx().mk_place_deref(ptr_place); let interior = self.tcx().mk_place_deref(ptr_place);
let interior_path = self.elaborator.deref_subpath(self.path); let interior_path = self.elaborator.deref_subpath(self.path);
@ -899,7 +899,7 @@ where
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, f)| { .map(|(i, f)| {
let field = Field::new(i); let field = FieldIdx::new(i);
let field_ty = f.ty(tcx, substs); let field_ty = f.ty(tcx, substs);
Operand::Move(tcx.mk_place_field(self.place, field, field_ty)) Operand::Move(tcx.mk_place_field(self.place, field, field_ty))
}) })

View file

@ -40,7 +40,7 @@ use rustc_index::vec::IndexVec;
use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
use rustc_middle::mir::*; use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use crate::lattice::{HasBottom, HasTop}; use crate::lattice::{HasBottom, HasTop};
use crate::{ use crate::{
@ -919,7 +919,7 @@ impl<V: HasTop> ValueOrPlace<V> {
/// Although only field projections are currently allowed, this could change in the future. /// Although only field projections are currently allowed, this could change in the future.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum TrackElem { pub enum TrackElem {
Field(Field), Field(FieldIdx),
Variant(VariantIdx), Variant(VariantIdx),
Discriminant, Discriminant,
} }
@ -941,7 +941,7 @@ pub fn iter_fields<'tcx>(
ty: Ty<'tcx>, ty: Ty<'tcx>,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
mut f: impl FnMut(Option<VariantIdx>, Field, Ty<'tcx>), mut f: impl FnMut(Option<VariantIdx>, FieldIdx, Ty<'tcx>),
) { ) {
match ty.kind() { match ty.kind() {
ty::Tuple(list) => { ty::Tuple(list) => {

View file

@ -13,8 +13,7 @@ use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_mir_dataflow::value_analysis::{Map, State, TrackElem, ValueAnalysis, ValueOrPlace}; use rustc_mir_dataflow::value_analysis::{Map, State, TrackElem, ValueAnalysis, ValueOrPlace};
use rustc_mir_dataflow::{lattice::FlatSet, Analysis, ResultsVisitor, SwitchIntEdgeEffects}; use rustc_mir_dataflow::{lattice::FlatSet, Analysis, ResultsVisitor, SwitchIntEdgeEffects};
use rustc_span::DUMMY_SP; use rustc_span::DUMMY_SP;
use rustc_target::abi::Align; use rustc_target::abi::{Align, FieldIdx, VariantIdx};
use rustc_target::abi::VariantIdx;
use crate::MirPass; use crate::MirPass;
@ -148,7 +147,7 @@ impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'_, 'tcx> {
for (field_index, operand) in operands.iter().enumerate() { for (field_index, operand) in operands.iter().enumerate() {
if let Some(field) = self.map().apply( if let Some(field) = self.map().apply(
variant_target_idx, variant_target_idx,
TrackElem::Field(Field::from_usize(field_index)), TrackElem::Field(FieldIdx::from_usize(field_index)),
) { ) {
let result = self.handle_operand(operand, state); let result = self.handle_operand(operand, state);
state.insert_idx(field, result, self.map()); state.insert_idx(field, result, self.map());

View file

@ -9,6 +9,7 @@ use rustc_middle::mir::patch::MirPatch;
use rustc_middle::mir::visit::MutVisitor; use rustc_middle::mir::visit::MutVisitor;
use rustc_middle::mir::*; use rustc_middle::mir::*;
use rustc_middle::ty::{Ty, TyCtxt}; use rustc_middle::ty::{Ty, TyCtxt};
use rustc_target::abi::FieldIdx;
/// Constructs the types used when accessing a Box's pointer /// Constructs the types used when accessing a Box's pointer
pub fn build_ptr_tys<'tcx>( pub fn build_ptr_tys<'tcx>(
@ -32,9 +33,9 @@ pub fn build_projection<'tcx>(
ptr_ty: Ty<'tcx>, ptr_ty: Ty<'tcx>,
) -> [PlaceElem<'tcx>; 3] { ) -> [PlaceElem<'tcx>; 3] {
[ [
PlaceElem::Field(Field::new(0), unique_ty), PlaceElem::Field(FieldIdx::new(0), unique_ty),
PlaceElem::Field(Field::new(0), nonnull_ty), PlaceElem::Field(FieldIdx::new(0), nonnull_ty),
PlaceElem::Field(Field::new(0), ptr_ty), PlaceElem::Field(FieldIdx::new(0), ptr_ty),
] ]
} }

View file

@ -15,7 +15,7 @@ use rustc_mir_dataflow::MoveDataParamEnv;
use rustc_mir_dataflow::{on_all_children_bits, on_all_drop_children_bits}; use rustc_mir_dataflow::{on_all_children_bits, on_all_drop_children_bits};
use rustc_mir_dataflow::{Analysis, ResultsCursor}; use rustc_mir_dataflow::{Analysis, ResultsCursor};
use rustc_span::{DesugaringKind, Span}; use rustc_span::{DesugaringKind, Span};
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use std::fmt; use std::fmt;
/// During MIR building, Drop terminators are inserted in every place where a drop may occur. /// During MIR building, Drop terminators are inserted in every place where a drop may occur.
@ -252,7 +252,7 @@ impl<'a, 'tcx> DropElaborator<'a, 'tcx> for Elaborator<'a, '_, 'tcx> {
} }
} }
fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path> { fn field_subpath(&self, path: Self::Path, field: FieldIdx) -> Option<Self::Path> {
rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e { rustc_mir_dataflow::move_path_children_matching(self.ctxt.move_data(), path, |e| match e {
ProjectionElem::Field(idx, _) => idx == field, ProjectionElem::Field(idx, _) => idx == field,
_ => false, _ => false,

View file

@ -73,7 +73,7 @@ use rustc_mir_dataflow::{self, Analysis};
use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::def_id::{DefId, LocalDefId};
use rustc_span::symbol::sym; use rustc_span::symbol::sym;
use rustc_span::Span; use rustc_span::Span;
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
use rustc_target::spec::PanicStrategy; use rustc_target::spec::PanicStrategy;
use std::{iter, ops}; use std::{iter, ops};
@ -162,9 +162,10 @@ impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
place, place,
Place { Place {
local: SELF_ARG, local: SELF_ARG,
projection: self projection: self.tcx().mk_place_elems(&[ProjectionElem::Field(
.tcx() FieldIdx::new(0),
.mk_place_elems(&[ProjectionElem::Field(Field::new(0), self.ref_gen_ty)]), self.ref_gen_ty,
)]),
}, },
self.tcx, self.tcx,
); );
@ -297,7 +298,7 @@ impl<'tcx> TransformVisitor<'tcx> {
let self_place = Place::from(SELF_ARG); let self_place = Place::from(SELF_ARG);
let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index); let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
let mut projection = base.projection.to_vec(); let mut projection = base.projection.to_vec();
projection.push(ProjectionElem::Field(Field::new(idx), ty)); projection.push(ProjectionElem::Field(FieldIdx::new(idx), ty));
Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) } Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
} }
@ -967,7 +968,7 @@ fn compute_layout<'tcx>(
// Build the generator variant field list. // Build the generator variant field list.
// Create a map from local indices to generator struct indices. // Create a map from local indices to generator struct indices.
let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> = let mut variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, GeneratorSavedLocal>> =
iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect(); iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
let mut remap = FxHashMap::default(); let mut remap = FxHashMap::default();
for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() { for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {

View file

@ -10,7 +10,7 @@ use rustc_middle::mir::*;
use rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv, Ty, TyCtxt}; use rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
use rustc_session::config::OptLevel; use rustc_session::config::OptLevel;
use rustc_span::{hygiene::ExpnKind, ExpnData, LocalExpnId, Span}; use rustc_span::{hygiene::ExpnKind, ExpnData, LocalExpnId, Span};
use rustc_target::abi::FIRST_VARIANT; use rustc_target::abi::{FieldIdx, FIRST_VARIANT};
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
use crate::simplify::{remove_dead_blocks, CfgSimplifier}; use crate::simplify::{remove_dead_blocks, CfgSimplifier};
@ -700,7 +700,7 @@ impl<'tcx> Inliner<'tcx> {
// The `tmp0`, `tmp1`, and `tmp2` in our example above. // The `tmp0`, `tmp1`, and `tmp2` in our example above.
let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| { let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
// This is e.g., `tuple_tmp.0` in our example above. // This is e.g., `tuple_tmp.0` in our example above.
let tuple_field = Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty)); let tuple_field = Operand::Move(tcx.mk_place_field(tuple, FieldIdx::new(i), ty));
// Spill to a local to make e.g., `tmp0`. // Spill to a local to make e.g., `tmp0`.
self.create_temp_if_necessary(tuple_field, callsite, caller_body) self.create_temp_if_necessary(tuple_field, callsite, caller_body)

View file

@ -3,14 +3,14 @@
use crate::MirPass; use crate::MirPass;
use rustc_hir::Mutability; use rustc_hir::Mutability;
use rustc_middle::mir::{ use rustc_middle::mir::{
BinOp, Body, CastKind, Constant, ConstantKind, Field, LocalDecls, Operand, Place, BinOp, Body, CastKind, Constant, ConstantKind, LocalDecls, Operand, Place, ProjectionElem,
ProjectionElem, Rvalue, SourceInfo, Statement, StatementKind, SwitchTargets, Terminator, Rvalue, SourceInfo, Statement, StatementKind, SwitchTargets, Terminator, TerminatorKind, UnOp,
TerminatorKind, UnOp,
}; };
use rustc_middle::ty::layout::ValidityRequirement; use rustc_middle::ty::layout::ValidityRequirement;
use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::util::IntTypeExt;
use rustc_middle::ty::{self, ParamEnv, SubstsRef, Ty, TyCtxt}; use rustc_middle::ty::{self, ParamEnv, SubstsRef, Ty, TyCtxt};
use rustc_span::symbol::Symbol; use rustc_span::symbol::Symbol;
use rustc_target::abi::FieldIdx;
pub struct InstCombine; pub struct InstCombine;
@ -187,7 +187,7 @@ impl<'tcx> InstCombineContext<'tcx, '_> {
for (i, field) in variant.fields.iter().enumerate() { for (i, field) in variant.fields.iter().enumerate() {
let field_ty = field.ty(self.tcx, substs); let field_ty = field.ty(self.tcx, substs);
if field_ty == *cast_ty { if field_ty == *cast_ty {
let place = place.project_deeper(&[ProjectionElem::Field(Field::from_usize(i), *cast_ty)], self.tcx); let place = place.project_deeper(&[ProjectionElem::Field(FieldIdx::from_usize(i), *cast_ty)], self.tcx);
let operand = if operand.is_move() { Operand::Move(place) } else { Operand::Copy(place) }; let operand = if operand.is_move() { Operand::Move(place) } else { Operand::Copy(place) };
*rvalue = Rvalue::Use(operand); *rvalue = Rvalue::Use(operand);
return; return;

View file

@ -6,7 +6,7 @@ use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::symbol::{sym, Symbol}; use rustc_span::symbol::{sym, Symbol};
use rustc_span::Span; use rustc_span::Span;
use rustc_target::abi::VariantIdx; use rustc_target::abi::{FieldIdx, VariantIdx};
pub struct LowerIntrinsics; pub struct LowerIntrinsics;
@ -211,7 +211,7 @@ impl<'tcx> MirPass<'tcx> for LowerIntrinsics {
Some(sym::Some), Some(sym::Some),
VariantIdx::from_u32(1), VariantIdx::from_u32(1),
), ),
PlaceElem::Field(Field::from_u32(0), *dest_ty), PlaceElem::Field(FieldIdx::from_u32(0), *dest_ty),
], ],
tcx, tcx,
), ),

View file

@ -1,10 +1,11 @@
use rustc_index::bit_set::ChunkedBitSet; use rustc_index::bit_set::ChunkedBitSet;
use rustc_middle::mir::{Body, Field, TerminatorKind}; use rustc_middle::mir::{Body, TerminatorKind};
use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt, VariantDef}; use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt, VariantDef};
use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex};
use rustc_mir_dataflow::{self, move_path_children_matching, Analysis, MoveDataParamEnv}; use rustc_mir_dataflow::{self, move_path_children_matching, Analysis, MoveDataParamEnv};
use rustc_target::abi::FieldIdx;
use crate::MirPass; use crate::MirPass;
@ -130,7 +131,7 @@ fn is_needs_drop_and_init<'tcx>(
.fields .fields
.iter() .iter()
.enumerate() .enumerate()
.map(|(f, field)| (Field::from_usize(f), field.ty(tcx, substs), mpi)) .map(|(f, field)| (FieldIdx::from_usize(f), field.ty(tcx, substs), mpi))
.any(field_needs_drop_and_init) .any(field_needs_drop_and_init)
}) })
} }
@ -138,7 +139,7 @@ fn is_needs_drop_and_init<'tcx>(
ty::Tuple(fields) => fields ty::Tuple(fields) => fields
.iter() .iter()
.enumerate() .enumerate()
.map(|(f, f_ty)| (Field::from_usize(f), f_ty, mpi)) .map(|(f, f_ty)| (FieldIdx::from_usize(f), f_ty, mpi))
.any(field_needs_drop_and_init), .any(field_needs_drop_and_init),
_ => true, _ => true,

View file

@ -5,7 +5,7 @@ use rustc_middle::mir::*;
use rustc_middle::ty::query::Providers; use rustc_middle::ty::query::Providers;
use rustc_middle::ty::InternalSubsts; use rustc_middle::ty::InternalSubsts;
use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, Ty, TyCtxt}; use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, Ty, TyCtxt};
use rustc_target::abi::{VariantIdx, FIRST_VARIANT}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT};
use rustc_index::vec::{Idx, IndexVec}; use rustc_index::vec::{Idx, IndexVec};
@ -308,7 +308,7 @@ impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {} fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> { fn field_subpath(&self, _path: Self::Path, _field: FieldIdx) -> Option<Self::Path> {
None None
} }
fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> { fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
@ -501,7 +501,7 @@ impl<'tcx> CloneShimBuilder<'tcx> {
// created by block 2*i. We store this block in `unwind` so that the next clone block // created by block 2*i. We store this block in `unwind` so that the next clone block
// will unwind to it if cloning fails. // will unwind to it if cloning fails.
let field = Field::new(i); let field = FieldIdx::new(i);
let src_field = self.tcx.mk_place_field(src, field, ity); let src_field = self.tcx.mk_place_field(src, field, ity);
let dest_field = self.tcx.mk_place_field(dest, field, ity); let dest_field = self.tcx.mk_place_field(dest, field, ity);
@ -724,7 +724,7 @@ fn build_call_shim<'tcx>(
if let Some(untuple_args) = untuple_args { if let Some(untuple_args) = untuple_args {
let tuple_arg = Local::new(1 + (sig.inputs().len() - 1)); let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
args.extend(untuple_args.iter().enumerate().map(|(i, ity)| { args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity)) Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), FieldIdx::new(i), *ity))
})); }));
} }

View file

@ -6,6 +6,7 @@ use rustc_middle::mir::visit::*;
use rustc_middle::mir::*; use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_mir_dataflow::value_analysis::{excluded_locals, iter_fields}; use rustc_mir_dataflow::value_analysis::{excluded_locals, iter_fields};
use rustc_target::abi::FieldIdx;
pub struct ScalarReplacementOfAggregates; pub struct ScalarReplacementOfAggregates;
@ -115,7 +116,7 @@ fn escaping_locals(excluded: &BitSet<Local>, body: &Body<'_>) -> BitSet<Local> {
struct ReplacementMap<'tcx> { struct ReplacementMap<'tcx> {
/// Pre-computed list of all "new" locals for each "old" local. This is used to expand storage /// Pre-computed list of all "new" locals for each "old" local. This is used to expand storage
/// and deinit statement and debuginfo. /// and deinit statement and debuginfo.
fragments: IndexVec<Local, Option<IndexVec<Field, Option<(Ty<'tcx>, Local)>>>>, fragments: IndexVec<Local, Option<IndexVec<FieldIdx, Option<(Ty<'tcx>, Local)>>>>,
} }
impl<'tcx> ReplacementMap<'tcx> { impl<'tcx> ReplacementMap<'tcx> {
@ -129,7 +130,7 @@ impl<'tcx> ReplacementMap<'tcx> {
fn place_fragments( fn place_fragments(
&self, &self,
place: Place<'tcx>, place: Place<'tcx>,
) -> Option<impl Iterator<Item = (Field, Ty<'tcx>, Local)> + '_> { ) -> Option<impl Iterator<Item = (FieldIdx, Ty<'tcx>, Local)> + '_> {
let local = place.as_local()?; let local = place.as_local()?;
let fields = self.fragments[local].as_ref()?; let fields = self.fragments[local].as_ref()?;
Some(fields.iter_enumerated().filter_map(|(field, &opt_ty_local)| { Some(fields.iter_enumerated().filter_map(|(field, &opt_ty_local)| {