]>
Commit | Line | Data |
---|---|---|
ba9703b0 XL |
1 | //! Structural const qualification. |
2 | //! | |
3 | //! See the `Qualif` trait for more info. | |
e74abb32 | 4 | |
fc512014 | 5 | use rustc_errors::ErrorReported; |
c295e0f8 XL |
6 | use rustc_hir as hir; |
7 | use rustc_infer::infer::TyCtxtInferExt; | |
ba9703b0 | 8 | use rustc_middle::mir::*; |
f9f354fc | 9 | use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty}; |
dfeec247 | 10 | use rustc_span::DUMMY_SP; |
c295e0f8 XL |
11 | use rustc_trait_selection::traits::{ |
12 | self, ImplSource, Obligation, ObligationCause, SelectionContext, | |
13 | }; | |
e74abb32 | 14 | |
f9f354fc | 15 | use super::ConstCx; |
e74abb32 | 16 | |
fc512014 XL |
17 | pub fn in_any_value_of_ty( |
18 | cx: &ConstCx<'_, 'tcx>, | |
19 | ty: Ty<'tcx>, | |
20 | error_occured: Option<ErrorReported>, | |
21 | ) -> ConstQualifs { | |
60c5eb7d XL |
22 | ConstQualifs { |
23 | has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty), | |
3c0e092e XL |
24 | needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty), |
25 | needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty), | |
f9f354fc | 26 | custom_eq: CustomEq::in_any_value_of_ty(cx, ty), |
fc512014 | 27 | error_occured, |
e74abb32 XL |
28 | } |
29 | } | |
30 | ||
31 | /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some | |
ba9703b0 | 32 | /// code for promotion or prevent it from evaluating at compile time. |
e74abb32 | 33 | /// |
ba9703b0 XL |
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 | |
cdc7bbd5 | 37 | /// needn't reject code unless it actually constructs and operates on the qualified variant. |
ba9703b0 XL |
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 | |
cdc7bbd5 | 41 | /// projection of a local) is assigned a qualified value, that local itself becomes qualified. |
e74abb32 | 42 | pub trait Qualif { |
e74abb32 XL |
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 | ||
3c0e092e XL |
49 | /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted. |
50 | const ALLOW_PROMOTED: bool = false; | |
51 | ||
ba9703b0 | 52 | /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`. |
60c5eb7d XL |
53 | fn in_qualifs(qualifs: &ConstQualifs) -> bool; |
54 | ||
ba9703b0 XL |
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-insenstive, 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. | |
62 | fn in_any_value_of_ty(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. | |
f9f354fc XL |
72 | fn in_adt_inherently( |
73 | cx: &ConstCx<'_, 'tcx>, | |
74 | adt: &'tcx AdtDef, | |
75 | substs: SubstsRef<'tcx>, | |
76 | ) -> bool; | |
e74abb32 XL |
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 { | |
e74abb32 XL |
87 | const ANALYSIS_NAME: &'static str = "flow_has_mut_interior"; |
88 | ||
60c5eb7d XL |
89 | fn in_qualifs(qualifs: &ConstQualifs) -> bool { |
90 | qualifs.has_mut_interior | |
91 | } | |
92 | ||
e74abb32 | 93 | fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { |
f035d41b | 94 | !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) |
e74abb32 XL |
95 | } |
96 | ||
f9f354fc | 97 | fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool { |
ba9703b0 XL |
98 | // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently. |
99 | // It arises structurally for all other types. | |
100 | Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type() | |
e74abb32 XL |
101 | } |
102 | } | |
103 | ||
104 | /// Constant containing an ADT that implements `Drop`. | |
3c0e092e XL |
105 | /// This must be ruled out because implicit promotion would remove side-effects |
106 | /// that occur as part of dropping that value. N.B., the implicit promotion has | |
107 | /// to reject const Drop implementations because even if side-effects are ruled | |
108 | /// out through other means, the execution of the drop could diverge. | |
109 | pub struct NeedsDrop; | |
110 | ||
111 | impl Qualif for NeedsDrop { | |
112 | const ANALYSIS_NAME: &'static str = "flow_needs_drop"; | |
113 | const IS_CLEARED_ON_MOVE: bool = true; | |
114 | ||
115 | fn in_qualifs(qualifs: &ConstQualifs) -> bool { | |
116 | qualifs.needs_drop | |
117 | } | |
118 | ||
119 | fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { | |
120 | ty.needs_drop(cx.tcx, cx.param_env) | |
121 | } | |
122 | ||
123 | fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool { | |
124 | adt.has_dtor(cx.tcx) | |
125 | } | |
126 | } | |
127 | ||
128 | /// Constant containing an ADT that implements non-const `Drop`. | |
129 | /// This must be ruled out because we cannot run `Drop` during compile-time. | |
c295e0f8 | 130 | pub struct NeedsNonConstDrop; |
e74abb32 | 131 | |
c295e0f8 XL |
132 | impl Qualif for NeedsNonConstDrop { |
133 | const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop"; | |
e74abb32 | 134 | const IS_CLEARED_ON_MOVE: bool = true; |
3c0e092e | 135 | const ALLOW_PROMOTED: bool = true; |
e74abb32 | 136 | |
60c5eb7d | 137 | fn in_qualifs(qualifs: &ConstQualifs) -> bool { |
3c0e092e | 138 | qualifs.needs_non_const_drop |
60c5eb7d XL |
139 | } |
140 | ||
c295e0f8 XL |
141 | fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, mut ty: Ty<'tcx>) -> bool { |
142 | // Avoid selecting for simple cases. | |
143 | match ty::util::needs_drop_components(ty, &cx.tcx.data_layout).as_deref() { | |
144 | Ok([]) => return false, | |
145 | Err(ty::util::AlwaysRequiresDrop) => return true, | |
146 | // If we've got a single component, select with that | |
147 | // to increase the chance that we hit the selection cache. | |
148 | Ok([t]) => ty = t, | |
149 | Ok([..]) => {} | |
150 | } | |
151 | ||
3c0e092e | 152 | let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else { |
c295e0f8 XL |
153 | // there is no way to define a type that needs non-const drop |
154 | // without having the lang item present. | |
155 | return false; | |
156 | }; | |
157 | let trait_ref = | |
158 | ty::TraitRef { def_id: drop_trait, substs: cx.tcx.mk_substs_trait(ty, &[]) }; | |
159 | let obligation = Obligation::new( | |
160 | ObligationCause::dummy(), | |
161 | cx.param_env, | |
162 | ty::Binder::dummy(ty::TraitPredicate { | |
163 | trait_ref, | |
164 | constness: ty::BoundConstness::ConstIfConst, | |
3c0e092e | 165 | polarity: ty::ImplPolarity::Positive, |
c295e0f8 XL |
166 | }), |
167 | ); | |
168 | ||
169 | let implsrc = cx.tcx.infer_ctxt().enter(|infcx| { | |
170 | let mut selcx = SelectionContext::with_constness(&infcx, hir::Constness::Const); | |
171 | selcx.select(&obligation) | |
172 | }); | |
3c0e092e XL |
173 | !matches!( |
174 | implsrc, | |
175 | Ok(Some( | |
176 | ImplSource::ConstDrop(_) | ImplSource::Param(_, ty::BoundConstness::ConstIfConst) | |
177 | )) | |
178 | ) | |
e74abb32 XL |
179 | } |
180 | ||
f9f354fc | 181 | fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool { |
c295e0f8 | 182 | adt.has_non_const_dtor(cx.tcx) |
ba9703b0 XL |
183 | } |
184 | } | |
185 | ||
f9f354fc XL |
186 | /// A constant that cannot be used as part of a pattern in a `match` expression. |
187 | pub struct CustomEq; | |
188 | ||
189 | impl Qualif for CustomEq { | |
190 | const ANALYSIS_NAME: &'static str = "flow_custom_eq"; | |
191 | ||
192 | fn in_qualifs(qualifs: &ConstQualifs) -> bool { | |
193 | qualifs.custom_eq | |
194 | } | |
195 | ||
196 | fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { | |
197 | // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`, | |
198 | // we know that at least some values of that type are not structural-match. I say "some" | |
199 | // because that component may be part of an enum variant (e.g., | |
200 | // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be | |
201 | // structural-match (`Option::None`). | |
29967ef6 | 202 | let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id()); |
f9f354fc XL |
203 | traits::search_for_structural_match_violation(id, cx.body.span, cx.tcx, ty).is_some() |
204 | } | |
205 | ||
206 | fn in_adt_inherently( | |
207 | cx: &ConstCx<'_, 'tcx>, | |
208 | adt: &'tcx AdtDef, | |
209 | substs: SubstsRef<'tcx>, | |
210 | ) -> bool { | |
211 | let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); | |
f035d41b | 212 | !ty.is_structural_eq_shallow(cx.tcx) |
f9f354fc XL |
213 | } |
214 | } | |
215 | ||
ba9703b0 XL |
216 | // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. |
217 | ||
218 | /// Returns `true` if this `Rvalue` contains qualif `Q`. | |
219 | pub fn in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool | |
220 | where | |
221 | Q: Qualif, | |
222 | F: FnMut(Local) -> bool, | |
223 | { | |
224 | match rvalue { | |
f9f354fc XL |
225 | Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => { |
226 | Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) | |
227 | } | |
ba9703b0 XL |
228 | |
229 | Rvalue::Discriminant(place) | Rvalue::Len(place) => { | |
230 | in_place::<Q, _>(cx, in_local, place.as_ref()) | |
231 | } | |
232 | ||
233 | Rvalue::Use(operand) | |
234 | | Rvalue::Repeat(operand, _) | |
235 | | Rvalue::UnaryOp(_, operand) | |
c295e0f8 XL |
236 | | Rvalue::Cast(_, operand, _) |
237 | | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand), | |
ba9703b0 | 238 | |
6a06907d | 239 | Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => { |
ba9703b0 XL |
240 | in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs) |
241 | } | |
242 | ||
243 | Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { | |
244 | // Special-case reborrows to be more like a copy of the reference. | |
5869c6ff XL |
245 | if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { |
246 | let base_ty = place_base.ty(cx.body, cx.tcx).ty; | |
1b1a35ee | 247 | if let ty::Ref(..) = base_ty.kind() { |
5869c6ff | 248 | return in_place::<Q, _>(cx, in_local, place_base); |
ba9703b0 XL |
249 | } |
250 | } | |
251 | ||
252 | in_place::<Q, _>(cx, in_local, place.as_ref()) | |
253 | } | |
254 | ||
255 | Rvalue::Aggregate(kind, operands) => { | |
256 | // Return early if we know that the struct or enum being constructed is always | |
257 | // qualified. | |
f9f354fc XL |
258 | if let AggregateKind::Adt(def, _, substs, ..) = **kind { |
259 | if Q::in_adt_inherently(cx, def, substs) { | |
e74abb32 XL |
260 | return true; |
261 | } | |
3c0e092e XL |
262 | if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { |
263 | return true; | |
264 | } | |
e74abb32 | 265 | } |
ba9703b0 XL |
266 | |
267 | // Otherwise, proceed structurally... | |
268 | operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o)) | |
e74abb32 | 269 | } |
ba9703b0 XL |
270 | } |
271 | } | |
e74abb32 | 272 | |
ba9703b0 XL |
273 | /// Returns `true` if this `Place` contains qualif `Q`. |
274 | pub fn in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool | |
275 | where | |
276 | Q: Qualif, | |
277 | F: FnMut(Local) -> bool, | |
278 | { | |
5869c6ff XL |
279 | let mut place = place; |
280 | while let Some((place_base, elem)) = place.last_projection() { | |
281 | match elem { | |
ba9703b0 XL |
282 | ProjectionElem::Index(index) if in_local(index) => return true, |
283 | ||
284 | ProjectionElem::Deref | |
285 | | ProjectionElem::Field(_, _) | |
286 | | ProjectionElem::ConstantIndex { .. } | |
287 | | ProjectionElem::Subslice { .. } | |
288 | | ProjectionElem::Downcast(_, _) | |
289 | | ProjectionElem::Index(_) => {} | |
290 | } | |
291 | ||
5869c6ff XL |
292 | let base_ty = place_base.ty(cx.body, cx.tcx); |
293 | let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty; | |
ba9703b0 XL |
294 | if !Q::in_any_value_of_ty(cx, proj_ty) { |
295 | return false; | |
296 | } | |
297 | ||
5869c6ff | 298 | place = place_base; |
ba9703b0 XL |
299 | } |
300 | ||
5869c6ff | 301 | assert!(place.projection.is_empty()); |
ba9703b0 XL |
302 | in_local(place.local) |
303 | } | |
304 | ||
305 | /// Returns `true` if this `Operand` contains qualif `Q`. | |
306 | pub fn in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool | |
307 | where | |
308 | Q: Qualif, | |
309 | F: FnMut(Local) -> bool, | |
310 | { | |
311 | let constant = match operand { | |
312 | Operand::Copy(place) | Operand::Move(place) => { | |
313 | return in_place::<Q, _>(cx, in_local, place.as_ref()); | |
314 | } | |
315 | ||
316 | Operand::Constant(c) => c, | |
317 | }; | |
318 | ||
319 | // Check the qualifs of the value of `const` items. | |
6a06907d | 320 | if let Some(ct) = constant.literal.const_for_ty() { |
94222f64 | 321 | if let ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs_: _, promoted }) = ct.val { |
3c0e092e XL |
322 | // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible |
323 | // only for `NeedsNonConstDrop` with precise drop checking. This is the only const | |
324 | // check performed after the promotion. Verify that with an assertion. | |
325 | assert!(promoted.is_none() || Q::ALLOW_PROMOTED); | |
6a06907d | 326 | // Don't peek inside trait associated constants. |
3c0e092e | 327 | if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() { |
6a06907d XL |
328 | let qualifs = if let Some((did, param_did)) = def.as_const_arg() { |
329 | cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did)) | |
330 | } else { | |
331 | cx.tcx.at(constant.span).mir_const_qualif(def.did) | |
332 | }; | |
333 | ||
334 | if !Q::in_qualifs(&qualifs) { | |
335 | return false; | |
336 | } | |
ba9703b0 | 337 | |
6a06907d XL |
338 | // Just in case the type is more specific than |
339 | // the definition, e.g., impl associated const | |
340 | // with type parameters, take it into account. | |
341 | } | |
ba9703b0 | 342 | } |
e74abb32 | 343 | } |
ba9703b0 | 344 | // Otherwise use the qualifs of the type. |
6a06907d | 345 | Q::in_any_value_of_ty(cx, constant.literal.ty()) |
e74abb32 | 346 | } |