]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #72562 - RalfJung:rollup-2ngjgwi, r=RalfJung
authorbors <bors@rust-lang.org>
Mon, 25 May 2020 09:43:59 +0000 (09:43 +0000)
committerbors <bors@rust-lang.org>
Mon, 25 May 2020 09:43:59 +0000 (09:43 +0000)
Rollup of 5 pull requests

Successful merges:

 - #71940 (Add `len` and `slice_from_raw_parts` to `NonNull<[T]>`)
 - #72525 (Miri casts: do not blindly rely on dest type)
 - #72537 (Fix InlineAsmOperand expresions being visited twice during liveness checking)
 - #72544 (librustc_middle: Rename upvars query to upvars_mentioned)
 - #72551 (First draft documenting Debug stability.)

Failed merges:

r? @ghost

18 files changed:
src/libcore/fmt/mod.rs
src/libcore/lib.rs
src/libcore/ptr/non_null.rs
src/librustc_middle/arena.rs
src/librustc_middle/mir/mod.rs
src/librustc_middle/query/mod.rs
src/librustc_middle/ty/print/pretty.rs
src/librustc_mir/borrow_check/diagnostics/mod.rs
src/librustc_mir/interpret/cast.rs
src/librustc_mir/interpret/step.rs
src/librustc_mir_build/hair/cx/expr.rs
src/librustc_passes/liveness.rs
src/librustc_passes/upvars.rs
src/librustc_trait_selection/traits/error_reporting/suggestions.rs
src/librustc_typeck/check/closure.rs
src/librustc_typeck/check/upvar.rs
src/librustc_typeck/expr_use_visitor.rs
src/librustc_typeck/mem_categorization.rs

index 95411b525d0db3934f1dd40d703be0c505455f83..3d90fe1fa2f21623db1648de5c418b3df56f6ba6 100644 (file)
@@ -441,6 +441,13 @@ fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
 /// `enum`s, it will use the name of the variant and, if applicable, `(`, then the
 /// `Debug` values of the fields, then `)`.
 ///
+/// # Stability
+///
+/// Derived `Debug` formats are not stable, and so may change with future Rust
+/// versions. Additionally, `Debug` implementations of types provided by the
+/// standard library (`libstd`, `libcore`, `liballoc`, etc.) are not stable, and
+/// may also change with future Rust versions.
+///
 /// # Examples
 ///
 /// Deriving an implementation:
index 3b7929f00168ad0c5bcf2a16754b1172bd490e39..ca13433caec8d518e187b97acad1b5d3479ae0b0 100644 (file)
@@ -87,6 +87,8 @@
 #![feature(const_generics)]
 #![feature(const_ptr_offset_from)]
 #![feature(const_result)]
+#![feature(const_slice_from_raw_parts)]
+#![feature(const_slice_ptr_len)]
 #![feature(const_type_name)]
 #![feature(custom_inner_attributes)]
 #![feature(decl_macro)]
index 7d08503215ed022bfb1920d791d9855ac1665d79..870364a61dd47c9bfbe072c4bf383e52c3826be0 100644 (file)
@@ -142,6 +142,65 @@ pub const fn cast<U>(self) -> NonNull<U> {
     }
 }
 
+impl<T> NonNull<[T]> {
+    /// Creates a non-null raw slice from a thin pointer and a length.
+    ///
+    /// The `len` argument is the number of **elements**, not the number of bytes.
+    ///
+    /// This function is safe, but dereferencing the return value is unsafe.
+    /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
+    ///
+    /// [`slice::from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// #![feature(nonnull_slice_from_raw_parts)]
+    ///
+    /// use std::ptr::NonNull;
+    ///
+    /// // create a slice pointer when starting out with a pointer to the first element
+    /// let mut x = [5, 6, 7];
+    /// let nonnull_pointer = NonNull::new(x.as_mut_ptr()).unwrap();
+    /// let slice = NonNull::slice_from_raw_parts(nonnull_pointer, 3);
+    /// assert_eq!(unsafe { slice.as_ref()[2] }, 7);
+    /// ```
+    ///
+    /// (Note that this example artifically demonstrates a use of this method,
+    /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.)
+    #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")]
+    #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")]
+    #[inline]
+    pub const fn slice_from_raw_parts(data: NonNull<T>, len: usize) -> Self {
+        // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null
+        unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) }
+    }
+
+    /// Returns the length of a non-null raw slice.
+    ///
+    /// The returned value is the number of **elements**, not the number of bytes.
+    ///
+    /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice
+    /// because the pointer does not have a valid address.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// #![feature(slice_ptr_len, nonnull_slice_from_raw_parts)]
+    ///
+    /// use std::ptr::NonNull;
+    ///
+    /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3);
+    /// assert_eq!(slice.len(), 3);
+    /// ```
+    #[unstable(feature = "slice_ptr_len", issue = "71146")]
+    #[rustc_const_unstable(feature = "const_slice_ptr_len", issue = "71146")]
+    #[inline]
+    pub const fn len(self) -> usize {
+        self.as_ptr().len()
+    }
+}
+
 #[stable(feature = "nonnull", since = "1.25.0")]
 impl<T: ?Sized> Clone for NonNull<T> {
     #[inline]
index 2df878c3fb2201df961339ca06848d88cc74a10a..9b9207312e8dddfd938eef398325276e48995f1d 100644 (file)
@@ -61,7 +61,7 @@ macro_rules! arena_types {
             [few] privacy_access_levels: rustc_middle::middle::privacy::AccessLevels,
             [few] foreign_module: rustc_middle::middle::cstore::ForeignModule,
             [few] foreign_modules: Vec<rustc_middle::middle::cstore::ForeignModule>,
-            [] upvars: rustc_data_structures::fx::FxIndexMap<rustc_hir::HirId, rustc_hir::Upvar>,
+            [] upvars_mentioned: rustc_data_structures::fx::FxIndexMap<rustc_hir::HirId, rustc_hir::Upvar>,
             [] object_safety_violations: rustc_middle::traits::ObjectSafetyViolation,
             [] codegen_unit: rustc_middle::mir::mono::CodegenUnit<$tcx>,
             [] attribute: rustc_ast::ast::Attribute,
index 8247338ae0fadc1fbdf6d27d4f800f354745c288..c279213e5bd0e9f009e8ee8e4b308f5fbaabc3b5 100644 (file)
@@ -2439,7 +2439,7 @@ fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
                             };
                             let mut struct_fmt = fmt.debug_struct(&name);
 
-                            if let Some(upvars) = tcx.upvars(def_id) {
+                            if let Some(upvars) = tcx.upvars_mentioned(def_id) {
                                 for (&var_id, place) in upvars.keys().zip(places) {
                                     let var_name = tcx.hir().name(var_id);
                                     struct_fmt.field(&var_name.as_str(), place);
@@ -2458,7 +2458,7 @@ fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
                             let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
                             let mut struct_fmt = fmt.debug_struct(&name);
 
-                            if let Some(upvars) = tcx.upvars(def_id) {
+                            if let Some(upvars) = tcx.upvars_mentioned(def_id) {
                                 for (&var_id, place) in upvars.keys().zip(places) {
                                     let var_name = tcx.hir().name(var_id);
                                     struct_fmt.field(&var_name.as_str(), place);
index f7f5c5df8d67bc176e9d9ba4c063f1895d7ed49d..2445d484754d0fbfbb45c73cd0661a012423d72e 100644 (file)
@@ -1040,7 +1040,7 @@ fn describe_as_module(def_id: DefId, tcx: TyCtxt<'_>) -> String {
             desc { "generating a postorder list of CrateNums" }
         }
 
-        query upvars(_: DefId) -> Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>> {
+        query upvars_mentioned(_: DefId) -> Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>> {
             eval_always
         }
         query maybe_unused_trait_import(def_id: LocalDefId) -> bool {
index f03d91aa64b781c07a75a5cf40027cad0641118a..031ce6629bf4dfc1ef959cdf8be51aba28188354 100644 (file)
@@ -610,7 +610,7 @@ fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error>
                         let mut sep = " ";
                         for (&var_id, upvar_ty) in self
                             .tcx()
-                            .upvars(did)
+                            .upvars_mentioned(did)
                             .as_ref()
                             .iter()
                             .flat_map(|v| v.keys())
@@ -659,7 +659,7 @@ fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error>
                         let mut sep = " ";
                         for (&var_id, upvar_ty) in self
                             .tcx()
-                            .upvars(did)
+                            .upvars_mentioned(did)
                             .as_ref()
                             .iter()
                             .flat_map(|v| v.keys())
index c218e3906fff2fa84220b9e2202b5fd94127fcc4..ca8e54ea286491d2112bd266a71ab21a1917db80 100644 (file)
@@ -377,11 +377,16 @@ fn describe_field_from_ty(
                     self.describe_field_from_ty(&ty, field, variant_index)
                 }
                 ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => {
-                    // `tcx.upvars(def_id)` returns an `Option`, which is `None` in case
+                    // `tcx.upvars_mentioned(def_id)` returns an `Option`, which is `None` in case
                     // the closure comes from another crate. But in that case we wouldn't
                     // be borrowck'ing it, so we can just unwrap:
-                    let (&var_id, _) =
-                        self.infcx.tcx.upvars(def_id).unwrap().get_index(field.index()).unwrap();
+                    let (&var_id, _) = self
+                        .infcx
+                        .tcx
+                        .upvars_mentioned(def_id)
+                        .unwrap()
+                        .get_index(field.index())
+                        .unwrap();
 
                     self.infcx.tcx.hir().name(var_id).to_string()
                 }
@@ -809,7 +814,7 @@ fn closure_span(
         let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
         debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
         if let hir::ExprKind::Closure(.., body_id, args_span, _) = expr {
-            for (upvar, place) in self.infcx.tcx.upvars(def_id)?.values().zip(places) {
+            for (upvar, place) in self.infcx.tcx.upvars_mentioned(def_id)?.values().zip(places) {
                 match place {
                     Operand::Copy(place) | Operand::Move(place)
                         if target_place == place.as_ref() =>
index 0e01652bc900273016bbfa1184ed52d15402c1e1..0fd695586eb9876e562909e6e16689c5a669a4d1 100644 (file)
@@ -1,36 +1,47 @@
 use std::convert::TryFrom;
 
-use super::{FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy};
 use rustc_apfloat::ieee::{Double, Single};
 use rustc_apfloat::{Float, FloatConvert};
 use rustc_ast::ast::FloatTy;
+use rustc_attr as attr;
 use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar};
 use rustc_middle::mir::CastKind;
 use rustc_middle::ty::adjustment::PointerCast;
-use rustc_middle::ty::layout::TyAndLayout;
+use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
 use rustc_middle::ty::{self, Ty, TypeAndMut, TypeFoldable};
 use rustc_span::symbol::sym;
-use rustc_target::abi::{LayoutOf, Size, Variants};
+use rustc_target::abi::{Integer, LayoutOf, Variants};
+
+use super::{truncate, FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy};
 
 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
     pub fn cast(
         &mut self,
         src: OpTy<'tcx, M::PointerTag>,
-        kind: CastKind,
+        cast_kind: CastKind,
+        cast_ty: Ty<'tcx>,
         dest: PlaceTy<'tcx, M::PointerTag>,
     ) -> InterpResult<'tcx> {
         use rustc_middle::mir::CastKind::*;
-        match kind {
+        // FIXME: In which cases should we trigger UB when the source is uninit?
+        match cast_kind {
             Pointer(PointerCast::Unsize) => {
-                self.unsize_into(src, dest)?;
+                let cast_ty = self.layout_of(cast_ty)?;
+                self.unsize_into(src, cast_ty, dest)?;
             }
 
-            Misc | Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer) => {
+            Misc => {
                 let src = self.read_immediate(src)?;
-                let res = self.cast_immediate(src, dest.layout)?;
+                let res = self.misc_cast(src, cast_ty)?;
                 self.write_immediate(res, dest)?;
             }
 
+            Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer) => {
+                // These are NOPs, but can be wide pointers.
+                let v = self.read_immediate(src)?;
+                self.write_immediate(*v, dest)?;
+            }
+
             Pointer(PointerCast::ReifyFnPointer) => {
                 // The src operand does not matter, just its type
                 match src.layout.ty.kind {
@@ -61,12 +72,12 @@ pub fn cast(
 
             Pointer(PointerCast::UnsafeFnPointer) => {
                 let src = self.read_immediate(src)?;
-                match dest.layout.ty.kind {
+                match cast_ty.kind {
                     ty::FnPtr(_) => {
                         // No change to value
                         self.write_immediate(*src, dest)?;
                     }
-                    _ => bug!("fn to unsafe fn cast on {:?}", dest.layout.ty),
+                    _ => bug!("fn to unsafe fn cast on {:?}", cast_ty),
                 }
             }
 
@@ -95,25 +106,21 @@ pub fn cast(
         Ok(())
     }
 
-    fn cast_immediate(
+    fn misc_cast(
         &self,
         src: ImmTy<'tcx, M::PointerTag>,
-        dest_layout: TyAndLayout<'tcx>,
+        cast_ty: Ty<'tcx>,
     ) -> InterpResult<'tcx, Immediate<M::PointerTag>> {
         use rustc_middle::ty::TyKind::*;
-        trace!("Casting {:?}: {:?} to {:?}", *src, src.layout.ty, dest_layout.ty);
+        trace!("Casting {:?}: {:?} to {:?}", *src, src.layout.ty, cast_ty);
 
         match src.layout.ty.kind {
             // Floating point
             Float(FloatTy::F32) => {
-                return Ok(self
-                    .cast_from_float(src.to_scalar()?.to_f32()?, dest_layout.ty)?
-                    .into());
+                return Ok(self.cast_from_float(src.to_scalar()?.to_f32()?, cast_ty).into());
             }
             Float(FloatTy::F64) => {
-                return Ok(self
-                    .cast_from_float(src.to_scalar()?.to_f64()?, dest_layout.ty)?
-                    .into());
+                return Ok(self.cast_from_float(src.to_scalar()?.to_f64()?, cast_ty).into());
             }
             // The rest is integer/pointer-"like", including fn ptr casts and casts from enums that
             // are represented as integers.
@@ -128,95 +135,92 @@ fn cast_immediate(
             ),
         }
 
+        // # First handle non-scalar source values.
+
         // Handle cast from a univariant (ZST) enum.
         match src.layout.variants {
             Variants::Single { index } => {
                 if let Some(discr) = src.layout.ty.discriminant_for_variant(*self.tcx, index) {
                     assert!(src.layout.is_zst());
                     let discr_layout = self.layout_of(discr.ty)?;
-                    return Ok(self
-                        .cast_from_int_like(discr.val, discr_layout, dest_layout)?
-                        .into());
+                    return Ok(self.cast_from_scalar(discr.val, discr_layout, cast_ty).into());
                 }
             }
             Variants::Multiple { .. } => {}
         }
 
-        // Handle casting the metadata away from a fat pointer.
-        if src.layout.ty.is_unsafe_ptr()
-            && dest_layout.ty.is_unsafe_ptr()
-            && dest_layout.size != src.layout.size
-        {
-            assert_eq!(src.layout.size, 2 * self.memory.pointer_size());
-            assert_eq!(dest_layout.size, self.memory.pointer_size());
-            assert!(dest_layout.ty.is_unsafe_ptr());
-            match *src {
-                Immediate::ScalarPair(data, _) => return Ok(data.into()),
-                Immediate::Scalar(..) => bug!(
-                    "{:?} input to a fat-to-thin cast ({:?} -> {:?})",
-                    *src,
-                    src.layout.ty,
-                    dest_layout.ty
-                ),
-            };
-        }
-
         // Handle casting any ptr to raw ptr (might be a fat ptr).
-        if src.layout.ty.is_any_ptr() && dest_layout.ty.is_unsafe_ptr() {
-            // The only possible size-unequal case was handled above.
-            assert_eq!(src.layout.size, dest_layout.size);
-            return Ok(*src);
+        if src.layout.ty.is_any_ptr() && cast_ty.is_unsafe_ptr() {
+            let dest_layout = self.layout_of(cast_ty)?;
+            if dest_layout.size == src.layout.size {
+                // Thin or fat pointer that just hast the ptr kind of target type changed.
+                return Ok(*src);
+            } else {
+                // Casting the metadata away from a fat ptr.
+                assert_eq!(src.layout.size, 2 * self.memory.pointer_size());
+                assert_eq!(dest_layout.size, self.memory.pointer_size());
+                assert!(src.layout.ty.is_unsafe_ptr());
+                return match *src {
+                    Immediate::ScalarPair(data, _) => Ok(data.into()),
+                    Immediate::Scalar(..) => bug!(
+                        "{:?} input to a fat-to-thin cast ({:?} -> {:?})",
+                        *src,
+                        src.layout.ty,
+                        cast_ty
+                    ),
+                };
+            }
         }
 
+        // # The remaining source values are scalar.
+
         // For all remaining casts, we either
         // (a) cast a raw ptr to usize, or
         // (b) cast from an integer-like (including bool, char, enums).
         // In both cases we want the bits.
         let bits = self.force_bits(src.to_scalar()?, src.layout.size)?;
-        Ok(self.cast_from_int_like(bits, src.layout, dest_layout)?.into())
+        Ok(self.cast_from_scalar(bits, src.layout, cast_ty).into())
     }
 
-    fn cast_from_int_like(
+    pub(super) fn cast_from_scalar(
         &self,
-        v: u128, // raw bits
+        v: u128, // raw bits (there is no ScalarTy so we separate data+layout)
         src_layout: TyAndLayout<'tcx>,
-        dest_layout: TyAndLayout<'tcx>,
-    ) -> InterpResult<'tcx, Scalar<M::PointerTag>> {
+        cast_ty: Ty<'tcx>,
+    ) -> Scalar<M::PointerTag> {
         // Let's make sure v is sign-extended *if* it has a signed type.
-        let signed = src_layout.abi.is_signed();
+        let signed = src_layout.abi.is_signed(); // Also asserts that abi is `Scalar`.
         let v = if signed { self.sign_extend(v, src_layout) } else { v };
-        trace!("cast_from_int: {}, {}, {}", v, src_layout.ty, dest_layout.ty);
+        trace!("cast_from_scalar: {}, {} -> {}", v, src_layout.ty, cast_ty);
         use rustc_middle::ty::TyKind::*;
-        match dest_layout.ty.kind {
+        match cast_ty.kind {
             Int(_) | Uint(_) | RawPtr(_) => {
-                let v = self.truncate(v, dest_layout);
-                Ok(Scalar::from_uint(v, dest_layout.size))
+                let size = match cast_ty.kind {
+                    Int(t) => Integer::from_attr(self, attr::IntType::SignedInt(t)).size(),
+                    Uint(t) => Integer::from_attr(self, attr::IntType::UnsignedInt(t)).size(),
+                    RawPtr(_) => self.pointer_size(),
+                    _ => bug!(),
+                };
+                let v = truncate(v, size);
+                Scalar::from_uint(v, size)
             }
 
-            Float(FloatTy::F32) if signed => {
-                Ok(Scalar::from_f32(Single::from_i128(v as i128).value))
-            }
-            Float(FloatTy::F64) if signed => {
-                Ok(Scalar::from_f64(Double::from_i128(v as i128).value))
-            }
-            Float(FloatTy::F32) => Ok(Scalar::from_f32(Single::from_u128(v).value)),
-            Float(FloatTy::F64) => Ok(Scalar::from_f64(Double::from_u128(v).value)),
+            Float(FloatTy::F32) if signed => Scalar::from_f32(Single::from_i128(v as i128).value),
+            Float(FloatTy::F64) if signed => Scalar::from_f64(Double::from_i128(v as i128).value),
+            Float(FloatTy::F32) => Scalar::from_f32(Single::from_u128(v).value),
+            Float(FloatTy::F64) => Scalar::from_f64(Double::from_u128(v).value),
 
             Char => {
                 // `u8` to `char` cast
-                Ok(Scalar::from_u32(u8::try_from(v).unwrap().into()))
+                Scalar::from_u32(u8::try_from(v).unwrap().into())
             }
 
             // Casts to bool are not permitted by rustc, no need to handle them here.
-            _ => bug!("invalid int to {:?} cast", dest_layout.ty),
+            _ => bug!("invalid int to {:?} cast", cast_ty),
         }
     }
 
-    fn cast_from_float<F>(
-        &self,
-        f: F,
-        dest_ty: Ty<'tcx>,
-    ) -> InterpResult<'tcx, Scalar<M::PointerTag>>
+    fn cast_from_float<F>(&self, f: F, dest_ty: Ty<'tcx>) -> Scalar<M::PointerTag>
     where
         F: Float + Into<Scalar<M::PointerTag>> + FloatConvert<Single> + FloatConvert<Double>,
     {
@@ -224,25 +228,25 @@ fn cast_from_float<F>(
         match dest_ty.kind {
             // float -> uint
             Uint(t) => {
-                let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits());
+                let size = Integer::from_attr(self, attr::IntType::UnsignedInt(t)).size();
                 // `to_u128` is a saturating cast, which is what we need
                 // (https://doc.rust-lang.org/nightly/nightly-rustc/rustc_apfloat/trait.Float.html#method.to_i128_r).
-                let v = f.to_u128(usize::try_from(width).unwrap()).value;
+                let v = f.to_u128(size.bits_usize()).value;
                 // This should already fit the bit width
-                Ok(Scalar::from_uint(v, Size::from_bits(width)))
+                Scalar::from_uint(v, size)
             }
             // float -> int
             Int(t) => {
-                let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits());
+                let size = Integer::from_attr(self, attr::IntType::SignedInt(t)).size();
                 // `to_i128` is a saturating cast, which is what we need
                 // (https://doc.rust-lang.org/nightly/nightly-rustc/rustc_apfloat/trait.Float.html#method.to_i128_r).
-                let v = f.to_i128(usize::try_from(width).unwrap()).value;
-                Ok(Scalar::from_int(v, Size::from_bits(width)))
+                let v = f.to_i128(size.bits_usize()).value;
+                Scalar::from_int(v, size)
             }
             // float -> f32
-            Float(FloatTy::F32) => Ok(Scalar::from_f32(f.convert(&mut false).value)),
+            Float(FloatTy::F32) => Scalar::from_f32(f.convert(&mut false).value),
             // float -> f64
-            Float(FloatTy::F64) => Ok(Scalar::from_f64(f.convert(&mut false).value)),
+            Float(FloatTy::F64) => Scalar::from_f64(f.convert(&mut false).value),
             // That's it.
             _ => bug!("invalid float to {:?} cast", dest_ty),
         }
@@ -254,11 +258,11 @@ fn unsize_into_ptr(
         dest: PlaceTy<'tcx, M::PointerTag>,
         // The pointee types
         source_ty: Ty<'tcx>,
-        dest_ty: Ty<'tcx>,
+        cast_ty: Ty<'tcx>,
     ) -> InterpResult<'tcx> {
         // A<Struct> -> A<Trait> conversion
         let (src_pointee_ty, dest_pointee_ty) =
-            self.tcx.struct_lockstep_tails_erasing_lifetimes(source_ty, dest_ty, self.param_env);
+            self.tcx.struct_lockstep_tails_erasing_lifetimes(source_ty, cast_ty, self.param_env);
 
         match (&src_pointee_ty.kind, &dest_pointee_ty.kind) {
             (&ty::Array(_, length), &ty::Slice(_)) => {
@@ -286,32 +290,33 @@ fn unsize_into_ptr(
                 self.write_immediate(val, dest)
             }
 
-            _ => bug!("invalid unsizing {:?} -> {:?}", src.layout.ty, dest.layout.ty),
+            _ => bug!("invalid unsizing {:?} -> {:?}", src.layout.ty, cast_ty),
         }
     }
 
     fn unsize_into(
         &mut self,
         src: OpTy<'tcx, M::PointerTag>,
+        cast_ty: TyAndLayout<'tcx>,
         dest: PlaceTy<'tcx, M::PointerTag>,
     ) -> InterpResult<'tcx> {
-        trace!("Unsizing {:?} into {:?}", src, dest);
-        match (&src.layout.ty.kind, &dest.layout.ty.kind) {
-            (&ty::Ref(_, s, _), &ty::Ref(_, d, _) | &ty::RawPtr(TypeAndMut { ty: d, .. }))
-            | (&ty::RawPtr(TypeAndMut { ty: s, .. }), &ty::RawPtr(TypeAndMut { ty: d, .. })) => {
-                self.unsize_into_ptr(src, dest, s, d)
+        trace!("Unsizing {:?} of type {} into {:?}", *src, src.layout.ty, cast_ty.ty);
+        match (&src.layout.ty.kind, &cast_ty.ty.kind) {
+            (&ty::Ref(_, s, _), &ty::Ref(_, c, _) | &ty::RawPtr(TypeAndMut { ty: c, .. }))
+            | (&ty::RawPtr(TypeAndMut { ty: s, .. }), &ty::RawPtr(TypeAndMut { ty: c, .. })) => {
+                self.unsize_into_ptr(src, dest, s, c)
             }
             (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
                 assert_eq!(def_a, def_b);
                 if def_a.is_box() || def_b.is_box() {
                     if !def_a.is_box() || !def_b.is_box() {
-                        bug!("invalid unsizing between {:?} -> {:?}", src.layout, dest.layout);
+                        bug!("invalid unsizing between {:?} -> {:?}", src.layout.ty, cast_ty.ty);
                     }
                     return self.unsize_into_ptr(
                         src,
                         dest,
                         src.layout.ty.boxed_ty(),
-                        dest.layout.ty.boxed_ty(),
+                        cast_ty.ty.boxed_ty(),
                     );
                 }
 
@@ -319,15 +324,16 @@ fn unsize_into(
                 // Example: `Arc<T>` -> `Arc<Trait>`
                 // here we need to increase the size of every &T thin ptr field to a fat ptr
                 for i in 0..src.layout.fields.count() {
-                    let dst_field = self.place_field(dest, i)?;
-                    if dst_field.layout.is_zst() {
+                    let cast_ty_field = cast_ty.field(self, i)?;
+                    if cast_ty_field.is_zst() {
                         continue;
                     }
                     let src_field = self.operand_field(src, i)?;
-                    if src_field.layout.ty == dst_field.layout.ty {
+                    let dst_field = self.place_field(dest, i)?;
+                    if src_field.layout.ty == cast_ty_field.ty {
                         self.copy_op(src_field, dst_field)?;
                     } else {
-                        self.unsize_into(src_field, dst_field)?;
+                        self.unsize_into(src_field, cast_ty_field, dst_field)?;
                     }
                 }
                 Ok(())
index bb4c0156c88cf8d3e4308a66487a94c90fc03ead..fd9815975c19f613efa5beca7d398a5149840404 100644 (file)
@@ -253,9 +253,10 @@ pub fn eval_rvalue_into_place(
                 self.write_scalar(Scalar::from_machine_usize(layout.size.bytes(), self), dest)?;
             }
 
-            Cast(kind, ref operand, _) => {
+            Cast(cast_kind, ref operand, cast_ty) => {
                 let src = self.eval_operand(operand, None)?;
-                self.cast(src, kind, dest)?;
+                let cast_ty = self.subst_from_current_frame_and_normalize_erasing_regions(cast_ty);
+                self.cast(src, cast_kind, cast_ty, dest)?;
             }
 
             Discriminant(place) => {
index 99b59d16029ff73df3689d61dc7cbd85dc42020f..114bf5710402f7b79e03a3ffdecce53c30ba0694 100644 (file)
@@ -386,7 +386,7 @@ fn make_mirror_unadjusted<'a, 'tcx>(
             };
             let upvars = cx
                 .tcx
-                .upvars(def_id)
+                .upvars_mentioned(def_id)
                 .iter()
                 .flat_map(|upvars| upvars.iter())
                 .zip(substs.upvar_tys())
index 21512c566e1c53ee3a2f3804b6b6668963de1e60..ece78d02512817175db4b8f37ffcbc0ee6bf3d04 100644 (file)
@@ -463,7 +463,7 @@ fn visit_expr<'tcx>(ir: &mut IrMaps<'tcx>, expr: &'tcx Expr<'tcx>) {
         hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
             debug!("expr {}: path that leads to {:?}", expr.hir_id, path.res);
             if let Res::Local(var_hir_id) = path.res {
-                let upvars = ir.tcx.upvars(ir.body_owner);
+                let upvars = ir.tcx.upvars_mentioned(ir.body_owner);
                 if !upvars.map_or(false, |upvars| upvars.contains_key(&var_hir_id)) {
                     ir.add_live_node_for_node(expr.hir_id, ExprNode(expr.span));
                 }
@@ -481,8 +481,8 @@ fn visit_expr<'tcx>(ir: &mut IrMaps<'tcx>, expr: &'tcx Expr<'tcx>) {
             // construction site.
             let mut call_caps = Vec::new();
             let closure_def_id = ir.tcx.hir().local_def_id(expr.hir_id);
-            if let Some(upvars) = ir.tcx.upvars(closure_def_id) {
-                let parent_upvars = ir.tcx.upvars(ir.body_owner);
+            if let Some(upvars) = ir.tcx.upvars_mentioned(closure_def_id) {
+                let parent_upvars = ir.tcx.upvars_mentioned(ir.body_owner);
                 call_caps.extend(upvars.iter().filter_map(|(&var_id, upvar)| {
                     let has_parent =
                         parent_upvars.map_or(false, |upvars| upvars.contains_key(&var_id));
@@ -1364,7 +1364,7 @@ fn access_path(
     ) -> LiveNode {
         match path.res {
             Res::Local(hid) => {
-                let upvars = self.ir.tcx.upvars(self.ir.body_owner);
+                let upvars = self.ir.tcx.upvars_mentioned(self.ir.body_owner);
                 if !upvars.map_or(false, |upvars| upvars.contains_key(&hid)) {
                     self.access_var(hir_id, hid, succ, acc, path.span)
                 } else {
@@ -1460,26 +1460,20 @@ fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) {
         hir::ExprKind::InlineAsm(ref asm) => {
             for op in asm.operands {
                 match op {
-                    hir::InlineAsmOperand::In { expr, .. }
-                    | hir::InlineAsmOperand::Const { expr, .. }
-                    | hir::InlineAsmOperand::Sym { expr, .. } => this.visit_expr(expr),
                     hir::InlineAsmOperand::Out { expr, .. } => {
                         if let Some(expr) = expr {
                             this.check_place(expr);
-                            this.visit_expr(expr);
                         }
                     }
                     hir::InlineAsmOperand::InOut { expr, .. } => {
                         this.check_place(expr);
-                        this.visit_expr(expr);
                     }
-                    hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
-                        this.visit_expr(in_expr);
+                    hir::InlineAsmOperand::SplitInOut { out_expr, .. } => {
                         if let Some(out_expr) = out_expr {
                             this.check_place(out_expr);
-                            this.visit_expr(out_expr);
                         }
                     }
+                    _ => {}
                 }
             }
         }
@@ -1535,7 +1529,7 @@ fn check_place(&mut self, expr: &'tcx Expr<'tcx>) {
         match expr.kind {
             hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
                 if let Res::Local(var_hid) = path.res {
-                    let upvars = self.ir.tcx.upvars(self.ir.body_owner);
+                    let upvars = self.ir.tcx.upvars_mentioned(self.ir.body_owner);
                     if !upvars.map_or(false, |upvars| upvars.contains_key(&var_hid)) {
                         // Assignment to an immutable variable or argument: only legal
                         // if there is no later assignment. If this local is actually
index fb986caa415c9d62a62e6ac9ca573dc8c0dcd82c..99b4ef9d12fcd2a5872e0a4f764b2587996add7b 100644 (file)
@@ -10,7 +10,7 @@
 use rustc_span::Span;
 
 pub fn provide(providers: &mut Providers<'_>) {
-    providers.upvars = |tcx, def_id| {
+    providers.upvars_mentioned = |tcx, def_id| {
         if !tcx.is_closure(def_id) {
             return None;
         }
@@ -89,7 +89,7 @@ fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) {
     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
         if let hir::ExprKind::Closure(..) = expr.kind {
             let closure_def_id = self.tcx.hir().local_def_id(expr.hir_id);
-            if let Some(upvars) = self.tcx.upvars(closure_def_id) {
+            if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
                 // Every capture of a closure expression is a local in scope,
                 // that is moved/copied/borrowed into the closure value, and
                 // for this analysis they are like any other access to a local.
index 5c85855535e38529dcaab7f7dc7d2417a28f4c96..31992f298080ead60326a5e846cfa4466f745865 100644 (file)
@@ -1380,7 +1380,7 @@ fn maybe_note_obligation_cause_for_async_await(
         let mut interior_or_upvar_span = None;
         let mut interior_extra_info = None;
 
-        if let Some(upvars) = self.tcx.upvars(generator_did) {
+        if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) {
             interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| {
                 let upvar_ty = tables.node_type(*upvar_id);
                 let upvar_ty = self.resolve_vars_if_possible(&upvar_ty);
index 8fa901d8a984a6969cd368c09a195bf029a95ba2..af93f9bc8c0a79b74a237c592e20bf5a346281b0 100644 (file)
@@ -90,18 +90,20 @@ fn check_closure(
             base_substs.extend_to(self.tcx, expr_def_id.to_def_id(), |param, _| match param.kind {
                 GenericParamDefKind::Lifetime => span_bug!(expr.span, "closure has lifetime param"),
                 GenericParamDefKind::Type { .. } => if param.index as usize == tupled_upvars_idx {
-                    self.tcx.mk_tup(self.tcx.upvars(expr_def_id).iter().flat_map(|upvars| {
-                        upvars.iter().map(|(&var_hir_id, _)| {
-                            // Create type variables (for now) to represent the transformed
-                            // types of upvars. These will be unified during the upvar
-                            // inference phase (`upvar.rs`).
-                            self.infcx.next_ty_var(TypeVariableOrigin {
-                                // FIXME(eddyb) distinguish upvar inference variables from the rest.
-                                kind: TypeVariableOriginKind::ClosureSynthetic,
-                                span: self.tcx.hir().span(var_hir_id),
+                    self.tcx.mk_tup(self.tcx.upvars_mentioned(expr_def_id).iter().flat_map(
+                        |upvars| {
+                            upvars.iter().map(|(&var_hir_id, _)| {
+                                // Create type variables (for now) to represent the transformed
+                                // types of upvars. These will be unified during the upvar
+                                // inference phase (`upvar.rs`).
+                                self.infcx.next_ty_var(TypeVariableOrigin {
+                                    // FIXME(eddyb) distinguish upvar inference variables from the rest.
+                                    kind: TypeVariableOriginKind::ClosureSynthetic,
+                                    span: self.tcx.hir().span(var_hir_id),
+                                })
                             })
-                        })
-                    }))
+                        },
+                    ))
                 } else {
                     // Create type variables (for now) to represent the various
                     // pieces of information kept in `{Closure,Generic}Substs`.
index 6aa8242193d5fce87d9a22a4ae2c1f9e6023b30e..8707e4fe84a22807e06cf3095efd65dee3766ba1 100644 (file)
@@ -111,7 +111,7 @@ fn analyze_closure(
             None
         };
 
-        if let Some(upvars) = self.tcx.upvars(closure_def_id) {
+        if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
             let mut upvar_list: FxIndexMap<hir::HirId, ty::UpvarId> =
                 FxIndexMap::with_capacity_and_hasher(upvars.len(), Default::default());
             for (&var_hir_id, _) in upvars.iter() {
@@ -218,7 +218,7 @@ fn final_upvar_tys(&self, closure_id: hir::HirId) -> Vec<Ty<'tcx>> {
         let tcx = self.tcx;
         let closure_def_id = tcx.hir().local_def_id(closure_id);
 
-        tcx.upvars(closure_def_id)
+        tcx.upvars_mentioned(closure_def_id)
             .iter()
             .flat_map(|upvars| {
                 upvars.iter().map(|(&var_hir_id, _)| {
index 9ba00faec4978ea47246e6719a670eb763310e12..53973eba22940fba94b2659ed77bf0b22c5f9b57 100644 (file)
@@ -539,7 +539,7 @@ fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
         debug!("walk_captures({:?})", closure_expr);
 
         let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
-        if let Some(upvars) = self.tcx().upvars(closure_def_id) {
+        if let Some(upvars) = self.tcx().upvars_mentioned(closure_def_id) {
             for &var_id in upvars.keys() {
                 let upvar_id = ty::UpvarId {
                     var_path: ty::UpvarPath { hir_id: var_id },
index 71f3e2d03c9ff79f6b6076746d70ba82a6dfb5af..93d01ccd66f1e1059876a9c1fdbca0c23cf41001 100644 (file)
@@ -159,7 +159,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
             infcx,
             param_env,
             body_owner,
-            upvars: infcx.tcx.upvars(body_owner),
+            upvars: infcx.tcx.upvars_mentioned(body_owner),
         }
     }