]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_mir/src/transform/check_consts/qualifs.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_mir / src / transform / check_consts / qualifs.rs
1 //! Structural const qualification.
2 //!
3 //! See the `Qualif` trait for more info.
4
5 use rustc_middle::mir::*;
6 use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
7 use rustc_span::DUMMY_SP;
8 use rustc_trait_selection::traits;
9
10 use super::ConstCx;
11
12 pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs {
13 ConstQualifs {
14 has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
15 needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
16 custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
17 }
18 }
19
20 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
21 /// code for promotion or prevent it from evaluating at compile time.
22 ///
23 /// Normally, we would determine what qualifications apply to each type and error when an illegal
24 /// operation is performed on such a type. However, this was found to be too imprecise, especially
25 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
26 /// needn't reject code unless it actually constructs and operates on the qualifed variant.
27 ///
28 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
29 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
30 /// projection of a local) is assigned a qualifed value, that local itself becomes qualifed.
31 pub trait Qualif {
32 /// The name of the file used to debug the dataflow analysis that computes this qualif.
33 const ANALYSIS_NAME: &'static str;
34
35 /// Whether this `Qualif` is cleared when a local is moved from.
36 const IS_CLEARED_ON_MOVE: bool = false;
37
38 /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
39 fn in_qualifs(qualifs: &ConstQualifs) -> bool;
40
41 /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
42 ///
43 /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
44 /// propagation is context-insenstive, this includes function arguments and values returned
45 /// from a call to another function.
46 ///
47 /// It also determines the `Qualif`s for primitive types.
48 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
49
50 /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
51 ///
52 /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
53 /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
54 /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
55 /// with a custom `Drop` impl is inherently `NeedsDrop`.
56 ///
57 /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
58 fn in_adt_inherently(
59 cx: &ConstCx<'_, 'tcx>,
60 adt: &'tcx AdtDef,
61 substs: SubstsRef<'tcx>,
62 ) -> bool;
63 }
64
65 /// Constant containing interior mutability (`UnsafeCell<T>`).
66 /// This must be ruled out to make sure that evaluating the constant at compile-time
67 /// and at *any point* during the run-time would produce the same result. In particular,
68 /// promotion of temporaries must not change program behavior; if the promoted could be
69 /// written to, that would be a problem.
70 pub struct HasMutInterior;
71
72 impl Qualif for HasMutInterior {
73 const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
74
75 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
76 qualifs.has_mut_interior
77 }
78
79 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
80 !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env)
81 }
82
83 fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
84 // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
85 // It arises structurally for all other types.
86 Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
87 }
88 }
89
90 /// Constant containing an ADT that implements `Drop`.
91 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
92 /// as that might not be a `const fn`, and (b) because implicit promotion would
93 /// remove side-effects that occur as part of dropping that value.
94 pub struct NeedsDrop;
95
96 impl Qualif for NeedsDrop {
97 const ANALYSIS_NAME: &'static str = "flow_needs_drop";
98 const IS_CLEARED_ON_MOVE: bool = true;
99
100 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
101 qualifs.needs_drop
102 }
103
104 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
105 ty.needs_drop(cx.tcx, cx.param_env)
106 }
107
108 fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
109 adt.has_dtor(cx.tcx)
110 }
111 }
112
113 /// A constant that cannot be used as part of a pattern in a `match` expression.
114 pub struct CustomEq;
115
116 impl Qualif for CustomEq {
117 const ANALYSIS_NAME: &'static str = "flow_custom_eq";
118
119 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
120 qualifs.custom_eq
121 }
122
123 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
124 // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
125 // we know that at least some values of that type are not structural-match. I say "some"
126 // because that component may be part of an enum variant (e.g.,
127 // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
128 // structural-match (`Option::None`).
129 let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id());
130 traits::search_for_structural_match_violation(id, cx.body.span, cx.tcx, ty).is_some()
131 }
132
133 fn in_adt_inherently(
134 cx: &ConstCx<'_, 'tcx>,
135 adt: &'tcx AdtDef,
136 substs: SubstsRef<'tcx>,
137 ) -> bool {
138 let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
139 !ty.is_structural_eq_shallow(cx.tcx)
140 }
141 }
142
143 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
144
145 /// Returns `true` if this `Rvalue` contains qualif `Q`.
146 pub fn in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool
147 where
148 Q: Qualif,
149 F: FnMut(Local) -> bool,
150 {
151 match rvalue {
152 Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
153 Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
154 }
155
156 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
157 in_place::<Q, _>(cx, in_local, place.as_ref())
158 }
159
160 Rvalue::Use(operand)
161 | Rvalue::Repeat(operand, _)
162 | Rvalue::UnaryOp(_, operand)
163 | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
164
165 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
166 in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
167 }
168
169 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
170 // Special-case reborrows to be more like a copy of the reference.
171 if let &[ref proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
172 let base_ty = Place::ty_from(place.local, proj_base, cx.body, cx.tcx).ty;
173 if let ty::Ref(..) = base_ty.kind() {
174 return in_place::<Q, _>(
175 cx,
176 in_local,
177 PlaceRef { local: place.local, projection: proj_base },
178 );
179 }
180 }
181
182 in_place::<Q, _>(cx, in_local, place.as_ref())
183 }
184
185 Rvalue::Aggregate(kind, operands) => {
186 // Return early if we know that the struct or enum being constructed is always
187 // qualified.
188 if let AggregateKind::Adt(def, _, substs, ..) = **kind {
189 if Q::in_adt_inherently(cx, def, substs) {
190 return true;
191 }
192 }
193
194 // Otherwise, proceed structurally...
195 operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
196 }
197 }
198 }
199
200 /// Returns `true` if this `Place` contains qualif `Q`.
201 pub fn in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
202 where
203 Q: Qualif,
204 F: FnMut(Local) -> bool,
205 {
206 let mut projection = place.projection;
207 while let &[ref proj_base @ .., proj_elem] = projection {
208 match proj_elem {
209 ProjectionElem::Index(index) if in_local(index) => return true,
210
211 ProjectionElem::Deref
212 | ProjectionElem::Field(_, _)
213 | ProjectionElem::ConstantIndex { .. }
214 | ProjectionElem::Subslice { .. }
215 | ProjectionElem::Downcast(_, _)
216 | ProjectionElem::Index(_) => {}
217 }
218
219 let base_ty = Place::ty_from(place.local, proj_base, cx.body, cx.tcx);
220 let proj_ty = base_ty.projection_ty(cx.tcx, proj_elem).ty;
221 if !Q::in_any_value_of_ty(cx, proj_ty) {
222 return false;
223 }
224
225 projection = proj_base;
226 }
227
228 assert!(projection.is_empty());
229 in_local(place.local)
230 }
231
232 /// Returns `true` if this `Operand` contains qualif `Q`.
233 pub fn in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool
234 where
235 Q: Qualif,
236 F: FnMut(Local) -> bool,
237 {
238 let constant = match operand {
239 Operand::Copy(place) | Operand::Move(place) => {
240 return in_place::<Q, _>(cx, in_local, place.as_ref());
241 }
242
243 Operand::Constant(c) => c,
244 };
245
246 // Check the qualifs of the value of `const` items.
247 if let ty::ConstKind::Unevaluated(def, _, promoted) = constant.literal.val {
248 assert!(promoted.is_none());
249 // Don't peek inside trait associated constants.
250 if cx.tcx.trait_of_item(def.did).is_none() {
251 let qualifs = if let Some((did, param_did)) = def.as_const_arg() {
252 cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did))
253 } else {
254 cx.tcx.at(constant.span).mir_const_qualif(def.did)
255 };
256
257 if !Q::in_qualifs(&qualifs) {
258 return false;
259 }
260
261 // Just in case the type is more specific than
262 // the definition, e.g., impl associated const
263 // with type parameters, take it into account.
264 }
265 }
266 // Otherwise use the qualifs of the type.
267 Q::in_any_value_of_ty(cx, constant.literal.ty)
268 }