1//! Structural const qualification.
2//!
3//! See the `Qualif` trait for more info.
45// FIXME(const_trait_impl): This API should be really reworked. It's dangerously general for
6// having basically only two use-cases that act in different ways.
78use rustc_attr_ir::lang_items::LangItem;
9use rustc_errors::ErrorGuaranteed;
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_middle::mir;
12use rustc_middle::mir::*;
13use rustc_middle::ty::{self, AdtDef, Ty, TypingMode};
14use rustc_span::bug;
15use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
16use tracing::instrument;
1718use super::ConstCx;
1920pub fn in_any_value_of_ty<'tcx>(
21 cx: &ConstCx<'_, 'tcx>,
22 ty: Ty<'tcx>,
23 tainted_by_errors: Option<ErrorGuaranteed>,
24) -> ConstQualifs {
25ConstQualifs {
26 has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
27 needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
28 needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
29tainted_by_errors,
30 }
31}
3233/// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
34/// code for promotion or prevent it from evaluating at compile time.
35///
36/// Normally, we would determine what qualifications apply to each type and error when an illegal
37/// operation is performed on such a type. However, this was found to be too imprecise, especially
38/// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
39/// needn't reject code unless it actually constructs and operates on the qualified variant.
40///
41/// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
42/// type-based one). Qualifications propagate structurally across variables: If a local (or a
43/// projection of a local) is assigned a qualified value, that local itself becomes qualified.
44///
45/// Note that whenever this analysis relies on something being UB and hence impossible in
46/// well-defined code, it is crucial that const-eval actually detects that UB! Const-eval is not
47/// guaranteed to detect all UB, and if it would skip this particular UB we may end up executing
48/// code that has not been const-checked.
49pub trait Qualif {
50/// The name of the file used to debug the dataflow analysis that computes this qualif.
51const ANALYSIS_NAME: &'static str;
5253/// Whether this `Qualif` is cleared when a local is moved from.
54const IS_CLEARED_ON_MOVE: bool;
5556/// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
57const ALLOW_PROMOTED: bool;
5859/// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
60fn in_qualifs(qualifs: &ConstQualifs) -> bool;
6162/// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
63 ///
64 /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
65 /// propagation is context-insensitive, this includes function arguments and values returned
66 /// from a call to another function.
67 ///
68 /// It also determines the `Qualif`s for primitive types.
69fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
7071/// Returns `true` if the `Qualif` is structural in an ADT's fields, i.e. if we may
72 /// recurse into an operand *value* to determine whether it has this `Qualif`.
73 ///
74 /// If this returns false, `in_any_value_of_ty` will be invoked to determine the
75 /// final qualif for this ADT.
76fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool;
77}
7879/// Constant containing interior mutability (`UnsafeCell<T>`).
80/// This must be ruled out to make sure that evaluating the constant at compile-time
81/// and at *any point* during the run-time would produce the same result. In particular,
82/// promotion of temporaries must not change program behavior; if the promoted could be
83/// written to, that would be a problem.
84pub struct HasMutInterior;
8586impl Qualiffor HasMutInterior {
87const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
88const IS_CLEARED_ON_MOVE: bool = false;
89const ALLOW_PROMOTED: bool = false;
9091fn in_qualifs(qualifs: &ConstQualifs) -> bool {
92qualifs.has_mut_interior
93 }
9495fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
96// Avoid selecting for simple cases, such as builtin types.
97if ty.is_trivially_freeze() {
98return false;
99 }
100101// Avoid selecting for `UnsafeCell` either.
102if ty.ty_adt_def().is_some_and(|adt| adt.is_unsafe_cell()) {
103return true;
104 }
105106// We do not use `ty.is_freeze` here, because that requires revealing opaque types, which
107 // requires borrowck, which in turn will invoke mir_const_qualifs again, causing a cycle error.
108 // Instead we invoke an obligation context manually, and provide the opaque type inference settings
109 // that allow the trait solver to just error out instead of cycling.
110let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, cx.body.span);
111let did = cx.body.source.def_id().expect_local();
112113let typing_env = if cx.tcx.use_typing_mode_post_typeck_until_borrowck() {
114cx.typing_env
115 } else {
116 ty::TypingEnv::new(cx.typing_env.param_env, TypingMode::analysis_in_body(cx.tcx, did))
117 };
118119let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
120let ocx = ObligationCtxt::new(&infcx);
121let obligation = Obligation::new(
122cx.tcx,
123ObligationCause::dummy_with_span(cx.body.span),
124param_env,
125 ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
126 );
127ocx.register_obligation(obligation);
128let errors = ocx.evaluate_obligations_error_on_ambiguity();
129 !errors.no_errors()
130 }
131132fn is_structural_in_adt_value<'tcx>(_cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
133// Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
134 // It arises structurally for all other types.
135!adt.is_unsafe_cell()
136 }
137}
138139/// Constant containing an ADT that implements `Drop`.
140/// This must be ruled out because implicit promotion would remove side-effects
141/// that occur as part of dropping that value. N.B., the implicit promotion has
142/// to reject const Drop implementations because even if side-effects are ruled
143/// out through other means, the execution of the drop could diverge.
144pub struct NeedsDrop;
145146impl Qualiffor NeedsDrop {
147const ANALYSIS_NAME: &'static str = "flow_needs_drop";
148const IS_CLEARED_ON_MOVE: bool = true;
149const ALLOW_PROMOTED: bool = true;
150151fn in_qualifs(qualifs: &ConstQualifs) -> bool {
152qualifs.needs_drop
153 }
154155fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
156ty.needs_drop(cx.tcx, cx.typing_env)
157 }
158159fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
160 !adt.has_dtor(cx.tcx)
161 }
162}
163164/// Constant containing an ADT that implements non-const `Drop`.
165/// This must be ruled out because we cannot run `Drop` during compile-time.
166pub struct NeedsNonConstDrop;
167168impl Qualiffor NeedsNonConstDrop {
169const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
170const IS_CLEARED_ON_MOVE: bool = true;
171const ALLOW_PROMOTED: bool = true;
172173fn in_qualifs(qualifs: &ConstQualifs) -> bool {
174qualifs.needs_non_const_drop
175 }
176177{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("in_any_value_of_ty",
"rustc_const_eval::check_consts::qualifs",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_const_eval/src/check_consts/qualifs.rs"),
::tracing_core::__macro_support::Option::Some(177u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::qualifs"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if !ty.needs_drop(cx.tcx, cx.typing_env) { return false; }
let destruct_def_id =
cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
let (infcx, param_env) =
cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
let ocx = ObligationCtxt::new(&infcx);
ocx.register_obligation(Obligation::new(cx.tcx,
ObligationCause::misc(cx.body.span, cx.def_id()), param_env,
ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id,
[ty])).to_host_effect_clause(cx.tcx,
match cx.const_kind() {
rustc_hir::ConstContext::ConstFn =>
ty::BoundConstness::Maybe,
rustc_hir::ConstContext::Static(_) |
rustc_hir::ConstContext::Const { .. } =>
ty::BoundConstness::Const,
})));
!ocx.evaluate_obligations_error_on_ambiguity().no_errors()
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_const_eval/src/check_consts/qualifs.rs:177",
"rustc_const_eval::check_consts::qualifs",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_const_eval/src/check_consts/qualifs.rs"),
::tracing_core::__macro_support::Option::Some(177u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::check_consts::qualifs"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "trace", skip(cx), ret)]178fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
179// If this doesn't need drop at all, then don't select `[const] Destruct`.
180if !ty.needs_drop(cx.tcx, cx.typing_env) {
181return false;
182 }
183184// We check that the type is `[const] Destruct` since that will verify that
185 // the type is both `[const] Drop` (if a drop impl exists for the adt), *and*
186 // that the components of this type are also `[const] Destruct`. This
187 // amounts to verifying that there are no values in this ADT that may have
188 // a non-const drop.
189let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
190let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
191let ocx = ObligationCtxt::new(&infcx);
192 ocx.register_obligation(Obligation::new(
193 cx.tcx,
194 ObligationCause::misc(cx.body.span, cx.def_id()),
195 param_env,
196 ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id, [ty]))
197 .to_host_effect_clause(
198 cx.tcx,
199match cx.const_kind() {
200 rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
201 rustc_hir::ConstContext::Static(_)
202 | rustc_hir::ConstContext::Const { .. } => ty::BoundConstness::Const,
203 },
204 ),
205 ));
206 !ocx.evaluate_obligations_error_on_ambiguity().no_errors()
207 }
208209fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
210// As soon as an ADT has a destructor, then the drop becomes non-structural
211 // in its value since:
212 // 1. The destructor may have `[const]` bounds which are not present on the type.
213 // Someone needs to check that those are satisfied.
214 // While this could be instead satisfied by checking that the `[const] Drop`
215 // impl holds (i.e. replicating part of the `in_any_value_of_ty` logic above),
216 // even in this case, we have another problem, which is,
217 // 2. The destructor may *modify* the operand being dropped, so even if we
218 // did recurse on the components of the operand, we may not be even dropping
219 // the same values that were present before the custom destructor was invoked.
220!adt.has_dtor(cx.tcx)
221 }
222}
223224// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
225226/// Returns `true` if this `Rvalue` contains qualif `Q`.
227pub fn in_rvalue<'tcx, Q, F>(
228 cx: &ConstCx<'_, 'tcx>,
229 in_local: &mut F,
230 rvalue: &Rvalue<'tcx>,
231) -> bool232where
233Q: Qualif,
234 F: FnMut(Local) -> bool,
235{
236match rvalue {
237 Rvalue::ThreadLocalRef(_) => Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)),
238239 Rvalue::Discriminant(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
240241 Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
242243 Rvalue::Use(operand, _)
244 | Rvalue::Repeat(operand, _)
245 | Rvalue::UnaryOp(_, operand)
246 | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
247248 Rvalue::BinaryOp(_, (lhs, rhs)) => {
249in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
250 }
251252 Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
253// Special-case reborrows to be more like a copy of the reference.
254if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
255let base_ty = place_base.ty(cx.body, cx.tcx).ty;
256if let ty::Ref(..) = base_ty.kind() {
257return in_place::<Q, _>(cx, in_local, place_base);
258 }
259 }
260261in_place::<Q, _>(cx, in_local, place.as_ref())
262 }
263264 Rvalue::Reborrow(_, _, place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
265266 Rvalue::WrapUnsafeBinder(op, _) => in_operand::<Q, _>(cx, in_local, op),
267268 Rvalue::Aggregate(kind, operands) => {
269// Return early if we know that the struct or enum being constructed is always
270 // qualified.
271if let AggregateKind::Adt(adt_did, ..) = **kind {
272let def = cx.tcx.adt_def(adt_did);
273// Don't do any value-based reasoning for unions.
274 // Also, if the ADT is not structural in its fields,
275 // then we cannot recurse on its fields. Instead,
276 // we fall back to checking the qualif for *any* value
277 // of the ADT.
278if def.is_union() || !Q::is_structural_in_adt_value(cx, def) {
279return Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx));
280 }
281 }
282283// Otherwise, proceed structurally...
284operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
285 }
286 }
287}
288289/// Returns `true` if this `Place` contains qualif `Q`.
290pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool291where
292Q: Qualif,
293 F: FnMut(Local) -> bool,
294{
295let mut place = place;
296while let Some((place_base, elem)) = place.last_projection() {
297match elem {
298 ProjectionElem::Index(index) if in_local(index) => return true,
299300 ProjectionElem::Deref
301 | ProjectionElem::PhantomDeref
302 | ProjectionElem::Field(_, _)
303 | ProjectionElem::OpaqueCast(_)
304 | ProjectionElem::ConstantIndex { .. }
305 | ProjectionElem::Subslice { .. }
306 | ProjectionElem::Downcast(_, _)
307 | ProjectionElem::Index(_)
308 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
309 }
310311let base_ty = place_base.ty(cx.body, cx.tcx);
312let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
313if !Q::in_any_value_of_ty(cx, proj_ty) {
314return false;
315 }
316317// `Deref` currently unconditionally "qualifies" if `in_any_value_of_ty` returns true,
318 // i.e., we treat all qualifs as non-structural for deref projections. Generally,
319 // we can say very little about `*ptr` even if we know that `ptr` satisfies all
320 // sorts of properties.
321if elem == ProjectionElem::Deref {
322// We have to assume that this qualifies.
323return true;
324 }
325326 place = place_base;
327 }
328329if !place.projection.is_empty() {
::core::panicking::panic("assertion failed: place.projection.is_empty()")
};assert!(place.projection.is_empty());
330in_local(place.local)
331}
332333/// Returns `true` if this `Operand` contains qualif `Q`.
334pub fn in_operand<'tcx, Q, F>(
335 cx: &ConstCx<'_, 'tcx>,
336 in_local: &mut F,
337 operand: &Operand<'tcx>,
338) -> bool339where
340Q: Qualif,
341 F: FnMut(Local) -> bool,
342{
343let constant = match operand {
344 Operand::Copy(place) | Operand::Move(place) => {
345return in_place::<Q, _>(cx, in_local, place.as_ref());
346 }
347 Operand::RuntimeChecks(_) => return Q::in_any_value_of_ty(cx, cx.tcx.types.bool),
348349 Operand::Constant(c) => c,
350 };
351352// Check the qualifs of the value of `const` items.
353let uneval = match constant.const_ {
354 Const::Ty(_, ct) => match ct.kind() {
355 ty::ConstKind::Param(_) | ty::ConstKind::Error(_) => None,
356// Alias consts in MIR bodies don't have associated MIR (e.g. `type const`).
357ty::ConstKind::Alias(_, _) => None,
358// FIXME(mgca): Investigate whether using `None` for `ConstKind::Value` is overly
359 // strict, and if instead we should be doing some kind of value-based analysis.
360ty::ConstKind::Value(_) => None,
361_ => ::rustc_span::macros::bug_impl(None,
format_args!("expected ConstKind::Param, ConstKind::Value, ConstKind::Alias, or ConstKind::Error here, found {0:?}",
ct), Location::caller())bug!(
362"expected ConstKind::Param, ConstKind::Value, ConstKind::Alias, or ConstKind::Error here, found {:?}",
363 ct
364 ),
365 },
366 Const::Unevaluated(uv, _) => Some(uv),
367 Const::Val(..) => None,
368 };
369370if let Some(mir::UnevaluatedConst { def, args: _, promoted }) = uneval {
371// Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
372 // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
373 // check performed after the promotion. Verify that with an assertion.
374if !(promoted.is_none() || Q::ALLOW_PROMOTED) {
::core::panicking::panic("assertion failed: promoted.is_none() || Q::ALLOW_PROMOTED")
};assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
375376// Don't peak inside trait associated constants.
377if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() {
378let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
379380if !Q::in_qualifs(&qualifs) {
381return false;
382 }
383384// Just in case the type is more specific than
385 // the definition, e.g., impl associated const
386 // with type parameters, take it into account.
387}
388 }
389390// Otherwise use the qualifs of the type.
391Q::in_any_value_of_ty(cx, constant.const_.ty())
392}