1 //! Removes assignments to ZST places.
4 use rustc_middle::mir::tcx::PlaceTy;
5 use rustc_middle::mir::{Body, LocalDecls, Place, StatementKind};
6 use rustc_middle::ty::{self, Ty, TyCtxt};
10 impl<'tcx> MirPass<'tcx> for RemoveZsts {
11 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
12 let param_env = tcx.param_env(body.source.def_id());
13 let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut();
14 for block in basic_blocks.iter_mut() {
15 for statement in block.statements.iter_mut() {
16 if let StatementKind::Assign(box (place, _)) = statement.kind {
17 let place_ty = place.ty(local_decls, tcx).ty;
18 if !maybe_zst(place_ty) {
21 let layout = match tcx.layout_of(param_env.and(place_ty)) {
28 if involves_a_union(place, local_decls, tcx) {
31 if tcx.consider_optimizing(|| {
33 "RemoveZsts - Place: {:?} SourceInfo: {:?}",
34 place, statement.source_info
45 /// A cheap, approximate check to avoid unnecessary `layout_of` calls.
46 fn maybe_zst(ty: Ty<'_>) -> bool {
48 // maybe ZST (could be more precise)
49 ty::Adt(..) | ty::Array(..) | ty::Closure(..) | ty::Tuple(..) | ty::Opaque(..) => true,
51 ty::FnDef(..) | ty::Never => true,
52 // unreachable or can't be ZST
57 /// Miri lazily allocates memory for locals on assignment,
58 /// so we must preserve writes to unions and union fields,
59 /// or it will ICE on reads of those fields.
60 fn involves_a_union<'tcx>(
62 local_decls: &LocalDecls<'tcx>,
65 let mut place_ty = PlaceTy::from_ty(local_decls[place.local].ty);
66 if place_ty.ty.is_union() {
69 for elem in place.projection {
70 place_ty = place_ty.projection_ty(tcx, elem);
71 if place_ty.ty.is_union() {