• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Structural const qualification.
2 //!
3 //! See the `Qualif` trait for more info.
4 
5 use rustc_errors::ErrorGuaranteed;
6 use rustc_hir::LangItem;
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_middle::mir;
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
11 use rustc_trait_selection::traits::{
12     self, ImplSource, Obligation, ObligationCause, ObligationCtxt, SelectionContext,
13 };
14 
15 use super::ConstCx;
16 
in_any_value_of_ty<'tcx>( cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>, tainted_by_errors: Option<ErrorGuaranteed>, ) -> ConstQualifs17 pub fn in_any_value_of_ty<'tcx>(
18     cx: &ConstCx<'_, 'tcx>,
19     ty: Ty<'tcx>,
20     tainted_by_errors: Option<ErrorGuaranteed>,
21 ) -> ConstQualifs {
22     ConstQualifs {
23         has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
24         needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
25         needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
26         custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
27         tainted_by_errors,
28     }
29 }
30 
31 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
32 /// code for promotion or prevent it from evaluating at compile time.
33 ///
34 /// Normally, we would determine what qualifications apply to each type and error when an illegal
35 /// operation is performed on such a type. However, this was found to be too imprecise, especially
36 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
37 /// needn't reject code unless it actually constructs and operates on the qualified variant.
38 ///
39 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
40 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
41 /// projection of a local) is assigned a qualified value, that local itself becomes qualified.
42 pub trait Qualif {
43     /// The name of the file used to debug the dataflow analysis that computes this qualif.
44     const ANALYSIS_NAME: &'static str;
45 
46     /// Whether this `Qualif` is cleared when a local is moved from.
47     const IS_CLEARED_ON_MOVE: bool = false;
48 
49     /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
50     const ALLOW_PROMOTED: bool = false;
51 
52     /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
in_qualifs(qualifs: &ConstQualifs) -> bool53     fn in_qualifs(qualifs: &ConstQualifs) -> bool;
54 
55     /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
56     ///
57     /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
58     /// propagation is context-insensitive, this includes function arguments and values returned
59     /// from a call to another function.
60     ///
61     /// It also determines the `Qualif`s for primitive types.
in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool62     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
63 
64     /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
65     ///
66     /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
67     /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
68     /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
69     /// with a custom `Drop` impl is inherently `NeedsDrop`.
70     ///
71     /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, substs: SubstsRef<'tcx>, ) -> bool72     fn in_adt_inherently<'tcx>(
73         cx: &ConstCx<'_, 'tcx>,
74         adt: AdtDef<'tcx>,
75         substs: SubstsRef<'tcx>,
76     ) -> bool;
77 }
78 
79 /// 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.
84 pub struct HasMutInterior;
85 
86 impl Qualif for HasMutInterior {
87     const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
88 
in_qualifs(qualifs: &ConstQualifs) -> bool89     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
90         qualifs.has_mut_interior
91     }
92 
in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool93     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
94         !ty.is_freeze(cx.tcx, cx.param_env)
95     }
96 
in_adt_inherently<'tcx>( _cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, _: SubstsRef<'tcx>, ) -> bool97     fn in_adt_inherently<'tcx>(
98         _cx: &ConstCx<'_, 'tcx>,
99         adt: AdtDef<'tcx>,
100         _: SubstsRef<'tcx>,
101     ) -> bool {
102         // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
103         // It arises structurally for all other types.
104         adt.is_unsafe_cell()
105     }
106 }
107 
108 /// Constant containing an ADT that implements `Drop`.
109 /// This must be ruled out because implicit promotion would remove side-effects
110 /// that occur as part of dropping that value. N.B., the implicit promotion has
111 /// to reject const Drop implementations because even if side-effects are ruled
112 /// out through other means, the execution of the drop could diverge.
113 pub struct NeedsDrop;
114 
115 impl Qualif for NeedsDrop {
116     const ANALYSIS_NAME: &'static str = "flow_needs_drop";
117     const IS_CLEARED_ON_MOVE: bool = true;
118 
in_qualifs(qualifs: &ConstQualifs) -> bool119     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
120         qualifs.needs_drop
121     }
122 
in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool123     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
124         ty.needs_drop(cx.tcx, cx.param_env)
125     }
126 
in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, _: SubstsRef<'tcx>, ) -> bool127     fn in_adt_inherently<'tcx>(
128         cx: &ConstCx<'_, 'tcx>,
129         adt: AdtDef<'tcx>,
130         _: SubstsRef<'tcx>,
131     ) -> bool {
132         adt.has_dtor(cx.tcx)
133     }
134 }
135 
136 /// Constant containing an ADT that implements non-const `Drop`.
137 /// This must be ruled out because we cannot run `Drop` during compile-time.
138 pub struct NeedsNonConstDrop;
139 
140 impl Qualif for NeedsNonConstDrop {
141     const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
142     const IS_CLEARED_ON_MOVE: bool = true;
143     const ALLOW_PROMOTED: bool = true;
144 
in_qualifs(qualifs: &ConstQualifs) -> bool145     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
146         qualifs.needs_non_const_drop
147     }
148 
149     #[instrument(level = "trace", skip(cx), ret)]
in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool150     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
151         // Avoid selecting for simple cases, such as builtin types.
152         if ty::util::is_trivially_const_drop(ty) {
153             return false;
154         }
155 
156         let obligation = Obligation::new(
157             cx.tcx,
158             ObligationCause::dummy_with_span(cx.body.span),
159             cx.param_env,
160             ty::TraitRef::from_lang_item(cx.tcx, LangItem::Destruct, cx.body.span, [ty])
161                 .with_constness(ty::BoundConstness::ConstIfConst),
162         );
163 
164         let infcx = cx.tcx.infer_ctxt().build();
165         let mut selcx = SelectionContext::new(&infcx);
166         let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
167             // If we couldn't select a const destruct candidate, then it's bad
168             return true;
169         };
170 
171         trace!(?impl_src);
172 
173         if !matches!(
174             impl_src,
175             ImplSource::Builtin(_) | ImplSource::Param(_, ty::BoundConstness::ConstIfConst)
176         ) {
177             // If our const destruct candidate is not ConstDestruct or implied by the param env,
178             // then it's bad
179             return true;
180         }
181 
182         if impl_src.borrow_nested_obligations().is_empty() {
183             return false;
184         }
185 
186         // If we had any errors, then it's bad
187         let ocx = ObligationCtxt::new(&infcx);
188         ocx.register_obligations(impl_src.nested_obligations());
189         let errors = ocx.select_all_or_error();
190         !errors.is_empty()
191     }
192 
in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, _: SubstsRef<'tcx>, ) -> bool193     fn in_adt_inherently<'tcx>(
194         cx: &ConstCx<'_, 'tcx>,
195         adt: AdtDef<'tcx>,
196         _: SubstsRef<'tcx>,
197     ) -> bool {
198         adt.has_non_const_dtor(cx.tcx)
199     }
200 }
201 
202 /// A constant that cannot be used as part of a pattern in a `match` expression.
203 pub struct CustomEq;
204 
205 impl Qualif for CustomEq {
206     const ANALYSIS_NAME: &'static str = "flow_custom_eq";
207 
in_qualifs(qualifs: &ConstQualifs) -> bool208     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
209         qualifs.custom_eq
210     }
211 
in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool212     fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
213         // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
214         // we know that at least some values of that type are not structural-match. I say "some"
215         // because that component may be part of an enum variant (e.g.,
216         // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
217         // structural-match (`Option::None`).
218         traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some()
219     }
220 
in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, def: AdtDef<'tcx>, substs: SubstsRef<'tcx>, ) -> bool221     fn in_adt_inherently<'tcx>(
222         cx: &ConstCx<'_, 'tcx>,
223         def: AdtDef<'tcx>,
224         substs: SubstsRef<'tcx>,
225     ) -> bool {
226         let ty = Ty::new_adt(cx.tcx, def, substs);
227         !ty.is_structural_eq_shallow(cx.tcx)
228     }
229 }
230 
231 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
232 
233 /// Returns `true` if this `Rvalue` contains qualif `Q`.
in_rvalue<'tcx, Q, F>( cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>, ) -> bool where Q: Qualif, F: FnMut(Local) -> bool,234 pub fn in_rvalue<'tcx, Q, F>(
235     cx: &ConstCx<'_, 'tcx>,
236     in_local: &mut F,
237     rvalue: &Rvalue<'tcx>,
238 ) -> bool
239 where
240     Q: Qualif,
241     F: FnMut(Local) -> bool,
242 {
243     match rvalue {
244         Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
245             Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
246         }
247 
248         Rvalue::Discriminant(place) | Rvalue::Len(place) => {
249             in_place::<Q, _>(cx, in_local, place.as_ref())
250         }
251 
252         Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
253 
254         Rvalue::Use(operand)
255         | Rvalue::Repeat(operand, _)
256         | Rvalue::UnaryOp(_, operand)
257         | Rvalue::Cast(_, operand, _)
258         | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand),
259 
260         Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
261             in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
262         }
263 
264         Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
265             // Special-case reborrows to be more like a copy of the reference.
266             if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
267                 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
268                 if let ty::Ref(..) = base_ty.kind() {
269                     return in_place::<Q, _>(cx, in_local, place_base);
270                 }
271             }
272 
273             in_place::<Q, _>(cx, in_local, place.as_ref())
274         }
275 
276         Rvalue::Aggregate(kind, operands) => {
277             // Return early if we know that the struct or enum being constructed is always
278             // qualified.
279             if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind {
280                 let def = cx.tcx.adt_def(adt_did);
281                 if Q::in_adt_inherently(cx, def, substs) {
282                     return true;
283                 }
284                 if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) {
285                     return true;
286                 }
287             }
288 
289             // Otherwise, proceed structurally...
290             operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
291         }
292     }
293 }
294 
295 /// Returns `true` if this `Place` contains qualif `Q`.
in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool where Q: Qualif, F: FnMut(Local) -> bool,296 pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
297 where
298     Q: Qualif,
299     F: FnMut(Local) -> bool,
300 {
301     let mut place = place;
302     while let Some((place_base, elem)) = place.last_projection() {
303         match elem {
304             ProjectionElem::Index(index) if in_local(index) => return true,
305 
306             ProjectionElem::Deref
307             | ProjectionElem::Field(_, _)
308             | ProjectionElem::OpaqueCast(_)
309             | ProjectionElem::ConstantIndex { .. }
310             | ProjectionElem::Subslice { .. }
311             | ProjectionElem::Downcast(_, _)
312             | ProjectionElem::Index(_) => {}
313         }
314 
315         let base_ty = place_base.ty(cx.body, cx.tcx);
316         let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
317         if !Q::in_any_value_of_ty(cx, proj_ty) {
318             return false;
319         }
320 
321         place = place_base;
322     }
323 
324     assert!(place.projection.is_empty());
325     in_local(place.local)
326 }
327 
328 /// Returns `true` if this `Operand` contains qualif `Q`.
in_operand<'tcx, Q, F>( cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>, ) -> bool where Q: Qualif, F: FnMut(Local) -> bool,329 pub fn in_operand<'tcx, Q, F>(
330     cx: &ConstCx<'_, 'tcx>,
331     in_local: &mut F,
332     operand: &Operand<'tcx>,
333 ) -> bool
334 where
335     Q: Qualif,
336     F: FnMut(Local) -> bool,
337 {
338     let constant = match operand {
339         Operand::Copy(place) | Operand::Move(place) => {
340             return in_place::<Q, _>(cx, in_local, place.as_ref());
341         }
342 
343         Operand::Constant(c) => c,
344     };
345 
346     // Check the qualifs of the value of `const` items.
347     let uneval = match constant.literal {
348         ConstantKind::Ty(ct)
349             if matches!(
350                 ct.kind(),
351                 ty::ConstKind::Param(_) | ty::ConstKind::Error(_) | ty::ConstKind::Value(_)
352             ) =>
353         {
354             None
355         }
356         ConstantKind::Ty(c) => {
357             bug!("expected ConstKind::Param or ConstKind::Value here, found {:?}", c)
358         }
359         ConstantKind::Unevaluated(uv, _) => Some(uv),
360         ConstantKind::Val(..) => None,
361     };
362 
363     if let Some(mir::UnevaluatedConst { def, substs: _, promoted }) = uneval {
364         // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
365         // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
366         // check performed after the promotion. Verify that with an assertion.
367         assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
368 
369         // Don't peek inside trait associated constants.
370         if promoted.is_none() && cx.tcx.trait_of_item(def).is_none() {
371             let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
372 
373             if !Q::in_qualifs(&qualifs) {
374                 return false;
375             }
376 
377             // Just in case the type is more specific than
378             // the definition, e.g., impl associated const
379             // with type parameters, take it into account.
380         }
381     }
382 
383     // Otherwise use the qualifs of the type.
384     Q::in_any_value_of_ty(cx, constant.literal.ty())
385 }
386