Skip to content

Commit efb4688

Browse files
committed
Use the correct place for enum variants.
1 parent 7213eaa commit efb4688

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

compiler/rustc_mir_transform/src/dataflow_const_prop.rs

+14-6
Original file line numberDiff line numberDiff line change
@@ -134,18 +134,21 @@ impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'_, 'tcx> {
134134
AggregateKind::Adt(def_id, variant_index, ..) => {
135135
match self.tcx.def_kind(def_id) {
136136
DefKind::Struct => (Some(target_idx), None),
137-
DefKind::Enum => (Some(target_idx), Some(variant_index)),
137+
DefKind::Enum => (
138+
self.map.apply(target_idx, TrackElem::Variant(variant_index)),
139+
Some(variant_index),
140+
),
138141
_ => (None, None),
139142
}
140143
}
141144
_ => (None, None),
142145
};
143-
if let Some(target) = variant_target {
146+
if let Some(variant_target_idx) = variant_target {
144147
for (field_index, operand) in operands.iter().enumerate() {
145-
if let Some(field) = self
146-
.map()
147-
.apply(target, TrackElem::Field(Field::from_usize(field_index)))
148-
{
148+
if let Some(field) = self.map().apply(
149+
variant_target_idx,
150+
TrackElem::Field(Field::from_usize(field_index)),
151+
) {
149152
let result = self.handle_operand(operand, state);
150153
state.insert_idx(field, result, self.map());
151154
}
@@ -154,6 +157,11 @@ impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'_, 'tcx> {
154157
if let Some(variant_index) = variant_index
155158
&& let Some(discr_idx) = self.map().apply(target_idx, TrackElem::Discriminant)
156159
{
160+
// We are assigning the discriminant as part of an aggregate.
161+
// This discriminant can only alias a variant field's value if the operand
162+
// had an invalid value for that type.
163+
// Using invalid values is UB, so we are allowed to perform the assignment
164+
// without extra flooding.
157165
let enum_ty = target.ty(self.local_decls, self.tcx).ty;
158166
if let Some(discr_val) = self.eval_discriminant(enum_ty, variant_index) {
159167
state.insert_value_idx(discr_idx, FlatSet::Elem(discr_val), &self.map);

tests/mir-opt/dataflow-const-prop/enum.simple.DataflowConstProp.diff

+4-2
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,10 @@
4545

4646
bb3: {
4747
StorageLive(_4); // scope 1 at $DIR/enum.rs:+2:29: +2:30
48-
_4 = ((_1 as V1).0: i32); // scope 1 at $DIR/enum.rs:+2:29: +2:30
49-
_2 = _4; // scope 3 at $DIR/enum.rs:+2:35: +2:36
48+
- _4 = ((_1 as V1).0: i32); // scope 1 at $DIR/enum.rs:+2:29: +2:30
49+
- _2 = _4; // scope 3 at $DIR/enum.rs:+2:35: +2:36
50+
+ _4 = const 0_i32; // scope 1 at $DIR/enum.rs:+2:29: +2:30
51+
+ _2 = const 0_i32; // scope 3 at $DIR/enum.rs:+2:35: +2:36
5052
StorageDead(_4); // scope 1 at $DIR/enum.rs:+2:35: +2:36
5153
goto -> bb4; // scope 1 at $DIR/enum.rs:+2:35: +2:36
5254
}

0 commit comments

Comments
 (0)