rustc_const_eval/interpret/discriminant.rs
1//! Functions for reading and writing discriminants of multi-variant layouts (enums and coroutines).
2
3use rustc_abi::{self as abi, TagEncoding, VariantIdx, Variants};
4use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout};
5use rustc_middle::ty::{self, CoroutineArgsExt, ScalarInt, Ty};
6use rustc_middle::{mir, span_bug};
7use tracing::{instrument, trace};
8
9use super::{
10 ImmTy, InterpCx, InterpResult, Machine, Projectable, Scalar, Writeable, err_ub, interp_ok,
11 throw_ub,
12};
13
14impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
15 /// Writes the discriminant of the given variant.
16 ///
17 /// If the variant is uninhabited, this is UB.
18 #[instrument(skip(self), level = "trace")]
19 pub fn write_discriminant(
20 &mut self,
21 variant_index: VariantIdx,
22 dest: &impl Writeable<'tcx, M::Provenance>,
23 ) -> InterpResult<'tcx> {
24 match self.tag_for_variant(dest.layout(), variant_index)? {
25 Some((tag, tag_field)) => {
26 // No need to validate that the discriminant here because the
27 // `TyAndLayout::for_variant()` call earlier already checks the
28 // variant is valid.
29 let tag_dest = self.project_field(dest, tag_field)?;
30 self.write_scalar(tag, &tag_dest)
31 }
32 None => {
33 // No need to write the tag here, because an untagged variant is
34 // implicitly encoded. For `Niche`-optimized enums, this works by
35 // simply by having a value that is outside the niche variants.
36 // But what if the data stored here does not actually encode
37 // this variant? That would be bad! So let's double-check...
38 let actual_variant = self.read_discriminant(&dest.to_op(self)?)?;
39 if actual_variant != variant_index {
40 throw_ub!(InvalidNichedEnumVariantWritten { enum_ty: dest.layout().ty });
41 }
42 interp_ok(())
43 }
44 }
45 }
46
47 /// Read discriminant, return the variant index.
48 /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)!
49 ///
50 /// Will never return an uninhabited variant.
51 #[instrument(skip(self), level = "trace")]
52 pub fn read_discriminant(
53 &self,
54 op: &impl Projectable<'tcx, M::Provenance>,
55 ) -> InterpResult<'tcx, VariantIdx> {
56 let ty = op.layout().ty;
57 trace!("read_discriminant_value {:#?}", op.layout());
58 // Get type and layout of the discriminant.
59 let discr_layout = self.layout_of(ty.discriminant_ty(*self.tcx))?;
60 trace!("discriminant type: {:?}", discr_layout.ty);
61
62 // We use "discriminant" to refer to the value associated with a particular enum variant.
63 // This is not to be confused with its "variant index", which is just determining its position in the
64 // declared list of variants -- they can differ with explicitly assigned discriminants.
65 // We use "tag" to refer to how the discriminant is encoded in memory, which can be either
66 // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`).
67 let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout().variants {
68 Variants::Empty => {
69 throw_ub!(UninhabitedEnumVariantRead(None));
70 }
71 Variants::Single { index } => {
72 if op.layout().is_uninhabited() {
73 // For consistency with `write_discriminant`, and to make sure that
74 // `project_downcast` cannot fail due to strange layouts, we declare immediate UB
75 // for uninhabited enums.
76 throw_ub!(UninhabitedEnumVariantRead(Some(index)));
77 }
78 // Since the type is inhabited, there must be an index.
79 return interp_ok(index);
80 }
81 Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
82 (tag, tag_encoding, tag_field)
83 }
84 };
85
86 // There are *three* layouts that come into play here:
87 // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for
88 // the `Scalar` we return.
89 // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type,
90 // and used to interpret the value we read from the tag field.
91 // For the return value, a cast to `discr_layout` is performed.
92 // - The field storing the tag has a layout, which is very similar to `tag_layout` but
93 // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks.
94
95 // Get layout for tag.
96 let tag_layout = self.layout_of(tag_scalar_layout.primitive().to_int_ty(*self.tcx))?;
97
98 // Read tag and sanity-check `tag_layout`.
99 let tag_val = self.read_immediate(&self.project_field(op, tag_field)?)?;
100 assert_eq!(tag_layout.size, tag_val.layout.size);
101 assert_eq!(tag_layout.backend_repr.is_signed(), tag_val.layout.backend_repr.is_signed());
102 trace!("tag value: {}", tag_val);
103
104 // Figure out which discriminant and variant this corresponds to.
105 let index = match *tag_encoding {
106 TagEncoding::Direct => {
107 // Generate a specific error if `tag_val` is not an integer.
108 // (`tag_bits` itself is only used for error messages below.)
109 let tag_bits = tag_val
110 .to_scalar()
111 .try_to_scalar_int()
112 .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))?
113 .to_bits(tag_layout.size);
114 // Cast bits from tag layout to discriminant layout.
115 // After the checks we did above, this cannot fail, as
116 // discriminants are int-like.
117 let discr_val = self.int_to_int_or_float(&tag_val, discr_layout).unwrap();
118 let discr_bits = discr_val.to_scalar().to_bits(discr_layout.size)?;
119 // Convert discriminant to variant index, and catch invalid discriminants.
120 let index = match *ty.kind() {
121 ty::Adt(adt, _) => {
122 adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits)
123 }
124 ty::Coroutine(def_id, args) => {
125 let args = args.as_coroutine();
126 args.discriminants(def_id, *self.tcx).find(|(_, var)| var.val == discr_bits)
127 }
128 _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-coroutine"),
129 }
130 .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?;
131 // Return the cast value, and the index.
132 index.0
133 }
134 TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
135 let tag_val = tag_val.to_scalar();
136 // Compute the variant this niche value/"tag" corresponds to. With niche layout,
137 // discriminant (encoded in niche/tag) and variant index are the same.
138 let variants_start = niche_variants.start().as_u32();
139 let variants_end = niche_variants.end().as_u32();
140 let variant = match tag_val.try_to_scalar_int() {
141 Err(dbg_val) => {
142 // So this is a pointer then, and casting to an int failed.
143 // Can only happen during CTFE.
144 // The niche must be just 0, and the ptr not null, then we know this is
145 // okay. Everything else, we conservatively reject.
146 let ptr_valid = niche_start == 0
147 && variants_start == variants_end
148 && !self.scalar_may_be_null(tag_val)?;
149 if !ptr_valid {
150 throw_ub!(InvalidTag(dbg_val))
151 }
152 untagged_variant
153 }
154 Ok(tag_bits) => {
155 let tag_bits = tag_bits.to_bits(tag_layout.size);
156 // We need to use machine arithmetic to get the relative variant idx:
157 // variant_index_relative = tag_val - niche_start_val
158 let tag_val = ImmTy::from_uint(tag_bits, tag_layout);
159 let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
160 let variant_index_relative_val =
161 self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?;
162 let variant_index_relative =
163 variant_index_relative_val.to_scalar().to_bits(tag_val.layout.size)?;
164 // Check if this is in the range that indicates an actual discriminant.
165 if variant_index_relative <= u128::from(variants_end - variants_start) {
166 let variant_index_relative = u32::try_from(variant_index_relative)
167 .expect("we checked that this fits into a u32");
168 // Then computing the absolute variant idx should not overflow any more.
169 let variant_index = VariantIdx::from_u32(
170 variants_start
171 .checked_add(variant_index_relative)
172 .expect("overflow computing absolute variant idx"),
173 );
174 let variants =
175 ty.ty_adt_def().expect("tagged layout for non adt").variants();
176 assert!(variant_index < variants.next_index());
177 if variant_index == untagged_variant {
178 // The untagged variant can be in the niche range, but even then it
179 // is not a valid encoding.
180 throw_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size)))
181 }
182 variant_index
183 } else {
184 untagged_variant
185 }
186 }
187 };
188 // Compute the size of the scalar we need to return.
189 // No need to cast, because the variant index directly serves as discriminant and is
190 // encoded in the tag.
191 variant
192 }
193 };
194 // Reading the discriminant of an uninhabited variant is UB. This is the basis for the
195 // `uninhabited_enum_branching` MIR pass. It also ensures consistency with
196 // `write_discriminant`.
197 if op.layout().for_variant(self, index).is_uninhabited() {
198 throw_ub!(UninhabitedEnumVariantRead(Some(index)))
199 }
200 interp_ok(index)
201 }
202
203 /// Read discriminant, return the user-visible discriminant.
204 /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)!
205 pub fn discriminant_for_variant(
206 &self,
207 ty: Ty<'tcx>,
208 variant: VariantIdx,
209 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
210 let discr_layout = self.layout_of(ty.discriminant_ty(*self.tcx))?;
211 let discr_value = match ty.discriminant_for_variant(*self.tcx, variant) {
212 Some(discr) => {
213 // This type actually has discriminants.
214 assert_eq!(discr.ty, discr_layout.ty);
215 Scalar::from_uint(discr.val, discr_layout.size)
216 }
217 None => {
218 // On a type without actual discriminants, variant is 0.
219 assert_eq!(variant.as_u32(), 0);
220 Scalar::from_uint(variant.as_u32(), discr_layout.size)
221 }
222 };
223 interp_ok(ImmTy::from_scalar(discr_value, discr_layout))
224 }
225
226 /// Computes how to write the tag of a given variant of enum `ty`:
227 /// - `None` means that nothing needs to be done as the variant is encoded implicitly
228 /// - `Some((val, field_idx))` means that the given integer value needs to be stored at the
229 /// given field index.
230 pub(crate) fn tag_for_variant(
231 &self,
232 layout: TyAndLayout<'tcx>,
233 variant_index: VariantIdx,
234 ) -> InterpResult<'tcx, Option<(ScalarInt, usize)>> {
235 // Layout computation excludes uninhabited variants from consideration.
236 // Therefore, there's no way to represent those variants in the given layout.
237 // Essentially, uninhabited variants do not have a tag that corresponds to their
238 // discriminant, so we have to bail out here.
239 if layout.for_variant(self, variant_index).is_uninhabited() {
240 throw_ub!(UninhabitedEnumVariantWritten(variant_index))
241 }
242
243 match layout.variants {
244 abi::Variants::Empty => unreachable!("we already handled uninhabited types"),
245 abi::Variants::Single { .. } => {
246 // The tag of a `Single` enum is like the tag of the niched
247 // variant: there's no tag as the discriminant is encoded
248 // entirely implicitly. If `write_discriminant` ever hits this
249 // case, we do a "validation read" to ensure the right
250 // discriminant is encoded implicitly, so any attempt to write
251 // the wrong discriminant for a `Single` enum will reliably
252 // result in UB.
253 interp_ok(None)
254 }
255
256 abi::Variants::Multiple {
257 tag_encoding: TagEncoding::Direct,
258 tag: tag_layout,
259 tag_field,
260 ..
261 } => {
262 // raw discriminants for enums are isize or bigger during
263 // their computation, but the in-memory tag is the smallest possible
264 // representation
265 let discr = self.discriminant_for_variant(layout.ty, variant_index)?;
266 let discr_size = discr.layout.size;
267 let discr_val = discr.to_scalar().to_bits(discr_size)?;
268 let tag_size = tag_layout.size(self);
269 let tag_val = tag_size.truncate(discr_val);
270 let tag = ScalarInt::try_from_uint(tag_val, tag_size).unwrap();
271 interp_ok(Some((tag, tag_field)))
272 }
273
274 abi::Variants::Multiple {
275 tag_encoding: TagEncoding::Niche { untagged_variant, .. },
276 ..
277 } if untagged_variant == variant_index => {
278 // The untagged variant is implicitly encoded simply by having a
279 // value that is outside the niche variants.
280 interp_ok(None)
281 }
282
283 abi::Variants::Multiple {
284 tag_encoding:
285 TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start },
286 tag: tag_layout,
287 tag_field,
288 ..
289 } => {
290 assert!(variant_index != untagged_variant);
291 // We checked that this variant is inhabited, so it must be in the niche range.
292 assert!(
293 niche_variants.contains(&variant_index),
294 "invalid variant index for this enum"
295 );
296 let variants_start = niche_variants.start().as_u32();
297 let variant_index_relative = variant_index.as_u32().strict_sub(variants_start);
298 // We need to use machine arithmetic when taking into account `niche_start`:
299 // tag_val = variant_index_relative + niche_start_val
300 let tag_layout = self.layout_of(tag_layout.primitive().to_int_ty(*self.tcx))?;
301 let niche_start_val = ImmTy::from_uint(niche_start, tag_layout);
302 let variant_index_relative_val =
303 ImmTy::from_uint(variant_index_relative, tag_layout);
304 let tag = self
305 .binary_op(mir::BinOp::Add, &variant_index_relative_val, &niche_start_val)?
306 .to_scalar_int()?;
307 interp_ok(Some((tag, tag_field)))
308 }
309 }
310 }
311}