]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/alignment.rs
Rollup merge of #64451 - RalfJung:miri-manifest, r=pietroalbini
[rust.git] / src / librustc_mir / util / alignment.rs
1 use rustc::ty::{self, TyCtxt};
2 use rustc::mir::*;
3
4 /// Returns `true` if this place is allowed to be less aligned
5 /// than its containing struct (because it is within a packed
6 /// struct).
7 pub fn is_disaligned<'tcx, L>(
8     tcx: TyCtxt<'tcx>,
9     local_decls: &L,
10     param_env: ty::ParamEnv<'tcx>,
11     place: &Place<'tcx>,
12 ) -> bool
13 where
14     L: HasLocalDecls<'tcx>,
15 {
16     debug!("is_disaligned({:?})", place);
17     if !is_within_packed(tcx, local_decls, place) {
18         debug!("is_disaligned({:?}) - not within packed", place);
19         return false
20     }
21
22     let ty = place.ty(local_decls, tcx).ty;
23     match tcx.layout_raw(param_env.and(ty)) {
24         Ok(layout) if layout.align.abi.bytes() == 1 => {
25             // if the alignment is 1, the type can't be further
26             // disaligned.
27             debug!("is_disaligned({:?}) - align = 1", place);
28             false
29         }
30         _ => {
31             debug!("is_disaligned({:?}) - true", place);
32             true
33         }
34     }
35 }
36
37 fn is_within_packed<'tcx, L>(tcx: TyCtxt<'tcx>, local_decls: &L, place: &Place<'tcx>) -> bool
38 where
39     L: HasLocalDecls<'tcx>,
40 {
41     for (i, elem) in place.projection.iter().enumerate().rev() {
42         let proj_base = &place.projection[..i];
43
44         match elem {
45             // encountered a Deref, which is ABI-aligned
46             ProjectionElem::Deref => break,
47             ProjectionElem::Field(..) => {
48                 let ty = Place::ty_from(&place.base, proj_base, local_decls, tcx).ty;
49                 match ty.sty {
50                     ty::Adt(def, _) if def.repr.packed() => {
51                         return true
52                     }
53                     _ => {}
54                 }
55             }
56             _ => {}
57         }
58     }
59
60     false
61 }