]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/alignment.rs
Auto merge of #58406 - Disasm:rv64-support, r=nagisa
[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<'a, 'tcx, L>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
8                                   local_decls: &L,
9                                   param_env: ty::ParamEnv<'tcx>,
10                                   place: &Place<'tcx>)
11                                   -> bool
12     where L: HasLocalDecls<'tcx>
13 {
14     debug!("is_disaligned({:?})", place);
15     if !is_within_packed(tcx, local_decls, place) {
16         debug!("is_disaligned({:?}) - not within packed", place);
17         return false
18     }
19
20     let ty = place.ty(local_decls, tcx).to_ty(tcx);
21     match tcx.layout_raw(param_env.and(ty)) {
22         Ok(layout) if layout.align.abi.bytes() == 1 => {
23             // if the alignment is 1, the type can't be further
24             // disaligned.
25             debug!("is_disaligned({:?}) - align = 1", place);
26             false
27         }
28         _ => {
29             debug!("is_disaligned({:?}) - true", place);
30             true
31         }
32     }
33 }
34
35 fn is_within_packed<'a, 'tcx, L>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
36                                  local_decls: &L,
37                                  place: &Place<'tcx>)
38                                  -> bool
39     where L: HasLocalDecls<'tcx>
40 {
41     let mut place = place;
42     while let &Place::Projection(box Projection {
43         ref base, ref elem
44     }) = place {
45         match *elem {
46             // encountered a Deref, which is ABI-aligned
47             ProjectionElem::Deref => break,
48             ProjectionElem::Field(..) => {
49                 let ty = base.ty(local_decls, tcx).to_ty(tcx);
50                 match ty.sty {
51                     ty::Adt(def, _) if def.repr.packed() => {
52                         return true
53                     }
54                     _ => {}
55                 }
56             }
57             _ => {}
58         }
59         place = base;
60     }
61
62     false
63 }