Skip to content

Commit 871b595

Browse files
committed
Auto merge of #111913 - oli-obk:valtrees2, r=lcnr
Only rewrite valtree-constants to patterns and keep other constants opaque Now that we can reliably fall back to comparing constants with `PartialEq::eq` to the match scrutinee, we can 1. eagerly try to convert constants to valtrees 2. then deeply convert the valtree to a pattern 3. if the to-valtree conversion failed, create an "opaque constant" pattern. This PR specifically avoids any behavioral changes or major cleanups. What we can now do as follow ups is * move the two remaining call sites to `destructure_mir_constant` off that query * make valtree to pattern conversion infallible * this needs to be done after careful analysis of the effects. There may be user visible changes from that. based on #111768
2 parents ad8304a + 3c02cfc commit 871b595

File tree

21 files changed

+302
-325
lines changed

21 files changed

+302
-325
lines changed

compiler/rustc_const_eval/src/const_eval/mod.rs

+1-38
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@
22

33
use crate::errors::MaxNumNodesInConstErr;
44
use crate::interpret::{
5-
intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, InterpResult, MemPlaceMeta,
6-
Scalar,
5+
intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, InterpResult, Scalar,
76
};
8-
use rustc_hir::Mutability;
97
use rustc_middle::mir;
108
use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId};
119
use rustc_middle::ty::{self, TyCtxt};
@@ -131,38 +129,3 @@ pub(crate) fn try_destructure_mir_constant<'tcx>(
131129

132130
Ok(mir::DestructuredConstant { variant, fields })
133131
}
134-
135-
#[instrument(skip(tcx), level = "debug")]
136-
pub(crate) fn deref_mir_constant<'tcx>(
137-
tcx: TyCtxt<'tcx>,
138-
param_env: ty::ParamEnv<'tcx>,
139-
val: mir::ConstantKind<'tcx>,
140-
) -> mir::ConstantKind<'tcx> {
141-
let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
142-
let op = ecx.eval_mir_constant(&val, None, None).unwrap();
143-
let mplace = ecx.deref_operand(&op).unwrap();
144-
if let Some(alloc_id) = mplace.ptr.provenance {
145-
assert_eq!(
146-
tcx.global_alloc(alloc_id).unwrap_memory().0.0.mutability,
147-
Mutability::Not,
148-
"deref_mir_constant cannot be used with mutable allocations as \
149-
that could allow pattern matching to observe mutable statics",
150-
);
151-
}
152-
153-
let ty = match mplace.meta {
154-
MemPlaceMeta::None => mplace.layout.ty,
155-
// In case of unsized types, figure out the real type behind.
156-
MemPlaceMeta::Meta(scalar) => match mplace.layout.ty.kind() {
157-
ty::Str => bug!("there's no sized equivalent of a `str`"),
158-
ty::Slice(elem_ty) => tcx.mk_array(*elem_ty, scalar.to_target_usize(&tcx).unwrap()),
159-
_ => bug!(
160-
"type {} should not have metadata, but had {:?}",
161-
mplace.layout.ty,
162-
mplace.meta
163-
),
164-
},
165-
};
166-
167-
mir::ConstantKind::Val(op_to_const(&ecx, &mplace.into()), ty)
168-
}

compiler/rustc_const_eval/src/lib.rs

-4
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,6 @@ pub fn provide(providers: &mut Providers) {
5656
providers.valtree_to_const_val = |tcx, (ty, valtree)| {
5757
const_eval::valtree_to_const_value(tcx, ty::ParamEnv::empty().and(ty), valtree)
5858
};
59-
providers.deref_mir_constant = |tcx, param_env_and_value| {
60-
let (param_env, value) = param_env_and_value.into_parts();
61-
const_eval::deref_mir_constant(tcx, param_env, value)
62-
};
6359
providers.check_validity_requirement = |tcx, (init_kind, param_env_and_ty)| {
6460
util::check_validity_requirement(tcx, init_kind, param_env_and_ty)
6561
};

compiler/rustc_metadata/src/rmeta/table.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ where
439439
/// Given the metadata, extract out the value at a particular index (if any).
440440
#[inline(never)]
441441
pub(super) fn get<'a, 'tcx, M: Metadata<'a, 'tcx>>(&self, metadata: M, i: I) -> T::Value<'tcx> {
442-
debug!("LazyTable::lookup: index={:?} len={:?}", i, self.encoded_size);
442+
trace!("LazyTable::lookup: index={:?} len={:?}", i, self.encoded_size);
443443

444444
let start = self.position.get();
445445
let bytes = &metadata.blob()[start..start + self.encoded_size];

compiler/rustc_middle/src/mir/mod.rs

+1-46
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
44
55
use crate::mir::interpret::{
6-
AllocRange, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, LitToConstInput, Scalar,
6+
AllocRange, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
77
};
88
use crate::mir::visit::MirVisitable;
99
use crate::ty::codec::{TyDecoder, TyEncoder};
@@ -2461,51 +2461,6 @@ impl<'tcx> ConstantKind<'tcx> {
24612461
Self::Val(val, ty)
24622462
}
24632463

2464-
#[instrument(skip(tcx), level = "debug", ret)]
2465-
pub fn from_inline_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
2466-
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2467-
let body_id = match tcx.hir().get(hir_id) {
2468-
hir::Node::AnonConst(ac) => ac.body,
2469-
_ => span_bug!(
2470-
tcx.def_span(def_id.to_def_id()),
2471-
"from_inline_const can only process anonymous constants"
2472-
),
2473-
};
2474-
let expr = &tcx.hir().body(body_id).value;
2475-
let ty = tcx.typeck(def_id).node_type(hir_id);
2476-
2477-
let lit_input = match expr.kind {
2478-
hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2479-
hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind {
2480-
hir::ExprKind::Lit(ref lit) => {
2481-
Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2482-
}
2483-
_ => None,
2484-
},
2485-
_ => None,
2486-
};
2487-
if let Some(lit_input) = lit_input {
2488-
// If an error occurred, ignore that it's a literal and leave reporting the error up to
2489-
// mir.
2490-
match tcx.at(expr.span).lit_to_mir_constant(lit_input) {
2491-
Ok(c) => return c,
2492-
Err(_) => {}
2493-
}
2494-
}
2495-
2496-
let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
2497-
let parent_substs =
2498-
tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
2499-
let substs =
2500-
ty::InlineConstSubsts::new(tcx, ty::InlineConstSubstsParts { parent_substs, ty })
2501-
.substs;
2502-
2503-
let uneval = UnevaluatedConst { def: def_id.to_def_id(), substs, promoted: None };
2504-
debug_assert!(!uneval.has_free_regions());
2505-
2506-
Self::Unevaluated(uneval, ty)
2507-
}
2508-
25092464
/// Literals are converted to `ConstantKindVal`, const generic parameters are eagerly
25102465
/// converted to a constant, everything else becomes `Unevaluated`.
25112466
#[instrument(skip(tcx), level = "debug", ret)]

compiler/rustc_middle/src/query/mod.rs

-12
Original file line numberDiff line numberDiff line change
@@ -1081,14 +1081,6 @@ rustc_queries! {
10811081
desc { "destructuring MIR constant"}
10821082
}
10831083

1084-
/// Dereference a constant reference or raw pointer and turn the result into a constant
1085-
/// again.
1086-
query deref_mir_constant(
1087-
key: ty::ParamEnvAnd<'tcx, mir::ConstantKind<'tcx>>
1088-
) -> mir::ConstantKind<'tcx> {
1089-
desc { "dereferencing MIR constant" }
1090-
}
1091-
10921084
query const_caller_location(key: (rustc_span::Symbol, u32, u32)) -> ConstValue<'tcx> {
10931085
desc { "getting a &core::panic::Location referring to a span" }
10941086
}
@@ -1100,10 +1092,6 @@ rustc_queries! {
11001092
desc { "converting literal to const" }
11011093
}
11021094

1103-
query lit_to_mir_constant(key: LitToConstInput<'tcx>) -> Result<mir::ConstantKind<'tcx>, LitToConstError> {
1104-
desc { "converting literal to mir constant" }
1105-
}
1106-
11071095
query check_match(key: LocalDefId) -> Result<(), rustc_errors::ErrorGuaranteed> {
11081096
desc { |tcx| "match-checking `{}`", tcx.def_path_str(key) }
11091097
cache_on_disk_if { true }

compiler/rustc_mir_build/src/build/expr/as_constant.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ pub fn as_constant_inner<'tcx>(
106106
}
107107

108108
#[instrument(skip(tcx, lit_input))]
109-
pub(crate) fn lit_to_mir_constant<'tcx>(
109+
fn lit_to_mir_constant<'tcx>(
110110
tcx: TyCtxt<'tcx>,
111111
lit_input: LitToConstInput<'tcx>,
112112
) -> Result<ConstantKind<'tcx>, LitToConstError> {

compiler/rustc_mir_build/src/build/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
pub(crate) use crate::build::expr::as_constant::lit_to_mir_constant;
21
use crate::build::expr::as_place::PlaceBuilder;
32
use crate::build::scope::DropKind;
43
use rustc_apfloat::ieee::{Double, Single};

compiler/rustc_mir_build/src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ fluent_messages! { "../messages.ftl" }
3232
pub fn provide(providers: &mut Providers) {
3333
providers.check_match = thir::pattern::check_match;
3434
providers.lit_to_const = thir::constant::lit_to_const;
35-
providers.lit_to_mir_constant = build::lit_to_mir_constant;
3635
providers.mir_built = build::mir_built;
3736
providers.thir_check_unsafety = check_unsafety::thir_check_unsafety;
3837
providers.thir_body = thir::cx::thir_body;

compiler/rustc_mir_build/src/thir/constant.rs

+18
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
33
use rustc_middle::ty::{self, ParamEnv, ScalarInt, TyCtxt};
44
use rustc_span::DUMMY_SP;
55

6+
use crate::build::parse_float_into_scalar;
7+
68
pub(crate) fn lit_to_const<'tcx>(
79
tcx: TyCtxt<'tcx>,
810
lit_input: LitToConstInput<'tcx>,
@@ -46,12 +48,28 @@ pub(crate) fn lit_to_const<'tcx>(
4648
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
4749
ty::ValTree::from_scalar_int((*n).into())
4850
}
51+
(ast::LitKind::CStr(data, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().c_str()) =>
52+
{
53+
let bytes = data as &[u8];
54+
ty::ValTree::from_raw_bytes(tcx, bytes)
55+
}
4956
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
5057
let scalar_int =
5158
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?;
5259
ty::ValTree::from_scalar_int(scalar_int)
5360
}
5461
(ast::LitKind::Bool(b), ty::Bool) => ty::ValTree::from_scalar_int((*b).into()),
62+
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
63+
let bits = parse_float_into_scalar(*n, *fty, neg)
64+
.ok_or_else(|| {
65+
LitToConstError::Reported(tcx.sess.delay_span_bug(
66+
DUMMY_SP,
67+
format!("couldn't parse float literal: {:?}", lit_input.lit),
68+
))
69+
})?
70+
.assert_int();
71+
ty::ValTree::from_scalar_int(bits)
72+
}
5573
(ast::LitKind::Char(c), ty::Char) => ty::ValTree::from_scalar_int((*c).into()),
5674
(ast::LitKind::Err, _) => {
5775
return Err(LitToConstError::Reported(

0 commit comments

Comments
 (0)