]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/remove_zsts.rs
Rollup merge of #105502 - chenyukang:yukang/fix-105366-impl, r=estebank
[rust.git] / compiler / rustc_mir_transform / src / remove_zsts.rs
1 //! Removes assignments to ZST places.
2
3 use crate::MirPass;
4 use rustc_middle::mir::{Body, StatementKind};
5 use rustc_middle::ty::{self, Ty, TyCtxt};
6
7 pub struct RemoveZsts;
8
9 impl<'tcx> MirPass<'tcx> for RemoveZsts {
10     fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
11         sess.mir_opt_level() > 0
12     }
13
14     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
15         // Avoid query cycles (generators require optimized MIR for layout).
16         if tcx.type_of(body.source.def_id()).is_generator() {
17             return;
18         }
19         let param_env = tcx.param_env(body.source.def_id());
20         let basic_blocks = body.basic_blocks.as_mut_preserves_cfg();
21         let local_decls = &body.local_decls;
22         for block in basic_blocks {
23             for statement in block.statements.iter_mut() {
24                 if let StatementKind::Assign(box (place, _)) | StatementKind::Deinit(box place) =
25                     statement.kind
26                 {
27                     let place_ty = place.ty(local_decls, tcx).ty;
28                     if !maybe_zst(place_ty) {
29                         continue;
30                     }
31                     let Ok(layout) = tcx.layout_of(param_env.and(place_ty)) else {
32                         continue;
33                     };
34                     if !layout.is_zst() {
35                         continue;
36                     }
37                     if tcx.consider_optimizing(|| {
38                         format!(
39                             "RemoveZsts - Place: {:?} SourceInfo: {:?}",
40                             place, statement.source_info
41                         )
42                     }) {
43                         statement.make_nop();
44                     }
45                 }
46             }
47         }
48     }
49 }
50
51 /// A cheap, approximate check to avoid unnecessary `layout_of` calls.
52 fn maybe_zst(ty: Ty<'_>) -> bool {
53     match ty.kind() {
54         // maybe ZST (could be more precise)
55         ty::Adt(..)
56         | ty::Array(..)
57         | ty::Closure(..)
58         | ty::Tuple(..)
59         | ty::Alias(ty::Opaque, ..) => true,
60         // definitely ZST
61         ty::FnDef(..) | ty::Never => true,
62         // unreachable or can't be ZST
63         _ => false,
64     }
65 }