Skip to content

Commit

Permalink
fix issue #78496
Browse files Browse the repository at this point in the history
  • Loading branch information
wecing committed Dec 10, 2020
1 parent 8080f54 commit c6f2d49
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
28 changes: 28 additions & 0 deletions compiler/rustc_mir/src/transform/early_otherwise_branch.rs
Expand Up @@ -283,6 +283,34 @@ impl<'a, 'tcx> Helper<'a, 'tcx> {
return None;
}

// when one place is the projection of the other, it's not safe to calculate their discriminant values sequentially.
// for example, this should not be optimized:
//
// ```rust
// enum E<'a> { Empty, Some(&'a E<'a>), }
// let Some(Some(_)) = e;
// ```
//
// ```mir
// bb0: {
// _2 = discriminant(*_1)
// switchInt(move _2) -> [...]
// }
// bb1: {
// _3 = discriminant(*(((*_1) as Some).0: &E))
// switchInt(move _3) -> [...]
// }
// ```
let discr_place = discr_info.place_of_adt_discr_read;
let this_discr_place = this_bb_discr_info.place_of_adt_discr_read;
if discr_place.local == this_discr_place.local
&& (discr_place.projection.starts_with(this_discr_place.projection)
|| this_discr_place.projection.starts_with(discr_place.projection))
{
trace!("NO: one target is the projection of another");
return None;
}

// if we reach this point, the optimization applies, and we should be able to optimize this case
// store the info that is needed to apply the optimization

Expand Down
16 changes: 16 additions & 0 deletions src/test/ui/mir/issue-78496.rs
@@ -0,0 +1,16 @@
// run-pass
// compile-flags: -Z mir-opt-level=2 -C opt-level=0

// example from #68867
pub enum E<'a> {
Empty,
Some(&'a E<'a>),
}

fn f(e: &E) -> u32 {
if let E::Some(E::Some(_)) = e { 1 } else { 2 }
}

fn main() {
assert_eq!(f(&E::Empty), 2);
}

0 comments on commit c6f2d49

Please sign in to comment.