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