1
Fork 0

RemoveZsts: don't touch unions

This commit is contained in:
Erik Desjardins 2021-03-24 13:00:36 -04:00
parent 79e5814f45
commit d5c1ad5ca1
3 changed files with 65 additions and 1 deletions

View file

@ -1,7 +1,8 @@
//! Removes assignments to ZST places.
use crate::transform::MirPass;
use rustc_middle::mir::{Body, StatementKind};
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::{Body, LocalDecls, Place, StatementKind};
use rustc_middle::ty::{self, Ty, TyCtxt};
pub struct RemoveZsts;
@ -28,6 +29,9 @@ impl<'tcx> MirPass<'tcx> for RemoveZsts {
if !layout.is_zst() {
continue;
}
if involves_a_union(place, local_decls, tcx) {
continue;
}
if tcx.consider_optimizing(|| {
format!(
"RemoveZsts - Place: {:?} SourceInfo: {:?}",
@ -55,3 +59,31 @@ fn maybe_zst(ty: Ty<'_>) -> bool {
_ => false,
}
}
/// Miri lazily allocates memory for locals on assignment,
/// so we must preserve writes to unions and union fields,
/// or it will ICE on reads of those fields.
fn involves_a_union<'tcx>(
place: Place<'tcx>,
local_decls: &LocalDecls<'tcx>,
tcx: TyCtxt<'tcx>,
) -> bool {
let mut place_ty = PlaceTy::from_ty(local_decls[place.local].ty);
if is_union(place_ty.ty) {
return true;
}
for elem in place.projection {
place_ty = place_ty.projection_ty(tcx, elem);
if is_union(place_ty.ty) {
return true;
}
}
return false;
}
fn is_union(ty: Ty<'_>) -> bool {
match ty.kind() {
ty::Adt(def, _) if def.is_union() => true,
_ => false,
}
}