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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion compiler/rustc_const_eval/src/const_eval/valtrees.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use rustc_abi::{BackendRepr, FieldIdx, VariantIdx};
use rustc_attr_ir::LangItem;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_middle::mir;
use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId, ValTreeCreationError};
Expand Down Expand Up @@ -175,6 +176,9 @@ fn const_to_valtree_inner<'tcx>(
Err(ValTreeCreationError::NonSupportedType(ty))
} else if def.variants().is_empty() {
bug!("uninhabited types should have errored and never gotten converted to valtree")
} else if tcx.is_lang_item(def.did(), LangItem::TypeId) {
let ty = ecx.read_type_id(place).report_err()?;
Ok(ty::ValTree::from_type_id(tcx, ty))
} else {
let variant = ecx.read_discriminant(place).report_err()?;
branches(
Expand Down Expand Up @@ -336,7 +340,7 @@ pub fn valtree_to_const_value<'tcx>(
}
if layout.backend_repr.is_scalar()
&& (matches!(cv.ty.kind(), ty::Tuple(_))
|| matches!(cv.ty.kind(), ty::Adt(def, _) if def.is_struct()))
|| matches!(cv.ty.kind(), ty::Adt(def, _) if def.is_struct() && !tcx.is_lang_item(def.did(), LangItem::TypeId)))
{
// A Scalar tuple/struct; we can avoid creating an allocation.
let branches = cv.to_branch();
Expand Down Expand Up @@ -432,6 +436,17 @@ fn valtree_into_mplace<'tcx>(
debug!(?imm);
ecx.write_immediate(imm, place).unwrap();
}
ty::Adt(def, _) if ecx.tcx.is_lang_item(def.did(), LangItem::TypeId) => {
let ty::ValTreeKind::TypeId(ty, _) = **valtree else {
bug!("expected a TypeId valtree");
};

// Need to create a place for this valtree.
ecx.write_type_id(ty, place).unwrap();

debug!("dump of place after writing type id:");
dump_place(ecx, place);
}
ty::Adt(_, _) | ty::Tuple(_) | ty::Array(_, _) | ty::Str | ty::Slice(_) => {
let branches = valtree.to_branch();

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_const_eval/src/interpret/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,12 +141,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// Read a value of type `TypeId`, returning the type it represents.
pub(crate) fn read_type_id(
&self,
op: &OpTy<'tcx, M::Provenance>,
src: &impl Projectable<'tcx, M::Provenance>,
) -> InterpResult<'tcx, Ty<'tcx>> {
// `TypeId` is a newtype around an array of pointers. All pointers must have the same
// provenance, and that provenance represents the type.
let ptr_size = self.pointer_size().bytes_usize();
let arr = self.project_field(op, FieldIdx::ZERO)?;
let arr = self.project_field(src, FieldIdx::ZERO)?;

let mut ty_and_hash = None;
let mut elem_iter = self.project_array_fields(&arr)?;
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/thir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,7 @@ pub enum PatKind<'tcx> {
/// much simpler.
/// * raw pointers derived from integers, other raw pointers will have already resulted in an
/// error.
/// * `TypeId`s to unify them across ctfe and runtime.
Constant {
value: ty::Value<'tcx>,
},
Expand Down
29 changes: 23 additions & 6 deletions compiler/rustc_middle/src/ty/consts/valtree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ impl<'tcx> ValTree<'tcx> {
pub fn from_scalar_int(tcx: TyCtxt<'tcx>, i: ScalarInt) -> Self {
tcx.intern_valtree(ty::ValTreeKind::Leaf(i))
}

pub fn from_type_id(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Self {
let hash = tcx.type_id_hash(ty).as_u128();
let valtree = ty::ValTree::from_scalar_int(tcx, hash.into());
let value = ty::Const::new_value(tcx, valtree, tcx.types.u128);
let branches = tcx.mk_const_list_from_iter(Some(value).into_iter());
tcx.intern_valtree(ty::ValTreeKind::TypeId(ty, branches))
}
}

impl<'tcx> Deref for ValTree<'tcx> {
Expand Down Expand Up @@ -171,7 +179,7 @@ impl<'tcx> Value<'tcx> {
pub fn to_leaf(self) -> ScalarInt {
match &**self.valtree {
ValTreeKind::Leaf(s) => *s,
ValTreeKind::Branch(..) => bug!("expected leaf, got {:?}", self),
_ => bug!("expected leaf, got {:?}", self),
}
}

Expand All @@ -181,15 +189,15 @@ impl<'tcx> Value<'tcx> {
pub fn to_branch(self) -> &'tcx [ty::Const<'tcx>] {
match &**self.valtree {
ValTreeKind::Branch(branch) => &**branch,
ValTreeKind::Leaf(..) => bug!("expected branch, got {:?}", self),
_ => bug!("expected branch, got {:?}", self),
}
}

/// Attempts to convert to a `ValTreeKind::Leaf` value.
pub fn try_to_leaf(self) -> Option<ScalarInt> {
match &**self.valtree {
ValTreeKind::Leaf(s) => Some(*s),
ValTreeKind::Branch(_) => None,
_ => None,
}
}

Expand All @@ -202,13 +210,22 @@ impl<'tcx> Value<'tcx> {
pub fn try_to_branch(self) -> Option<&'tcx [ty::Const<'tcx>]> {
match &**self.valtree {
ValTreeKind::Branch(branch) => Some(&**branch),
ValTreeKind::Leaf(_) => None,
_ => None,
}
}

/// Destructures ADT constants into the constants of their fields.
pub fn destructure_adt_const(&self) -> ty::DestructuredAdtConst<'tcx> {
let fields = self.to_branch();
let fields = match **self.valtree {
ValTreeKind::Leaf(_) => {
bug!("destructure_adt_const: expected branch or type id `{:?}`", self.ty)
}
ValTreeKind::Branch(branch) => &**branch,
ValTreeKind::TypeId(ty, consts) => {
assert_eq!(consts.len(), 1);
return ty::DestructuredAdtConst::TypeId { ty, value: consts[0] };
}
};

let (variant, fields) = match self.ty.kind() {
ty::Adt(def, _) if def.variants().is_empty() => {
Expand All @@ -222,7 +239,7 @@ impl<'tcx> Value<'tcx> {
_ => bug!("destructure_adt_const called on non-ADT type: {:?}", self.ty),
};

ty::DestructuredAdtConst { variant, fields }
ty::DestructuredAdtConst::Aggregate { variant, fields }
}
}

Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2589,8 +2589,8 @@ impl<'tcx> fmt::Debug for SymbolName<'tcx> {
}

/// The constituent parts of a type level constant of kind ADT or array.
#[derive(Copy, Clone, Debug, StableHash)]
pub struct DestructuredAdtConst<'tcx> {
pub variant: VariantIdx,
pub fields: &'tcx [ty::Const<'tcx>],
#[derive(Copy, Clone, Debug)]
pub enum DestructuredAdtConst<'tcx> {
Aggregate { variant: VariantIdx, fields: &'tcx [ty::Const<'tcx>] },
TypeId { ty: Ty<'tcx>, value: ty::Const<'tcx> },
}
11 changes: 6 additions & 5 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2000,9 +2000,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
}
return Ok(());
}
(ty::ValTreeKind::Branch(_), ty::Adt(def, args)) => {
let contents = cv.destructure_adt_const();
let fields = contents.fields.iter().copied();
(ty::ValTreeKind::Branch(_), ty::Adt(def, args))
if let ty::DestructuredAdtConst::Aggregate { variant, fields } =
cv.destructure_adt_const() =>
{
let fields = fields.iter().copied();

if def.variants().is_empty() {
self.typed_value(
Expand All @@ -2014,8 +2016,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
": ",
)?;
} else {
let variant_idx = contents.variant;
let variant_def = &def.variant(variant_idx);
let variant_def = &def.variant(variant);
self.pretty_print_value_path(variant_def.def_id, args)?;
match variant_def.ctor_kind() {
Some(CtorKind::Const) => {}
Expand Down
9 changes: 6 additions & 3 deletions compiler/rustc_mir_build/src/builder/matches/buckets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
}

(
TestKind::StringEq { value: test_val, .. },
TestableCase::Constant { value: case_val, kind: PatConstKind::String },
TestKind::CallPartialEq { value: test_val, .. },
TestableCase::Constant {
value: case_val,
kind: PatConstKind::String | PatConstKind::TypeId,
},
)
| (
TestKind::ScalarEq { value: test_val, .. },
Expand Down Expand Up @@ -362,7 +365,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
| TestKind::If
| TestKind::SliceLen { .. }
| TestKind::Range { .. }
| TestKind::StringEq { .. }
| TestKind::CallPartialEq { .. }
| TestKind::ScalarEq { .. }
| TestKind::AggregateEq { .. }
| TestKind::Deref { .. },
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_mir_build/src/builder/matches/match_pair.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::sync::Arc;

use rustc_abi::FieldIdx;
use rustc_attr_ir::LangItem;
use rustc_middle::mir::{Pinnedness, Place, PlaceElem, ProjectionElem};
use rustc_middle::thir::{Ascription, DerefPatBorrowMode, FieldPat, Pat, PatKind};
use rustc_middle::ty::{self, Ty, TypeVisitableExt};
Expand Down Expand Up @@ -359,6 +360,10 @@ impl<'tcx> InterPat<'tcx> {
PatConstKind::Float
} else if pat_ty.is_str() {
PatConstKind::String
} else if let ty::Adt(def, _) = pat_ty.kind()
&& cx.tcx.is_lang_item(def.did(), LangItem::TypeId)
{
PatConstKind::TypeId
} else {
// FIXME(Zalathar): This still covers several different
// categories (e.g. raw pointer, pattern-type)
Expand Down
8 changes: 5 additions & 3 deletions compiler/rustc_mir_build/src/builder/matches/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1230,6 +1230,8 @@ enum PatConstKind {
/// from. Tested by comparing the bytes of the whole aggregate at once,
/// rather than comparing element by element.
Aggregate,
/// Specifically `core::any::TypeId`.
TypeId,
/// Any other constant-pattern is usually tested via some kind of equality
/// check. Types that might be encountered here include:
/// - raw pointers derived from integer values
Expand Down Expand Up @@ -1305,10 +1307,10 @@ enum TestKind<'tcx> {
/// Test whether a `bool` is `true` or `false`.
If,

/// Tests the place against a string constant using string equality.
StringEq {
/// Tests the place against a constant using `PartialEq::eq`.
CallPartialEq {
/// Constant string value to test against.
/// Note that this value has type `str` (not `&str`).
/// Note that this value is not a reference, so `str`, not `&str`.
value: ty::Value<'tcx>,
},

Expand Down
39 changes: 19 additions & 20 deletions compiler/rustc_mir_build/src/builder/matches/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
TestableCase::Constant { value: _, kind: PatConstKind::IntOrChar } => {
TestKind::SwitchInt
}
TestableCase::Constant { value, kind: PatConstKind::String } => {
TestKind::StringEq { value }
TestableCase::Constant { value, kind: PatConstKind::String | PatConstKind::TypeId } => {
TestKind::CallPartialEq { value }
}
TestableCase::Constant { value, kind: PatConstKind::Aggregate } => {
TestKind::AggregateEq { value }
Expand Down Expand Up @@ -143,42 +143,41 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
self.cfg.terminate(block, self.source_info(match_start_span), terminator);
}

TestKind::StringEq { value } => {
TestKind::CallPartialEq { value } => {
let tcx = self.tcx;
let success_block = target_block(TestBranch::Success);
let fail_block = target_block(TestBranch::Failure);

let ref_str_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, tcx.types.str_);
assert!(ref_str_ty.is_imm_ref_str(), "{ref_str_ty:?}");
let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, value.ty);

// The string constant we're testing against has type `str`, but
// calling `<str as PartialEq>::eq` requires `&str` operands.
// If the constant we're testing against has type `T`,
// calling `<T as PartialEq>::eq` requires `&T` operands.
//
// Because `str` and `&str` have the same valtree representation,
// Because `T` and `&T` have the same valtree representation,
// we can "cast" to the desired type by just replacing the type.
assert!(value.ty.is_str(), "unexpected value type for StringEq test: {value:?}");
let expected_value = ty::Value { ty: ref_str_ty, valtree: value.valtree };
let expected_value = ty::Value { ty: ref_ty, valtree: value.valtree };
let expected_value_operand =
self.literal_operand(test.span, Const::from_ty_value(tcx, expected_value));

// Similarly, the scrutinized place has type `str`, but we need `&str`.
// Get a reference by doing `let actual_value_ref_place: &str = &place`.
let actual_value_ref_place = self.temp(ref_str_ty, test.span);
// Similarly, the scrutinized place has type `T`, but we need `&T`.
// Get a reference by doing `let actual_value_ref_place: &T = &place`.
let actual_value_ref_place = self.temp(ref_ty, test.span);
self.cfg.push_assign(
block,
self.source_info(test.span),
actual_value_ref_place,
Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, place),
);

// Compare two strings using `<str as std::cmp::PartialEq>::eq`.
// Compare two consts using `<T as std::cmp::PartialEq>::eq`.
// (Interestingly this means that exhaustiveness analysis relies, for soundness,
// on the `PartialEq` impl for `str` to be correct!)
self.string_compare(
self.compare_with_eq(
block,
success_block,
fail_block,
source_info,
value.ty,
expected_value_operand,
Operand::Copy(actual_value_ref_place),
);
Expand Down Expand Up @@ -259,7 +258,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
block,
self.source_info(test.span),
transmuted_expect,
Rvalue::Cast(CastKind::Transmute, expected_value_operand, base),
Rvalue::Cast(CastKind::Transmute, expected_value_operand.clone(), base),
);

actual_value_place = transmuted_place;
Expand Down Expand Up @@ -458,19 +457,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
);
}

/// Compare two values of type `&str` using `<str as std::cmp::PartialEq>::eq`.
fn string_compare(
/// Compare two values using `PartialEq::eq`.
fn compare_with_eq(
&mut self,
block: BasicBlock,
success_block: BasicBlock,
fail_block: BasicBlock,
source_info: SourceInfo,
val_ty: Ty<'tcx>,
expect: Operand<'tcx>,
val: Operand<'tcx>,
) {
let str_ty = self.tcx.types.str_;
let eq_def_id = self.tcx.require_lang_item(LangItem::PartialEq, source_info.span);
let method = trait_method(self.tcx, eq_def_id, sym::eq, &[str_ty.into(), str_ty.into()]);
let method = trait_method(self.tcx, eq_def_id, sym::eq, &[val_ty.into(), val_ty.into()]);

let bool_ty = self.tcx.types.bool;
let eq_result = self.temp(bool_ty, source_info.span);
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,9 @@ impl<'tcx> ConstToPat<'tcx> {
.lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())),
}
}
ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::TypeId) => {
PatKind::Constant { value }
}
ty::Adt(def, _) => {
assert!(!def.is_union()); // Valtree construction would never succeed for unions.
PatKind::Leaf {
Expand Down
25 changes: 15 additions & 10 deletions compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,18 +220,23 @@ fn encode_const_value<'tcx>(
// User-defined types
// Struct and enum values are encoded as their field values as literal arguments, preceded
// by V<variant-index> for enum values.
ty::Adt(adt_def, ..) => {
let contents = cv.destructure_adt_const();
if adt_def.is_enum() {
let _ = write!(s, "V{}", contents.variant.as_u32());
ty::Adt(adt_def, ..) => match cv.destructure_adt_const() {
ty::DestructuredAdtConst::Aggregate { variant, fields } => {
if adt_def.is_enum() {
let _ = write!(s, "V{}", variant.as_u32());
}
for field in fields {
let ty::ConstKind::Value(field_cv) = field.kind() else {
bug!("encode_const_value: unexpected kind `{:?}`", field.kind());
};
s.push_str(&encode_const(tcx, *field, field_cv.ty, dict, options));
}
}
for field in contents.fields {
let ty::ConstKind::Value(field_cv) = field.kind() else {
bug!("encode_const_value: unexpected kind `{:?}`", field.kind());
};
s.push_str(&encode_const(tcx, *field, field_cv.ty, dict, options));
ty::DestructuredAdtConst::TypeId { ty: _, value } => {
let ty = value.to_value().ty;
s.push_str(&encode_const(tcx, value, ty, dict, options))
}
}
},

// Pointer types
// Reference values are encoded as the values of their referents (i.e., the valtree of a
Expand Down
Loading
Loading