2 * Methods for the various MIR types. These are intended for use after
3 * building is complete.
7 use crate::ty::{self, Ty, TyCtxt};
9 use rustc_target::abi::VariantIdx;
11 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
12 pub struct PlaceTy<'tcx> {
14 /// Downcast to a particular variant of an enum or a generator, if included.
15 pub variant_index: Option<VariantIdx>,
18 // At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
19 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
20 static_assert_size!(PlaceTy<'_>, 16);
22 impl<'tcx> PlaceTy<'tcx> {
24 pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
25 PlaceTy { ty, variant_index: None }
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`.)
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.variant(variant_index)
45 let field_def = &variant_def.fields[f.index()];
46 field_def.ty(tcx, substs)
48 ty::Tuple(tys) => tys[f.index()],
49 _ => bug!("extracting field of non-tuple non-adt: {:?}", self),
51 debug!("field_ty self: {:?} f: {:?} yields: {:?}", self, f, answer);
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, |_, ty| ty)
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>(
70 param_env: ty::ParamEnv<'tcx>,
71 elem: &ProjectionElem<V, T>,
72 mut handle_field: impl FnMut(&Self, Field, T) -> Ty<'tcx>,
73 mut handle_opaque_cast: impl FnMut(&Self, T) -> Ty<'tcx>,
77 T: ::std::fmt::Debug + Copy,
79 if self.variant_index.is_some() && !matches!(elem, ProjectionElem::Field(..)) {
80 bug!("cannot use non field projection on downcasted place")
82 let answer = match *elem {
83 ProjectionElem::Deref => {
88 bug!("deref projection of non-dereferenceable ty {:?}", self)
93 ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } => {
94 PlaceTy::from_ty(self.ty.builtin_index().unwrap())
96 ProjectionElem::Subslice { from, to, from_end } => {
97 PlaceTy::from_ty(match self.ty.kind() {
98 ty::Slice(..) => self.ty,
99 ty::Array(inner, _) if !from_end => tcx.mk_array(*inner, (to - from) as u64),
100 ty::Array(inner, size) if from_end => {
101 let size = size.eval_usize(tcx, param_env);
102 let len = size - (from as u64) - (to as u64);
103 tcx.mk_array(*inner, len)
105 _ => bug!("cannot subslice non-array type: `{:?}`", self),
108 ProjectionElem::Downcast(_name, index) => {
109 PlaceTy { ty: self.ty, variant_index: Some(index) }
111 ProjectionElem::Field(f, fty) => PlaceTy::from_ty(handle_field(&self, f, fty)),
112 ProjectionElem::OpaqueCast(ty) => PlaceTy::from_ty(handle_opaque_cast(&self, ty)),
114 debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
119 impl<'tcx> Place<'tcx> {
122 projection: &[PlaceElem<'tcx>],
127 D: HasLocalDecls<'tcx>,
131 .fold(PlaceTy::from_ty(local_decls.local_decls()[local].ty), |place_ty, &elem| {
132 place_ty.projection_ty(tcx, elem)
136 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
138 D: HasLocalDecls<'tcx>,
140 Place::ty_from(self.local, &self.projection, local_decls, tcx)
144 impl<'tcx> PlaceRef<'tcx> {
145 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
147 D: HasLocalDecls<'tcx>,
149 Place::ty_from(self.local, &self.projection, local_decls, tcx)
153 pub enum RvalueInitializationState {
158 impl<'tcx> Rvalue<'tcx> {
159 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
161 D: HasLocalDecls<'tcx>,
164 Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
165 Rvalue::Repeat(ref operand, count) => {
166 tcx.mk_ty(ty::Array(operand.ty(local_decls, tcx), count))
168 Rvalue::ThreadLocalRef(did) => {
169 let static_ty = tcx.type_of(did);
170 if tcx.is_mutable_static(did) {
171 tcx.mk_mut_ptr(static_ty)
172 } else if tcx.is_foreign_item(did) {
173 tcx.mk_imm_ptr(static_ty)
175 // FIXME: These things don't *really* have 'static lifetime.
176 tcx.mk_imm_ref(tcx.lifetimes.re_static, static_ty)
179 Rvalue::Ref(reg, bk, ref place) => {
180 let place_ty = place.ty(local_decls, tcx).ty;
181 tcx.mk_ref(reg, ty::TypeAndMut { ty: place_ty, mutbl: bk.to_mutbl_lossy() })
183 Rvalue::AddressOf(mutability, ref place) => {
184 let place_ty = place.ty(local_decls, tcx).ty;
185 tcx.mk_ptr(ty::TypeAndMut { ty: place_ty, mutbl: mutability })
187 Rvalue::Len(..) => tcx.types.usize,
188 Rvalue::Cast(.., ty) => ty,
189 Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
190 let lhs_ty = lhs.ty(local_decls, tcx);
191 let rhs_ty = rhs.ty(local_decls, tcx);
192 op.ty(tcx, lhs_ty, rhs_ty)
194 Rvalue::CheckedBinaryOp(op, box (ref lhs, ref rhs)) => {
195 let lhs_ty = lhs.ty(local_decls, tcx);
196 let rhs_ty = rhs.ty(local_decls, tcx);
197 let ty = op.ty(tcx, lhs_ty, rhs_ty);
198 tcx.intern_tup(&[ty, tcx.types.bool])
200 Rvalue::UnaryOp(UnOp::Not | UnOp::Neg, ref operand) => operand.ty(local_decls, tcx),
201 Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
202 Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) => tcx.types.usize,
203 Rvalue::Aggregate(ref ak, ref ops) => match **ak {
204 AggregateKind::Array(ty) => tcx.mk_array(ty, ops.len() as u64),
205 AggregateKind::Tuple => tcx.mk_tup(ops.iter().map(|op| op.ty(local_decls, tcx))),
206 AggregateKind::Adt(did, _, substs, _, _) => {
207 tcx.bound_type_of(did).subst(tcx, substs)
209 AggregateKind::Closure(did, substs) => tcx.mk_closure(did.to_def_id(), substs),
210 AggregateKind::Generator(did, substs, movability) => {
211 tcx.mk_generator(did.to_def_id(), substs, movability)
214 Rvalue::ShallowInitBox(_, ty) => tcx.mk_box(ty),
215 Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
220 /// Returns `true` if this rvalue is deeply initialized (most rvalues) or
221 /// whether its only shallowly initialized (`Rvalue::Box`).
222 pub fn initialization_state(&self) -> RvalueInitializationState {
224 Rvalue::ShallowInitBox(_, _) => RvalueInitializationState::Shallow,
225 _ => RvalueInitializationState::Deep,
230 impl<'tcx> Operand<'tcx> {
231 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
233 D: HasLocalDecls<'tcx>,
236 &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
237 &Operand::Constant(ref c) => c.literal.ty(),
243 pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
244 // FIXME: handle SIMD correctly
254 // these should be integers or floats of the same size.
255 assert_eq!(lhs_ty, rhs_ty);
258 &BinOp::Shl | &BinOp::Shr | &BinOp::Offset => {
259 lhs_ty // lhs_ty can be != rhs_ty
261 &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
269 pub fn to_mutbl_lossy(self) -> hir::Mutability {
271 BorrowKind::Mut { .. } => hir::Mutability::Mut,
272 BorrowKind::Shared => hir::Mutability::Not,
274 // We have no type corresponding to a unique imm borrow, so
275 // use `&mut`. It gives all the capabilities of a `&uniq`
276 // and hence is a safe "over approximation".
277 BorrowKind::Unique => hir::Mutability::Mut,
279 // We have no type corresponding to a shallow borrow, so use
280 // `&` as an approximation.
281 BorrowKind::Shallow => hir::Mutability::Not,
287 pub fn to_hir_binop(self) -> hir::BinOpKind {
289 BinOp::Add => hir::BinOpKind::Add,
290 BinOp::Sub => hir::BinOpKind::Sub,
291 BinOp::Mul => hir::BinOpKind::Mul,
292 BinOp::Div => hir::BinOpKind::Div,
293 BinOp::Rem => hir::BinOpKind::Rem,
294 BinOp::BitXor => hir::BinOpKind::BitXor,
295 BinOp::BitAnd => hir::BinOpKind::BitAnd,
296 BinOp::BitOr => hir::BinOpKind::BitOr,
297 BinOp::Shl => hir::BinOpKind::Shl,
298 BinOp::Shr => hir::BinOpKind::Shr,
299 BinOp::Eq => hir::BinOpKind::Eq,
300 BinOp::Ne => hir::BinOpKind::Ne,
301 BinOp::Lt => hir::BinOpKind::Lt,
302 BinOp::Gt => hir::BinOpKind::Gt,
303 BinOp::Le => hir::BinOpKind::Le,
304 BinOp::Ge => hir::BinOpKind::Ge,
305 BinOp::Offset => unreachable!(),