]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/tcx.rs
Rollup merge of #59928 - petrochenkov:denyambass, r=varkor
[rust.git] / src / librustc / mir / tcx.rs
1 /*!
2  * Methods for the various MIR types. These are intended for use after
3  * building is complete.
4  */
5
6 use crate::mir::*;
7 use crate::ty::subst::Subst;
8 use crate::ty::{self, Ty, TyCtxt};
9 use crate::ty::layout::VariantIdx;
10 use crate::hir;
11 use crate::ty::util::IntTypeExt;
12
13 #[derive(Copy, Clone, Debug)]
14 pub struct PlaceTy<'tcx> {
15     pub ty: Ty<'tcx>,
16     /// Downcast to a particular variant of an enum, if included.
17     pub variant_index: Option<VariantIdx>,
18 }
19
20 static_assert!(PLACE_TY_IS_3_PTRS_LARGE:
21     mem::size_of::<PlaceTy<'_>>() <= 24
22 );
23
24 impl<'a, 'gcx, 'tcx> PlaceTy<'tcx> {
25     pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
26         PlaceTy { ty, variant_index: None }
27     }
28
29     /// `place_ty.field_ty(tcx, f)` computes the type at a given field
30     /// of a record or enum-variant. (Most clients of `PlaceTy` can
31     /// instead just extract the relevant type directly from their
32     /// `PlaceElem`, but some instances of `ProjectionElem<V, T>` do
33     /// not carry a `Ty` for `T`.)
34     ///
35     /// Note that the resulting type has not been normalized.
36     pub fn field_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>, f: &Field) -> Ty<'tcx>
37     {
38         let answer = match self.ty.sty {
39             ty::Adt(adt_def, substs) => {
40                 let variant_def = match self.variant_index {
41                     None => adt_def.non_enum_variant(),
42                     Some(variant_index) => {
43                         assert!(adt_def.is_enum());
44                         &adt_def.variants[variant_index]
45                     }
46                 };
47                 let field_def = &variant_def.fields[f.index()];
48                 field_def.ty(tcx, substs)
49             }
50             ty::Tuple(ref tys) => tys[f.index()].expect_ty(),
51             _ => bug!("extracting field of non-tuple non-adt: {:?}", self),
52         };
53         debug!("field_ty self: {:?} f: {:?} yields: {:?}", self, f, answer);
54         answer
55     }
56
57     /// Convenience wrapper around `projection_ty_core` for
58     /// `PlaceElem`, where we can just use the `Ty` that is already
59     /// stored inline on field projection elems.
60     pub fn projection_ty(self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
61                          elem: &PlaceElem<'tcx>)
62                          -> PlaceTy<'tcx>
63     {
64         self.projection_ty_core(tcx, elem, |_, _, ty| ty)
65     }
66
67     /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
68     /// projects `place_ty` onto `elem`, returning the appropriate
69     /// `Ty` or downcast variant corresponding to that projection.
70     /// The `handle_field` callback must map a `Field` to its `Ty`,
71     /// (which should be trivial when `T` = `Ty`).
72     pub fn projection_ty_core<V, T>(
73         self,
74         tcx: TyCtxt<'a, 'gcx, 'tcx>,
75         elem: &ProjectionElem<V, T>,
76         mut handle_field: impl FnMut(&Self, &Field, &T) -> Ty<'tcx>)
77         -> PlaceTy<'tcx>
78     where
79         V: ::std::fmt::Debug, T: ::std::fmt::Debug
80     {
81         let answer = match *elem {
82             ProjectionElem::Deref => {
83                 let ty = self.ty
84                              .builtin_deref(true)
85                              .unwrap_or_else(|| {
86                                  bug!("deref projection of non-dereferencable ty {:?}", self)
87                              })
88                              .ty;
89                 PlaceTy::from_ty(ty)
90             }
91             ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } =>
92                 PlaceTy::from_ty(self.ty.builtin_index().unwrap()),
93             ProjectionElem::Subslice { from, to } => {
94                 PlaceTy::from_ty(match self.ty.sty {
95                     ty::Array(inner, size) => {
96                         let size = size.unwrap_usize(tcx);
97                         let len = size - (from as u64) - (to as u64);
98                         tcx.mk_array(inner, len)
99                     }
100                     ty::Slice(..) => self.ty,
101                     _ => {
102                         bug!("cannot subslice non-array type: `{:?}`", self)
103                     }
104                 })
105             }
106             ProjectionElem::Downcast(_name, index) =>
107                 PlaceTy { ty: self.ty, variant_index: Some(index) },
108             ProjectionElem::Field(ref f, ref fty) =>
109                 PlaceTy::from_ty(handle_field(&self, f, fty)),
110         };
111         debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
112         answer
113     }
114 }
115
116 BraceStructTypeFoldableImpl! {
117     impl<'tcx> TypeFoldable<'tcx> for PlaceTy<'tcx> {
118         ty,
119         variant_index,
120     }
121 }
122
123 impl<'tcx> Place<'tcx> {
124     pub fn ty<'a, 'gcx, D>(&self, local_decls: &D, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PlaceTy<'tcx>
125         where D: HasLocalDecls<'tcx>
126     {
127         match *self {
128             Place::Base(PlaceBase::Local(index)) =>
129                 PlaceTy::from_ty(local_decls.local_decls()[index].ty),
130             Place::Base(PlaceBase::Static(ref data)) =>
131                 PlaceTy::from_ty(data.ty),
132             Place::Projection(ref proj) =>
133                 proj.base.ty(local_decls, tcx).projection_ty(tcx, &proj.elem),
134         }
135     }
136 }
137
138 pub enum RvalueInitializationState {
139     Shallow,
140     Deep
141 }
142
143 impl<'tcx> Rvalue<'tcx> {
144     pub fn ty<'a, 'gcx, D>(&self, local_decls: &D, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>
145         where D: HasLocalDecls<'tcx>
146     {
147         match *self {
148             Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
149             Rvalue::Repeat(ref operand, count) => {
150                 tcx.mk_array(operand.ty(local_decls, tcx), count)
151             }
152             Rvalue::Ref(reg, bk, ref place) => {
153                 let place_ty = place.ty(local_decls, tcx).ty;
154                 tcx.mk_ref(reg,
155                     ty::TypeAndMut {
156                         ty: place_ty,
157                         mutbl: bk.to_mutbl_lossy()
158                     }
159                 )
160             }
161             Rvalue::Len(..) => tcx.types.usize,
162             Rvalue::Cast(.., ty) => ty,
163             Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
164                 let lhs_ty = lhs.ty(local_decls, tcx);
165                 let rhs_ty = rhs.ty(local_decls, tcx);
166                 op.ty(tcx, lhs_ty, rhs_ty)
167             }
168             Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
169                 let lhs_ty = lhs.ty(local_decls, tcx);
170                 let rhs_ty = rhs.ty(local_decls, tcx);
171                 let ty = op.ty(tcx, lhs_ty, rhs_ty);
172                 tcx.intern_tup(&[ty, tcx.types.bool])
173             }
174             Rvalue::UnaryOp(UnOp::Not, ref operand) |
175             Rvalue::UnaryOp(UnOp::Neg, ref operand) => {
176                 operand.ty(local_decls, tcx)
177             }
178             Rvalue::Discriminant(ref place) => {
179                 let ty = place.ty(local_decls, tcx).ty;
180                 if let ty::Adt(adt_def, _) = ty.sty {
181                     adt_def.repr.discr_type().to_ty(tcx)
182                 } else {
183                     // This can only be `0`, for now, so `u8` will suffice.
184                     tcx.types.u8
185                 }
186             }
187             Rvalue::NullaryOp(NullOp::Box, t) => tcx.mk_box(t),
188             Rvalue::NullaryOp(NullOp::SizeOf, _) => tcx.types.usize,
189             Rvalue::Aggregate(ref ak, ref ops) => {
190                 match **ak {
191                     AggregateKind::Array(ty) => {
192                         tcx.mk_array(ty, ops.len() as u64)
193                     }
194                     AggregateKind::Tuple => {
195                         tcx.mk_tup(ops.iter().map(|op| op.ty(local_decls, tcx)))
196                     }
197                     AggregateKind::Adt(def, _, substs, _, _) => {
198                         tcx.type_of(def.did).subst(tcx, substs)
199                     }
200                     AggregateKind::Closure(did, substs) => {
201                         tcx.mk_closure(did, substs)
202                     }
203                     AggregateKind::Generator(did, substs, movability) => {
204                         tcx.mk_generator(did, substs, movability)
205                     }
206                 }
207             }
208         }
209     }
210
211     #[inline]
212     /// Returns `true` if this rvalue is deeply initialized (most rvalues) or
213     /// whether its only shallowly initialized (`Rvalue::Box`).
214     pub fn initialization_state(&self) -> RvalueInitializationState {
215         match *self {
216             Rvalue::NullaryOp(NullOp::Box, _) => RvalueInitializationState::Shallow,
217             _ => RvalueInitializationState::Deep
218         }
219     }
220 }
221
222 impl<'tcx> Operand<'tcx> {
223     pub fn ty<'a, 'gcx, D>(&self, local_decls: &D, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx>
224         where D: HasLocalDecls<'tcx>
225     {
226         match self {
227             &Operand::Copy(ref l) |
228             &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
229             &Operand::Constant(ref c) => c.ty,
230         }
231     }
232 }
233
234 impl<'tcx> BinOp {
235       pub fn ty<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
236                           lhs_ty: Ty<'tcx>,
237                           rhs_ty: Ty<'tcx>)
238                           -> Ty<'tcx> {
239         // FIXME: handle SIMD correctly
240         match self {
241             &BinOp::Add | &BinOp::Sub | &BinOp::Mul | &BinOp::Div | &BinOp::Rem |
242             &BinOp::BitXor | &BinOp::BitAnd | &BinOp::BitOr => {
243                 // these should be integers or floats of the same size.
244                 assert_eq!(lhs_ty, rhs_ty);
245                 lhs_ty
246             }
247             &BinOp::Shl | &BinOp::Shr | &BinOp::Offset => {
248                 lhs_ty // lhs_ty can be != rhs_ty
249             }
250             &BinOp::Eq | &BinOp::Lt | &BinOp::Le |
251             &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
252                 tcx.types.bool
253             }
254         }
255     }
256 }
257
258 impl BorrowKind {
259     pub fn to_mutbl_lossy(self) -> hir::Mutability {
260         match self {
261             BorrowKind::Mut { .. } => hir::MutMutable,
262             BorrowKind::Shared => hir::MutImmutable,
263
264             // We have no type corresponding to a unique imm borrow, so
265             // use `&mut`. It gives all the capabilities of an `&uniq`
266             // and hence is a safe "over approximation".
267             BorrowKind::Unique => hir::MutMutable,
268
269             // We have no type corresponding to a shallow borrow, so use
270             // `&` as an approximation.
271             BorrowKind::Shallow => hir::MutImmutable,
272         }
273     }
274 }
275
276 impl BinOp {
277     pub fn to_hir_binop(self) -> hir::BinOpKind {
278         match self {
279             BinOp::Add => hir::BinOpKind::Add,
280             BinOp::Sub => hir::BinOpKind::Sub,
281             BinOp::Mul => hir::BinOpKind::Mul,
282             BinOp::Div => hir::BinOpKind::Div,
283             BinOp::Rem => hir::BinOpKind::Rem,
284             BinOp::BitXor => hir::BinOpKind::BitXor,
285             BinOp::BitAnd => hir::BinOpKind::BitAnd,
286             BinOp::BitOr => hir::BinOpKind::BitOr,
287             BinOp::Shl => hir::BinOpKind::Shl,
288             BinOp::Shr => hir::BinOpKind::Shr,
289             BinOp::Eq => hir::BinOpKind::Eq,
290             BinOp::Ne => hir::BinOpKind::Ne,
291             BinOp::Lt => hir::BinOpKind::Lt,
292             BinOp::Gt => hir::BinOpKind::Gt,
293             BinOp::Le => hir::BinOpKind::Le,
294             BinOp::Ge => hir::BinOpKind::Ge,
295             BinOp::Offset => unreachable!()
296         }
297     }
298 }