1 //! This pass type-checks the MIR to ensure it is not broken.
3 #![allow(unreachable_code)]
5 use crate::borrow_check::borrow_set::BorrowSet;
6 use crate::borrow_check::location::LocationTable;
7 use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
8 use crate::borrow_check::nll::facts::AllFacts;
9 use crate::borrow_check::nll::region_infer::values::LivenessValues;
10 use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
11 use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
12 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
13 use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
14 use crate::borrow_check::nll::renumber;
15 use crate::borrow_check::nll::type_check::free_region_relations::{
16 CreateResult, UniversalRegionRelations,
18 use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
19 use crate::borrow_check::nll::ToRegionVid;
20 use crate::dataflow::move_paths::MoveData;
21 use crate::dataflow::FlowAtLocation;
22 use crate::dataflow::MaybeInitializedPlaces;
23 use crate::transform::{MirPass, MirSource};
26 use rustc::hir::def_id::DefId;
27 use rustc::infer::canonical::QueryRegionConstraint;
28 use rustc::infer::outlives::env::RegionBoundPairs;
29 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
30 use rustc::infer::type_variable::TypeVariableOrigin;
31 use rustc::mir::interpret::{InterpError::BoundsCheck, ConstValue};
32 use rustc::mir::tcx::PlaceTy;
33 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
35 use rustc::traits::query::type_op;
36 use rustc::traits::query::type_op::custom::CustomTypeOp;
37 use rustc::traits::query::{Fallible, NoSolution};
38 use rustc::traits::{ObligationCause, PredicateObligations};
39 use rustc::ty::adjustment::{PointerCast};
40 use rustc::ty::fold::TypeFoldable;
41 use rustc::ty::subst::{Subst, SubstsRef, UnpackedKind, UserSubsts};
43 self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
44 CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
45 UserTypeAnnotationIndex,
47 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
48 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
49 use rustc::ty::layout::VariantIdx;
51 use std::{fmt, iter, mem};
52 use syntax_pos::{Span, DUMMY_SP};
54 macro_rules! span_mirbug {
55 ($context:expr, $elem:expr, $($message:tt)*) => ({
56 $crate::borrow_check::nll::type_check::mirbug(
60 "broken MIR in {:?} ({:?}): {}",
63 format_args!($($message)*),
69 macro_rules! span_mirbug_and_err {
70 ($context:expr, $elem:expr, $($message:tt)*) => ({
72 span_mirbug!($context, $elem, $($message)*);
78 mod constraint_conversion;
79 pub mod free_region_relations;
84 /// Type checks the given `mir` in the context of the inference
85 /// context `infcx`. Returns any region constraints that have yet to
86 /// be proven. This result is includes liveness constraints that
87 /// ensure that regions appearing in the types of all local variables
88 /// are live at all points where that local variable may later be
91 /// This phase of type-check ought to be infallible -- this is because
92 /// the original, HIR-based type-check succeeded. So if any errors
93 /// occur here, we will get a `bug!` reported.
97 /// - `infcx` -- inference context to use
98 /// - `param_env` -- parameter environment to use for trait solving
99 /// - `mir` -- MIR to type-check
100 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
101 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
102 /// and lifetimes (e.g., `&'a T` implies `T: 'a`)
103 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
104 /// to outlive; should represent the fn body
105 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
106 /// the types of the input parameters found in the MIR itself will be equated with these
107 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
108 /// the type for the RETURN_PLACE will be equated with this
109 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
110 /// constraints for the regions in the types of variables
111 /// - `flow_inits` -- results of a maybe-init dataflow analysis
112 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
113 pub(crate) fn type_check<'gcx, 'tcx>(
114 infcx: &InferCtxt<'_, 'gcx, 'tcx>,
115 param_env: ty::ParamEnv<'gcx>,
118 universal_regions: &Rc<UniversalRegions<'tcx>>,
119 location_table: &LocationTable,
120 borrow_set: &BorrowSet<'tcx>,
121 all_facts: &mut Option<AllFacts>,
122 flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
123 move_data: &MoveData<'tcx>,
124 elements: &Rc<RegionValueElements>,
125 ) -> MirTypeckResults<'tcx> {
126 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
127 let mut constraints = MirTypeckRegionConstraints {
128 placeholder_indices: PlaceholderIndices::default(),
129 placeholder_index_to_region: IndexVec::default(),
130 liveness_constraints: LivenessValues::new(elements.clone()),
131 outlives_constraints: ConstraintSet::default(),
132 closure_bounds_mapping: Default::default(),
133 type_tests: Vec::default(),
137 universal_region_relations,
139 normalized_inputs_and_output,
140 } = free_region_relations::create(
143 Some(implicit_region_bound),
148 let mut borrowck_context = BorrowCheckContext {
153 constraints: &mut constraints,
162 Some(implicit_region_bound),
163 Some(&mut borrowck_context),
164 Some(&universal_region_relations),
166 cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
167 liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
171 .map(|bcx| translate_outlives_facts(bcx));
177 universal_region_relations,
181 fn type_check_internal<'a, 'gcx, 'tcx, R>(
182 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
184 param_env: ty::ParamEnv<'gcx>,
186 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
187 implicit_region_bound: Option<ty::Region<'tcx>>,
188 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
189 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
190 mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
192 let mut checker = TypeChecker::new(
198 implicit_region_bound,
200 universal_region_relations,
202 let errors_reported = {
203 let mut verifier = TypeVerifier::new(&mut checker, mir);
204 verifier.visit_mir(mir);
205 verifier.errors_reported
208 if !errors_reported {
209 // if verifier failed, don't do further checks to avoid ICEs
210 checker.typeck_mir(mir);
216 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
217 if let Some(facts) = cx.all_facts {
218 let location_table = cx.location_table;
221 .extend(cx.constraints.outlives_constraints.iter().flat_map(
222 |constraint: &OutlivesConstraint| {
223 if let Some(from_location) = constraint.locations.from_location() {
224 Either::Left(iter::once((
227 location_table.mid_index(from_location),
233 .map(move |location| (constraint.sup, constraint.sub, location)),
241 fn mirbug(tcx: TyCtxt<'_, '_, '_>, span: Span, msg: &str) {
242 // We sometimes see MIR failures (notably predicate failures) due to
243 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
244 // to avoid reporting bugs in those cases.
245 tcx.sess.diagnostic().delay_span_bug(span, msg);
248 enum FieldAccessError {
249 OutOfRange { field_count: usize },
252 /// Verifies that MIR types are sane to not crash further checks.
254 /// The sanitize_XYZ methods here take an MIR object and compute its
255 /// type, calling `span_mirbug` and returning an error type if there
257 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
258 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
262 errors_reported: bool,
265 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
266 fn visit_span(&mut self, span: &Span) {
267 if !span.is_dummy() {
268 self.last_span = *span;
272 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
273 self.sanitize_place(place, location, context);
276 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
277 self.super_constant(constant, location);
278 self.sanitize_constant(constant, location);
279 self.sanitize_type(constant, constant.ty);
281 if let Some(annotation_index) = constant.user_ty {
282 if let Err(terr) = self.cx.relate_type_and_user_type(
284 ty::Variance::Invariant,
285 &UserTypeProjection { base: annotation_index, projs: vec![], },
286 location.to_locations(),
287 ConstraintCategory::Boring,
289 let annotation = &self.cx.user_type_annotations[annotation_index];
293 "bad constant user type {:?} vs {:?}: {:?}",
300 if let ConstValue::Unevaluated(def_id, substs) = constant.literal.val {
301 if let Err(terr) = self.cx.fully_perform_op(
302 location.to_locations(),
303 ConstraintCategory::Boring,
304 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
305 constant.ty, def_id, UserSubsts { substs, user_self_ty: None },
311 "bad constant type {:?} ({:?})",
317 if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
318 let tcx = self.tcx();
320 let instantiated_predicates = tcx
321 .predicates_of(def_id)
322 .instantiate(tcx, substs);
323 self.cx.normalize_and_prove_instantiated_predicates(
324 instantiated_predicates,
325 location.to_locations(),
331 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
332 self.super_rvalue(rvalue, location);
333 let rval_ty = rvalue.ty(self.mir, self.tcx());
334 self.sanitize_type(rvalue, rval_ty);
337 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
338 self.super_local_decl(local, local_decl);
339 self.sanitize_type(local_decl, local_decl.ty);
341 for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
342 let ty = if !local_decl.is_nonref_binding() {
343 // If we have a binding of the form `let ref x: T = ..` then remove the outermost
344 // reference so we can check the type annotation for the remaining type.
345 if let ty::Ref(_, rty, _) = local_decl.ty.sty {
348 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
354 if let Err(terr) = self.cx.relate_type_and_user_type(
356 ty::Variance::Invariant,
358 Locations::All(*span),
359 ConstraintCategory::TypeAnnotation,
364 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
374 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
375 self.sanitize_type(&"return type", mir.return_ty());
376 for local_decl in &mir.local_decls {
377 self.sanitize_type(local_decl, local_decl.ty);
379 if self.errors_reported {
386 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
387 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'b Mir<'tcx>) -> Self {
390 mir_def_id: cx.mir_def_id,
393 errors_reported: false,
397 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
401 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
402 if ty.has_escaping_bound_vars() || ty.references_error() {
403 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
409 /// Checks that the constant's `ty` field matches up with what would be
410 /// expected from its literal. Unevaluated constants and well-formed
411 /// constraints are checked by `visit_constant`.
412 fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
414 "sanitize_constant(constant={:?}, location={:?})",
418 let literal = constant.literal;
420 if let ConstValue::Unevaluated(..) = literal.val {
424 debug!("sanitize_constant: expected_ty={:?}", literal.ty);
426 if let Err(terr) = self.cx.eq_types(
429 location.to_locations(),
430 ConstraintCategory::Boring,
435 "constant {:?} should have type {:?} but has {:?} ({:?})",
444 /// Checks that the types internal to the `place` match up with
445 /// what would be expected.
450 context: PlaceContext,
452 debug!("sanitize_place: {:?}", place);
453 let place_ty = match place {
454 Place::Base(PlaceBase::Local(index)) =>
455 PlaceTy::from_ty(self.mir.local_decls[*index].ty),
456 Place::Base(PlaceBase::Static(box Static { kind, ty: sty })) => {
457 let sty = self.sanitize_type(place, sty);
459 |verifier: &mut TypeVerifier<'a, 'b, 'gcx, 'tcx>,
463 if let Err(terr) = verifier.cx.eq_types(
466 location.to_locations(),
467 ConstraintCategory::Boring,
472 "bad promoted type ({:?}: {:?}): {:?}",
480 StaticKind::Promoted(promoted) => {
481 if !self.errors_reported {
482 let promoted_mir = &self.mir.promoted[*promoted];
483 self.sanitize_promoted(promoted_mir, location);
485 let promoted_ty = promoted_mir.return_ty();
486 check_err(self, place, promoted_ty, sty);
489 StaticKind::Static(def_id) => {
490 let ty = self.tcx().type_of(*def_id);
491 let ty = self.cx.normalize(ty, location);
493 check_err(self, place, ty, sty);
496 PlaceTy::from_ty(sty)
498 Place::Projection(ref proj) => {
499 let base_context = if context.is_mutating_use() {
500 PlaceContext::MutatingUse(MutatingUseContext::Projection)
502 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
504 let base_ty = self.sanitize_place(&proj.base, location, base_context);
505 if base_ty.variant_index.is_none() {
506 if base_ty.ty.references_error() {
507 assert!(self.errors_reported);
508 return PlaceTy::from_ty(self.tcx().types.err);
511 self.sanitize_projection(base_ty, &proj.elem, place, location)
514 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
515 let tcx = self.tcx();
516 let trait_ref = ty::TraitRef {
517 def_id: tcx.lang_items().copy_trait().unwrap(),
518 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
521 // In order to have a Copy operand, the type T of the
522 // value must be Copy. Note that we prove that T: Copy,
523 // rather than using the `is_copy_modulo_regions`
524 // test. This is important because
525 // `is_copy_modulo_regions` ignores the resulting region
526 // obligations and assumes they pass. This can result in
527 // bounds from Copy impls being unsoundly ignored (e.g.,
528 // #29149). Note that we decide to use Copy before knowing
529 // whether the bounds fully apply: in effect, the rule is
530 // that if a value of some type could implement Copy, then
532 self.cx.prove_trait_ref(
534 location.to_locations(),
535 ConstraintCategory::CopyBound,
541 fn sanitize_promoted(&mut self, promoted_mir: &'b Mir<'tcx>, location: Location) {
542 // Determine the constraints from the promoted MIR by running the type
543 // checker on the promoted MIR, then transfer the constraints back to
544 // the main MIR, changing the locations to the provided location.
546 let parent_mir = mem::replace(&mut self.mir, promoted_mir);
548 let all_facts = &mut None;
549 let mut constraints = Default::default();
550 let mut closure_bounds = Default::default();
551 if let Some(ref mut bcx) = self.cx.borrowck_context {
552 // Don't try to add borrow_region facts for the promoted MIR
553 mem::swap(bcx.all_facts, all_facts);
555 // Use a new sets of constraints and closure bounds so that we can
556 // modify their locations.
557 mem::swap(&mut bcx.constraints.outlives_constraints, &mut constraints);
558 mem::swap(&mut bcx.constraints.closure_bounds_mapping, &mut closure_bounds);
561 self.visit_mir(promoted_mir);
563 if !self.errors_reported {
564 // if verifier failed, don't do further checks to avoid ICEs
565 self.cx.typeck_mir(promoted_mir);
568 self.mir = parent_mir;
569 // Merge the outlives constraints back in, at the given location.
570 if let Some(ref mut base_bcx) = self.cx.borrowck_context {
571 mem::swap(base_bcx.all_facts, all_facts);
572 mem::swap(&mut base_bcx.constraints.outlives_constraints, &mut constraints);
573 mem::swap(&mut base_bcx.constraints.closure_bounds_mapping, &mut closure_bounds);
575 let locations = location.to_locations();
576 for constraint in constraints.iter() {
577 let mut constraint = *constraint;
578 constraint.locations = locations;
579 if let ConstraintCategory::Return
580 | ConstraintCategory::UseAsConst
581 | ConstraintCategory::UseAsStatic = constraint.category
583 // "Returning" from a promoted is an assigment to a
584 // temporary from the user's point of view.
585 constraint.category = ConstraintCategory::Boring;
587 base_bcx.constraints.outlives_constraints.push(constraint)
590 if !closure_bounds.is_empty() {
591 let combined_bounds_mapping = closure_bounds
593 .flat_map(|(_, value)| value)
595 let existing = base_bcx
597 .closure_bounds_mapping
598 .insert(location, combined_bounds_mapping);
601 "Multiple promoteds/closures at the same location."
607 fn sanitize_projection(
610 pi: &PlaceElem<'tcx>,
614 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
615 let tcx = self.tcx();
616 let base_ty = base.ty;
618 ProjectionElem::Deref => {
619 let deref_ty = base_ty.builtin_deref(true);
621 deref_ty.map(|t| t.ty).unwrap_or_else(|| {
622 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
626 ProjectionElem::Index(i) => {
627 let index_ty = Place::Base(PlaceBase::Local(i)).ty(self.mir, tcx).ty;
628 if index_ty != tcx.types.usize {
630 span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
634 base_ty.builtin_index().unwrap_or_else(|| {
635 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
640 ProjectionElem::ConstantIndex { .. } => {
641 // consider verifying in-bounds
643 base_ty.builtin_index().unwrap_or_else(|| {
644 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
648 ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
650 ty::Array(inner, size) => {
651 let size = size.unwrap_usize(tcx);
652 let min_size = (from as u64) + (to as u64);
653 if let Some(rest_size) = size.checked_sub(min_size) {
654 tcx.mk_array(inner, rest_size)
656 span_mirbug_and_err!(
659 "taking too-small slice of {:?}",
664 ty::Slice(..) => base_ty,
665 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
668 ProjectionElem::Downcast(maybe_name, index) => match base_ty.sty {
669 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
670 if index.as_usize() >= adt_def.variants.len() {
672 span_mirbug_and_err!(
675 "cast to variant #{:?} but enum only has {:?}",
677 adt_def.variants.len()
683 variant_index: Some(index),
688 let ty = if let Some(name) = maybe_name {
689 span_mirbug_and_err!(
692 "can't downcast {:?} as {:?}",
697 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
702 ProjectionElem::Field(field, fty) => {
703 let fty = self.sanitize_type(place, fty);
704 match self.field_ty(place, base, field, location) {
705 Ok(ty) => if let Err(terr) = self.cx.eq_types(
708 location.to_locations(),
709 ConstraintCategory::Boring,
714 "bad field access ({:?}: {:?}): {:?}",
720 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
723 "accessed field #{} but variant only has {}",
728 PlaceTy::from_ty(fty)
733 fn error(&mut self) -> Ty<'tcx> {
734 self.errors_reported = true;
740 parent: &dyn fmt::Debug,
741 base_ty: PlaceTy<'tcx>,
744 ) -> Result<Ty<'tcx>, FieldAccessError> {
745 let tcx = self.tcx();
747 let (variant, substs) = match base_ty {
748 PlaceTy { ty, variant_index: Some(variant_index) } => {
750 ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
751 _ => bug!("can't have downcast of non-adt type"),
754 PlaceTy { ty, variant_index: None } => match ty.sty {
755 ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
756 (&adt_def.variants[VariantIdx::new(0)], substs),
757 ty::Closure(def_id, substs) => {
758 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
760 None => Err(FieldAccessError::OutOfRange {
761 field_count: substs.upvar_tys(def_id, tcx).count(),
765 ty::Generator(def_id, substs, _) => {
766 // Try pre-transform fields first (upvars and current state)
767 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
771 // Then try `field_tys` which contains all the fields, but it
772 // requires the final optimized MIR.
773 return match substs.field_tys(def_id, tcx).nth(field.index()) {
775 None => Err(FieldAccessError::OutOfRange {
776 field_count: substs.field_tys(def_id, tcx).count(),
781 return match tys.get(field.index()) {
782 Some(&ty) => Ok(ty.expect_ty()),
783 None => Err(FieldAccessError::OutOfRange {
784 field_count: tys.len(),
789 return Ok(span_mirbug_and_err!(
792 "can't project out of {:?}",
799 if let Some(field) = variant.fields.get(field.index()) {
800 Ok(self.cx.normalize(&field.ty(tcx, substs), location))
802 Err(FieldAccessError::OutOfRange {
803 field_count: variant.fields.len(),
809 /// The MIR type checker. Visits the MIR and enforces all the
810 /// constraints needed for it to be valid and well-typed. Along the
811 /// way, it accrues region constraints -- these can later be used by
812 /// NLL region checking.
813 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
814 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
815 param_env: ty::ParamEnv<'gcx>,
817 /// User type annotations are shared between the main MIR and the MIR of
818 /// all of the promoted items.
819 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
821 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
822 implicit_region_bound: Option<ty::Region<'tcx>>,
823 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
824 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
825 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
828 struct BorrowCheckContext<'a, 'tcx: 'a> {
829 universal_regions: &'a UniversalRegions<'tcx>,
830 location_table: &'a LocationTable,
831 all_facts: &'a mut Option<AllFacts>,
832 borrow_set: &'a BorrowSet<'tcx>,
833 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
836 crate struct MirTypeckResults<'tcx> {
837 crate constraints: MirTypeckRegionConstraints<'tcx>,
838 crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
841 /// A collection of region constraints that must be satisfied for the
842 /// program to be considered well-typed.
843 crate struct MirTypeckRegionConstraints<'tcx> {
844 /// Maps from a `ty::Placeholder` to the corresponding
845 /// `PlaceholderIndex` bit that we will use for it.
847 /// To keep everything in sync, do not insert this set
848 /// directly. Instead, use the `placeholder_region` helper.
849 crate placeholder_indices: PlaceholderIndices,
851 /// Each time we add a placeholder to `placeholder_indices`, we
852 /// also create a corresponding "representative" region vid for
853 /// that wraps it. This vector tracks those. This way, when we
854 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
855 /// the same underlying `RegionVid`.
856 crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
858 /// In general, the type-checker is not responsible for enforcing
859 /// liveness constraints; this job falls to the region inferencer,
860 /// which performs a liveness analysis. However, in some limited
861 /// cases, the MIR type-checker creates temporary regions that do
862 /// not otherwise appear in the MIR -- in particular, the
863 /// late-bound regions that it instantiates at call-sites -- and
864 /// hence it must report on their liveness constraints.
865 crate liveness_constraints: LivenessValues<RegionVid>,
867 crate outlives_constraints: ConstraintSet,
869 crate closure_bounds_mapping:
870 FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
872 crate type_tests: Vec<TypeTest<'tcx>>,
875 impl MirTypeckRegionConstraints<'tcx> {
876 fn placeholder_region(
878 infcx: &InferCtxt<'_, '_, 'tcx>,
879 placeholder: ty::PlaceholderRegion,
880 ) -> ty::Region<'tcx> {
881 let placeholder_index = self.placeholder_indices.insert(placeholder);
882 match self.placeholder_index_to_region.get(placeholder_index) {
885 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
886 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
887 self.placeholder_index_to_region.push(region);
894 /// The `Locations` type summarizes *where* region constraints are
895 /// required to hold. Normally, this is at a particular point which
896 /// created the obligation, but for constraints that the user gave, we
897 /// want the constraint to hold at all points.
898 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
900 /// Indicates that a type constraint should always be true. This
901 /// is particularly important in the new borrowck analysis for
902 /// things like the type of the return slot. Consider this
906 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
908 /// return &y; // error
912 /// Here, we wind up with the signature from the return type being
913 /// something like `&'1 u32` where `'1` is a universal region. But
914 /// the type of the return slot `_0` is something like `&'2 u32`
915 /// where `'2` is an existential region variable. The type checker
916 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
917 /// older NLL analysis, we required this only at the entry point
918 /// to the function. By the nature of the constraints, this wound
919 /// up propagating to all points reachable from start (because
920 /// `'1` -- as a universal region -- is live everywhere). In the
921 /// newer analysis, though, this doesn't work: `_0` is considered
922 /// dead at the start (it has no usable value) and hence this type
923 /// equality is basically a no-op. Then, later on, when we do `_0
924 /// = &'3 y`, that region `'3` never winds up related to the
925 /// universal region `'1` and hence no error occurs. Therefore, we
926 /// use Locations::All instead, which ensures that the `'1` and
927 /// `'2` are equal everything. We also use this for other
928 /// user-given type annotations; e.g., if the user wrote `let mut
929 /// x: &'static u32 = ...`, we would ensure that all values
930 /// assigned to `x` are of `'static` lifetime.
932 /// The span points to the place the constraint arose. For example,
933 /// it points to the type in a user-given type annotation. If
934 /// there's no sensible span then it's DUMMY_SP.
937 /// An outlives constraint that only has to hold at a single location,
938 /// usually it represents a point where references flow from one spot to
939 /// another (e.g., `x = y`)
944 pub fn from_location(&self) -> Option<Location> {
946 Locations::All(_) => None,
947 Locations::Single(from_location) => Some(*from_location),
951 /// Gets a span representing the location.
952 pub fn span(&self, mir: &Mir<'_>) -> Span {
954 Locations::All(span) => *span,
955 Locations::Single(l) => mir.source_info(*l).span,
960 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
962 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
965 param_env: ty::ParamEnv<'gcx>,
966 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
967 implicit_region_bound: Option<ty::Region<'tcx>>,
968 borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
969 universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
971 let mut checker = Self {
975 user_type_annotations: &mir.user_type_annotations,
978 implicit_region_bound,
980 reported_errors: Default::default(),
981 universal_region_relations,
983 checker.check_user_type_annotations();
987 /// Equate the inferred type and the annotated type for user type annotations
988 fn check_user_type_annotations(&mut self) {
990 "check_user_type_annotations: user_type_annotations={:?}",
991 self.user_type_annotations
993 for user_annotation in self.user_type_annotations {
994 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
995 let (annotation, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars(
999 UserType::Ty(mut ty) => {
1000 ty = self.normalize(ty, Locations::All(span));
1002 if let Err(terr) = self.eq_types(
1005 Locations::All(span),
1006 ConstraintCategory::BoringNoLocation,
1011 "bad user type ({:?} = {:?}): {:?}",
1018 self.prove_predicate(
1019 ty::Predicate::WellFormed(inferred_ty),
1020 Locations::All(span),
1021 ConstraintCategory::TypeAnnotation,
1024 UserType::TypeOf(def_id, user_substs) => {
1025 if let Err(terr) = self.fully_perform_op(
1026 Locations::All(span),
1027 ConstraintCategory::BoringNoLocation,
1028 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1029 inferred_ty, def_id, user_substs,
1035 "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1047 /// Given some operation `op` that manipulates types, proves
1048 /// predicates, or otherwise uses the inference context, executes
1049 /// `op` and then executes all the further obligations that `op`
1050 /// returns. This will yield a set of outlives constraints amongst
1051 /// regions which are extracted and stored as having occurred at
1054 /// **Any `rustc::infer` operations that might generate region
1055 /// constraints should occur within this method so that those
1056 /// constraints can be properly localized!**
1057 fn fully_perform_op<R>(
1059 locations: Locations,
1060 category: ConstraintCategory,
1061 op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
1063 let (r, opt_data) = op.fully_perform(self.infcx)?;
1065 if let Some(data) = &opt_data {
1066 self.push_region_constraints(locations, category, data);
1072 fn push_region_constraints(
1074 locations: Locations,
1075 category: ConstraintCategory,
1076 data: &[QueryRegionConstraint<'tcx>],
1079 "push_region_constraints: constraints generated at {:?} are {:#?}",
1083 if let Some(ref mut borrowck_context) = self.borrowck_context {
1084 constraint_conversion::ConstraintConversion::new(
1086 borrowck_context.universal_regions,
1087 self.region_bound_pairs,
1088 self.implicit_region_bound,
1092 &mut borrowck_context.constraints,
1093 ).convert_all(&data);
1097 /// Convenient wrapper around `relate_tys::relate_types` -- see
1098 /// that fn for docs.
1104 locations: Locations,
1105 category: ConstraintCategory,
1107 relate_tys::relate_types(
1114 self.borrowck_context.as_mut().map(|x| &mut **x),
1122 locations: Locations,
1123 category: ConstraintCategory,
1125 self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1128 /// Try to relate `sub <: sup`; if this fails, instantiate opaque
1129 /// variables in `sub` with their inferred definitions and try
1130 /// again. This is used for opaque types in places (e.g., `let x:
1131 /// impl Foo = ..`).
1132 fn sub_types_or_anon(
1136 locations: Locations,
1137 category: ConstraintCategory,
1139 if let Err(terr) = self.sub_types(sub, sup, locations, category) {
1140 if let ty::Opaque(..) = sup.sty {
1141 // When you have `let x: impl Foo = ...` in a closure,
1142 // the resulting inferend values are stored with the
1143 // def-id of the base function.
1144 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
1145 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
1157 locations: Locations,
1158 category: ConstraintCategory,
1160 self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1163 fn relate_type_and_user_type(
1167 user_ty: &UserTypeProjection,
1168 locations: Locations,
1169 category: ConstraintCategory,
1172 "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1173 a, v, user_ty, locations,
1176 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1177 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1179 let tcx = self.infcx.tcx;
1181 for proj in &user_ty.projs {
1182 let projected_ty = curr_projected_ty.projection_ty_core(tcx, proj, |this, field, &()| {
1183 let ty = this.field_ty(tcx, field);
1184 self.normalize(ty, locations)
1186 curr_projected_ty = projected_ty;
1188 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1189 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1191 let ty = curr_projected_ty.ty;
1192 self.relate_types(a, v, ty, locations, category)?;
1197 fn eq_opaque_type_and_type(
1199 revealed_ty: Ty<'tcx>,
1201 anon_owner_def_id: DefId,
1202 locations: Locations,
1203 category: ConstraintCategory,
1206 "eq_opaque_type_and_type( \
1209 revealed_ty, anon_ty
1211 let infcx = self.infcx;
1212 let tcx = infcx.tcx;
1213 let param_env = self.param_env;
1214 debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1215 let opaque_type_map = self.fully_perform_op(
1220 let mut obligations = ObligationAccumulator::default();
1222 let dummy_body_id = ObligationCause::dummy().body_id;
1223 let (output_ty, opaque_type_map) =
1224 obligations.add(infcx.instantiate_opaque_types(
1231 "eq_opaque_type_and_type: \
1232 instantiated output_ty={:?} \
1233 opaque_type_map={:#?} \
1235 output_ty, opaque_type_map, revealed_ty
1237 obligations.add(infcx
1238 .at(&ObligationCause::dummy(), param_env)
1239 .eq(output_ty, revealed_ty)?);
1241 for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1242 let opaque_defn_ty = tcx.type_of(opaque_def_id);
1243 let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1244 let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1246 "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1247 opaque_decl.concrete_ty,
1248 infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1251 obligations.add(infcx
1252 .at(&ObligationCause::dummy(), param_env)
1253 .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1256 debug!("eq_opaque_type_and_type: equated");
1259 value: Some(opaque_type_map),
1260 obligations: obligations.into_vec(),
1263 || "input_output".to_string(),
1267 let universal_region_relations = match self.universal_region_relations {
1269 None => return Ok(()),
1272 // Finally, if we instantiated the anon types successfully, we
1273 // have to solve any bounds (e.g., `-> impl Iterator` needs to
1274 // prove that `T: Iterator` where `T` is the type we
1275 // instantiated it with).
1276 if let Some(opaque_type_map) = opaque_type_map {
1277 for (opaque_def_id, opaque_decl) in opaque_type_map {
1278 self.fully_perform_op(
1280 ConstraintCategory::OpaqueType,
1283 infcx.constrain_opaque_type(
1286 universal_region_relations,
1290 obligations: vec![],
1293 || "opaque_type_map".to_string(),
1301 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1305 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1306 debug!("check_stmt: {:?}", stmt);
1307 let tcx = self.tcx();
1309 StatementKind::Assign(ref place, ref rv) => {
1310 // Assignments to temporaries are not "interesting";
1311 // they are not caused by the user, but rather artifacts
1312 // of lowering. Assignments to other sorts of places *are* interesting
1314 let category = match *place {
1315 Place::Base(PlaceBase::Local(RETURN_PLACE)) => if let Some(BorrowCheckContext {
1318 defining_ty: DefiningTy::Const(def_id, _),
1322 }) = self.borrowck_context
1324 if tcx.is_static(*def_id) {
1325 ConstraintCategory::UseAsStatic
1327 ConstraintCategory::UseAsConst
1330 ConstraintCategory::Return
1332 Place::Base(PlaceBase::Local(l))
1333 if !mir.local_decls[l].is_user_variable.is_some() => {
1334 ConstraintCategory::Boring
1336 _ => ConstraintCategory::Assignment,
1339 let place_ty = place.ty(mir, tcx).ty;
1340 let rv_ty = rv.ty(mir, tcx);
1342 self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1347 "bad assignment ({:?} = {:?}): {:?}",
1354 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1355 if let Err(terr) = self.relate_type_and_user_type(
1357 ty::Variance::Invariant,
1358 &UserTypeProjection { base: annotation_index, projs: vec![], },
1359 location.to_locations(),
1360 ConstraintCategory::Boring,
1362 let annotation = &self.user_type_annotations[annotation_index];
1366 "bad user type on rvalue ({:?} = {:?}): {:?}",
1374 self.check_rvalue(mir, rv, location);
1375 if !self.tcx().features().unsized_locals {
1376 let trait_ref = ty::TraitRef {
1377 def_id: tcx.lang_items().sized_trait().unwrap(),
1378 substs: tcx.mk_substs_trait(place_ty, &[]),
1380 self.prove_trait_ref(
1382 location.to_locations(),
1383 ConstraintCategory::SizedBound,
1387 StatementKind::SetDiscriminant {
1391 let place_type = place.ty(mir, tcx).ty;
1392 let adt = match place_type.sty {
1393 ty::Adt(adt, _) if adt.is_enum() => adt,
1396 stmt.source_info.span,
1397 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1403 if variant_index.as_usize() >= adt.variants.len() {
1405 stmt.source_info.span,
1406 "bad set discriminant ({:?} = {:?}): value of of range",
1412 StatementKind::AscribeUserType(ref place, variance, box ref projection) => {
1413 let place_ty = place.ty(mir, tcx).ty;
1414 if let Err(terr) = self.relate_type_and_user_type(
1418 Locations::All(stmt.source_info.span),
1419 ConstraintCategory::TypeAnnotation,
1421 let annotation = &self.user_type_annotations[projection.base];
1425 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1433 StatementKind::FakeRead(..)
1434 | StatementKind::StorageLive(..)
1435 | StatementKind::StorageDead(..)
1436 | StatementKind::InlineAsm { .. }
1437 | StatementKind::Retag { .. }
1438 | StatementKind::Nop => {}
1442 fn check_terminator(
1445 term: &Terminator<'tcx>,
1446 term_location: Location,
1448 debug!("check_terminator: {:?}", term);
1449 let tcx = self.tcx();
1451 TerminatorKind::Goto { .. }
1452 | TerminatorKind::Resume
1453 | TerminatorKind::Abort
1454 | TerminatorKind::Return
1455 | TerminatorKind::GeneratorDrop
1456 | TerminatorKind::Unreachable
1457 | TerminatorKind::Drop { .. }
1458 | TerminatorKind::FalseEdges { .. }
1459 | TerminatorKind::FalseUnwind { .. } => {
1460 // no checks needed for these
1463 TerminatorKind::DropAndReplace {
1469 let place_ty = location.ty(mir, tcx).ty;
1470 let rv_ty = value.ty(mir, tcx);
1472 let locations = term_location.to_locations();
1474 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1479 "bad DropAndReplace ({:?} = {:?}): {:?}",
1486 TerminatorKind::SwitchInt {
1491 let discr_ty = discr.ty(mir, tcx);
1492 if let Err(terr) = self.sub_types(
1495 term_location.to_locations(),
1496 ConstraintCategory::Assignment,
1501 "bad SwitchInt ({:?} on {:?}): {:?}",
1507 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1508 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1510 // FIXME: check the values
1512 TerminatorKind::Call {
1519 let func_ty = func.ty(mir, tcx);
1520 debug!("check_terminator: call, func_ty={:?}", func_ty);
1521 let sig = match func_ty.sty {
1522 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1524 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1528 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1529 term.source_info.span,
1530 LateBoundRegionConversionTime::FnCall,
1533 let sig = self.normalize(sig, term_location);
1534 self.check_call_dest(mir, term, &sig, destination, term_location);
1536 self.prove_predicates(
1537 sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1538 term_location.to_locations(),
1539 ConstraintCategory::Boring,
1542 // The ordinary liveness rules will ensure that all
1543 // regions in the type of the callee are live here. We
1544 // then further constrain the late-bound regions that
1545 // were instantiated at the call site to be live as
1546 // well. The resulting is that all the input (and
1547 // output) types in the signature must be live, since
1548 // all the inputs that fed into it were live.
1549 for &late_bound_region in map.values() {
1550 if let Some(ref mut borrowck_context) = self.borrowck_context {
1551 let region_vid = borrowck_context
1553 .to_region_vid(late_bound_region);
1556 .liveness_constraints
1557 .add_element(region_vid, term_location);
1561 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1563 TerminatorKind::Assert {
1564 ref cond, ref msg, ..
1566 let cond_ty = cond.ty(mir, tcx);
1567 if cond_ty != tcx.types.bool {
1568 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1571 if let BoundsCheck { ref len, ref index } = *msg {
1572 if len.ty(mir, tcx) != tcx.types.usize {
1573 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1575 if index.ty(mir, tcx) != tcx.types.usize {
1576 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1580 TerminatorKind::Yield { ref value, .. } => {
1581 let value_ty = value.ty(mir, tcx);
1582 match mir.yield_ty {
1583 None => span_mirbug!(self, term, "yield in non-generator"),
1585 if let Err(terr) = self.sub_types(
1588 term_location.to_locations(),
1589 ConstraintCategory::Yield,
1594 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1609 term: &Terminator<'tcx>,
1610 sig: &ty::FnSig<'tcx>,
1611 destination: &Option<(Place<'tcx>, BasicBlock)>,
1612 term_location: Location,
1614 let tcx = self.tcx();
1615 match *destination {
1616 Some((ref dest, _target_block)) => {
1617 let dest_ty = dest.ty(mir, tcx).ty;
1618 let category = match *dest {
1619 Place::Base(PlaceBase::Local(RETURN_PLACE)) => {
1620 if let Some(BorrowCheckContext {
1623 defining_ty: DefiningTy::Const(def_id, _),
1627 }) = self.borrowck_context
1629 if tcx.is_static(*def_id) {
1630 ConstraintCategory::UseAsStatic
1632 ConstraintCategory::UseAsConst
1635 ConstraintCategory::Return
1638 Place::Base(PlaceBase::Local(l))
1639 if !mir.local_decls[l].is_user_variable.is_some() => {
1640 ConstraintCategory::Boring
1642 _ => ConstraintCategory::Assignment,
1645 let locations = term_location.to_locations();
1648 self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1653 "call dest mismatch ({:?} <- {:?}): {:?}",
1660 // When `#![feature(unsized_locals)]` is not enabled,
1661 // this check is done at `check_local`.
1662 if self.tcx().features().unsized_locals {
1663 let span = term.source_info.span;
1664 self.ensure_place_sized(dest_ty, span);
1668 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1669 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1675 fn check_call_inputs(
1678 term: &Terminator<'tcx>,
1679 sig: &ty::FnSig<'tcx>,
1680 args: &[Operand<'tcx>],
1681 term_location: Location,
1682 from_hir_call: bool,
1684 debug!("check_call_inputs({:?}, {:?})", sig, args);
1685 // Do not count the `VaList` argument as a "true" argument to
1686 // a C-variadic function.
1687 let inputs = if sig.c_variadic {
1688 &sig.inputs()[..sig.inputs().len() - 1]
1692 if args.len() < inputs.len() || (args.len() > inputs.len() && !sig.c_variadic) {
1693 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1695 for (n, (fn_arg, op_arg)) in inputs.iter().zip(args).enumerate() {
1696 let op_arg_ty = op_arg.ty(mir, self.tcx());
1697 let category = if from_hir_call {
1698 ConstraintCategory::CallArgument
1700 ConstraintCategory::Boring
1703 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1708 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1718 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1719 let is_cleanup = block_data.is_cleanup;
1720 self.last_span = block_data.terminator().source_info.span;
1721 match block_data.terminator().kind {
1722 TerminatorKind::Goto { target } => {
1723 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1725 TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1726 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1728 TerminatorKind::Resume => if !is_cleanup {
1729 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1731 TerminatorKind::Abort => if !is_cleanup {
1732 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1734 TerminatorKind::Return => if is_cleanup {
1735 span_mirbug!(self, block_data, "return on cleanup block")
1737 TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1738 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1740 TerminatorKind::Yield { resume, drop, .. } => {
1742 span_mirbug!(self, block_data, "yield in cleanup block")
1744 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1745 if let Some(drop) = drop {
1746 self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1749 TerminatorKind::Unreachable => {}
1750 TerminatorKind::Drop { target, unwind, .. }
1751 | TerminatorKind::DropAndReplace { target, unwind, .. }
1752 | TerminatorKind::Assert {
1757 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1758 if let Some(unwind) = unwind {
1760 span_mirbug!(self, block_data, "unwind on cleanup block")
1762 self.assert_iscleanup(mir, block_data, unwind, true);
1765 TerminatorKind::Call {
1770 if let &Some((_, target)) = destination {
1771 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1773 if let Some(cleanup) = cleanup {
1775 span_mirbug!(self, block_data, "cleanup on cleanup block")
1777 self.assert_iscleanup(mir, block_data, cleanup, true);
1780 TerminatorKind::FalseEdges {
1782 ref imaginary_targets,
1784 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1785 for target in imaginary_targets {
1786 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1789 TerminatorKind::FalseUnwind {
1793 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1794 if let Some(unwind) = unwind {
1799 "cleanup in cleanup block via false unwind"
1802 self.assert_iscleanup(mir, block_data, unwind, true);
1808 fn assert_iscleanup(
1811 ctxt: &dyn fmt::Debug,
1815 if mir[bb].is_cleanup != iscleanuppad {
1819 "cleanuppad mismatch: {:?} should be {:?}",
1826 fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1827 match mir.local_kind(local) {
1828 LocalKind::ReturnPointer | LocalKind::Arg => {
1829 // return values of normal functions are required to be
1830 // sized by typeck, but return values of ADT constructors are
1831 // not because we don't include a `Self: Sized` bounds on them.
1833 // Unbound parts of arguments were never required to be Sized
1834 // - maybe we should make that a warning.
1837 LocalKind::Var | LocalKind::Temp => {}
1840 // When `#![feature(unsized_locals)]` is enabled, only function calls
1841 // and nullary ops are checked in `check_call_dest`.
1842 if !self.tcx().features().unsized_locals {
1843 let span = local_decl.source_info.span;
1844 let ty = local_decl.ty;
1845 self.ensure_place_sized(ty, span);
1849 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1850 let tcx = self.tcx();
1852 // Erase the regions from `ty` to get a global type. The
1853 // `Sized` bound in no way depends on precise regions, so this
1854 // shouldn't affect `is_sized`.
1855 let gcx = tcx.global_tcx();
1856 let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1857 if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1858 // in current MIR construction, all non-control-flow rvalue
1859 // expressions evaluate through `as_temp` or `into` a return
1860 // slot or local, so to find all unsized rvalues it is enough
1861 // to check all temps, return slots and locals.
1862 if let None = self.reported_errors.replace((ty, span)) {
1863 let mut diag = struct_span_err!(
1867 "cannot move a value of type {0}: the size of {0} \
1868 cannot be statically determined",
1872 // While this is located in `nll::typeck` this error is not
1873 // an NLL error, it's a required check to prevent creation
1874 // of unsized rvalues in certain cases:
1875 // * operand of a box expression
1876 // * callee in a call expression
1882 fn aggregate_field_ty(
1884 ak: &AggregateKind<'tcx>,
1887 ) -> Result<Ty<'tcx>, FieldAccessError> {
1888 let tcx = self.tcx();
1891 AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1892 let variant = &def.variants[variant_index];
1893 let adj_field_index = active_field_index.unwrap_or(field_index);
1894 if let Some(field) = variant.fields.get(adj_field_index) {
1895 Ok(self.normalize(field.ty(tcx, substs), location))
1897 Err(FieldAccessError::OutOfRange {
1898 field_count: variant.fields.len(),
1902 AggregateKind::Closure(def_id, substs) => {
1903 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1905 None => Err(FieldAccessError::OutOfRange {
1906 field_count: substs.upvar_tys(def_id, tcx).count(),
1910 AggregateKind::Generator(def_id, substs, _) => {
1911 // Try pre-transform fields first (upvars and current state)
1912 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1915 // Then try `field_tys` which contains all the fields, but it
1916 // requires the final optimized MIR.
1917 match substs.field_tys(def_id, tcx).nth(field_index) {
1919 None => Err(FieldAccessError::OutOfRange {
1920 field_count: substs.field_tys(def_id, tcx).count(),
1925 AggregateKind::Array(ty) => Ok(ty),
1926 AggregateKind::Tuple => {
1927 unreachable!("This should have been covered in check_rvalues");
1932 fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1933 let tcx = self.tcx();
1936 Rvalue::Aggregate(ak, ops) => {
1937 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1940 Rvalue::Repeat(operand, len) => if *len > 1 {
1941 let operand_ty = operand.ty(mir, tcx);
1943 let trait_ref = ty::TraitRef {
1944 def_id: tcx.lang_items().copy_trait().unwrap(),
1945 substs: tcx.mk_substs_trait(operand_ty, &[]),
1948 self.prove_trait_ref(
1950 location.to_locations(),
1951 ConstraintCategory::CopyBound,
1955 Rvalue::NullaryOp(_, ty) => {
1956 // Even with unsized locals cannot box an unsized value.
1957 if self.tcx().features().unsized_locals {
1958 let span = mir.source_info(location).span;
1959 self.ensure_place_sized(ty, span);
1962 let trait_ref = ty::TraitRef {
1963 def_id: tcx.lang_items().sized_trait().unwrap(),
1964 substs: tcx.mk_substs_trait(ty, &[]),
1967 self.prove_trait_ref(
1969 location.to_locations(),
1970 ConstraintCategory::SizedBound,
1974 Rvalue::Cast(cast_kind, op, ty) => {
1976 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1977 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1979 // The type that we see in the fcx is like
1980 // `foo::<'a, 'b>`, where `foo` is the path to a
1981 // function definition. When we extract the
1982 // signature, it comes from the `fn_sig` query,
1983 // and hence may contain unnormalized results.
1984 let fn_sig = self.normalize(fn_sig, location);
1986 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1988 if let Err(terr) = self.eq_types(
1991 location.to_locations(),
1992 ConstraintCategory::Cast,
1997 "equating {:?} with {:?} yields {:?}",
2005 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
2006 let sig = match op.ty(mir, tcx).sty {
2007 ty::Closure(def_id, substs) => {
2008 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
2012 let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2014 if let Err(terr) = self.eq_types(
2017 location.to_locations(),
2018 ConstraintCategory::Cast,
2023 "equating {:?} with {:?} yields {:?}",
2031 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2032 let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
2034 // The type that we see in the fcx is like
2035 // `foo::<'a, 'b>`, where `foo` is the path to a
2036 // function definition. When we extract the
2037 // signature, it comes from the `fn_sig` query,
2038 // and hence may contain unnormalized results.
2039 let fn_sig = self.normalize(fn_sig, location);
2041 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2043 if let Err(terr) = self.eq_types(
2046 location.to_locations(),
2047 ConstraintCategory::Cast,
2052 "equating {:?} with {:?} yields {:?}",
2060 CastKind::Pointer(PointerCast::Unsize) => {
2062 let trait_ref = ty::TraitRef {
2063 def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
2064 substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
2067 self.prove_trait_ref(
2069 location.to_locations(),
2070 ConstraintCategory::Cast,
2074 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2075 let ty_from = match op.ty(mir, tcx).sty {
2076 ty::RawPtr(ty::TypeAndMut {
2078 mutbl: hir::MutMutable,
2084 "unexpected base type for cast {:?}",
2090 let ty_to = match ty.sty {
2091 ty::RawPtr(ty::TypeAndMut {
2093 mutbl: hir::MutImmutable,
2099 "unexpected target type for cast {:?}",
2105 if let Err(terr) = self.sub_types(
2108 location.to_locations(),
2109 ConstraintCategory::Cast,
2114 "relating {:?} with {:?} yields {:?}",
2123 if let ty::Ref(_, mut ty_from, _) = op.ty(mir, tcx).sty {
2124 let (mut ty_to, mutability) = if let ty::RawPtr(ty::TypeAndMut {
2133 "invalid cast types {:?} -> {:?}",
2140 // Handle the direct cast from `&[T; N]` to `*const T` by unwrapping
2141 // any array we find.
2142 while let ty::Array(ty_elem_from, _) = ty_from.sty {
2143 ty_from = ty_elem_from;
2144 if let ty::Array(ty_elem_to, _) = ty_to.sty {
2151 if let hir::MutMutable = mutability {
2152 if let Err(terr) = self.eq_types(
2155 location.to_locations(),
2156 ConstraintCategory::Cast,
2161 "equating {:?} with {:?} yields {:?}",
2168 if let Err(terr) = self.sub_types(
2171 location.to_locations(),
2172 ConstraintCategory::Cast,
2177 "relating {:?} with {:?} yields {:?}",
2189 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2190 self.add_reborrow_constraint(mir, location, region, borrowed_place);
2193 Rvalue::BinaryOp(BinOp::Eq, left, right)
2194 | Rvalue::BinaryOp(BinOp::Ne, left, right)
2195 | Rvalue::BinaryOp(BinOp::Lt, left, right)
2196 | Rvalue::BinaryOp(BinOp::Le, left, right)
2197 | Rvalue::BinaryOp(BinOp::Gt, left, right)
2198 | Rvalue::BinaryOp(BinOp::Ge, left, right) => {
2199 let ty_left = left.ty(mir, tcx);
2200 if let ty::RawPtr(_) | ty::FnPtr(_) = ty_left.sty {
2201 let ty_right = right.ty(mir, tcx);
2202 let common_ty = self.infcx.next_ty_var(
2203 TypeVariableOrigin::MiscVariable(mir.source_info(location).span),
2208 location.to_locations(),
2209 ConstraintCategory::Boring
2210 ).unwrap_or_else(|err| {
2211 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2213 if let Err(terr) = self.sub_types(
2216 location.to_locations(),
2217 ConstraintCategory::Boring
2222 "unexpected comparison types {:?} and {:?} yields {:?}",
2233 | Rvalue::BinaryOp(..)
2234 | Rvalue::CheckedBinaryOp(..)
2235 | Rvalue::UnaryOp(..)
2236 | Rvalue::Discriminant(..) => {}
2240 /// If this rvalue supports a user-given type annotation, then
2241 /// extract and return it. This represents the final type of the
2242 /// rvalue and will be unified with the inferred type.
2243 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2246 | Rvalue::Repeat(..)
2250 | Rvalue::BinaryOp(..)
2251 | Rvalue::CheckedBinaryOp(..)
2252 | Rvalue::NullaryOp(..)
2253 | Rvalue::UnaryOp(..)
2254 | Rvalue::Discriminant(..) => None,
2256 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2257 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2258 AggregateKind::Array(_) => None,
2259 AggregateKind::Tuple => None,
2260 AggregateKind::Closure(_, _) => None,
2261 AggregateKind::Generator(_, _, _) => None,
2266 fn check_aggregate_rvalue(
2269 rvalue: &Rvalue<'tcx>,
2270 aggregate_kind: &AggregateKind<'tcx>,
2271 operands: &[Operand<'tcx>],
2274 let tcx = self.tcx();
2276 self.prove_aggregate_predicates(aggregate_kind, location);
2278 if *aggregate_kind == AggregateKind::Tuple {
2279 // tuple rvalue field type is always the type of the op. Nothing to check here.
2283 for (i, operand) in operands.iter().enumerate() {
2284 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2285 Ok(field_ty) => field_ty,
2286 Err(FieldAccessError::OutOfRange { field_count }) => {
2290 "accessed field #{} but variant only has {}",
2297 let operand_ty = operand.ty(mir, tcx);
2299 if let Err(terr) = self.sub_types(
2302 location.to_locations(),
2303 ConstraintCategory::Boring,
2308 "{:?} is not a subtype of {:?}: {:?}",
2317 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2321 /// - `location`: the location `L` where the borrow expression occurs
2322 /// - `borrow_region`: the region `'a` associated with the borrow
2323 /// - `borrowed_place`: the place `P` being borrowed
2324 fn add_reborrow_constraint(
2328 borrow_region: ty::Region<'tcx>,
2329 borrowed_place: &Place<'tcx>,
2331 // These constraints are only meaningful during borrowck:
2332 let BorrowCheckContext {
2338 } = match self.borrowck_context {
2339 Some(ref mut borrowck_context) => borrowck_context,
2343 // In Polonius mode, we also push a `borrow_region` fact
2344 // linking the loan to the region (in some cases, though,
2345 // there is no loan associated with this borrow expression --
2346 // that occurs when we are borrowing an unsafe place, for
2348 if let Some(all_facts) = all_facts {
2349 if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2350 let region_vid = borrow_region.to_region_vid();
2351 all_facts.borrow_region.push((
2354 location_table.mid_index(location),
2359 // If we are reborrowing the referent of another reference, we
2360 // need to add outlives relationships. In a case like `&mut
2361 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2362 // need to ensure that `'b: 'a`.
2364 let mut borrowed_place = borrowed_place;
2367 "add_reborrow_constraint({:?}, {:?}, {:?})",
2368 location, borrow_region, borrowed_place
2370 while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2371 debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2374 ProjectionElem::Deref => {
2375 let tcx = self.infcx.tcx;
2376 let base_ty = base.ty(mir, tcx).ty;
2378 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2380 ty::Ref(ref_region, _, mutbl) => {
2381 constraints.outlives_constraints.push(OutlivesConstraint {
2382 sup: ref_region.to_region_vid(),
2383 sub: borrow_region.to_region_vid(),
2384 locations: location.to_locations(),
2385 category: ConstraintCategory::Boring,
2389 hir::Mutability::MutImmutable => {
2390 // Immutable reference. We don't need the base
2391 // to be valid for the entire lifetime of
2395 hir::Mutability::MutMutable => {
2396 // Mutable reference. We *do* need the base
2397 // to be valid, because after the base becomes
2398 // invalid, someone else can use our mutable deref.
2400 // This is in order to make the following function
2403 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2408 // As otherwise you could clone `&mut T` using the
2409 // following function:
2411 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2412 // let my_clone = unsafe_deref(&'a x);
2421 // deref of raw pointer, guaranteed to be valid
2424 ty::Adt(def, _) if def.is_box() => {
2425 // deref of `Box`, need the base to be valid - propagate
2427 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2430 ProjectionElem::Field(..)
2431 | ProjectionElem::Downcast(..)
2432 | ProjectionElem::Index(..)
2433 | ProjectionElem::ConstantIndex { .. }
2434 | ProjectionElem::Subslice { .. } => {
2435 // other field access
2439 // The "propagate" case. We need to check that our base is valid
2440 // for the borrow's lifetime.
2441 borrowed_place = base;
2445 fn prove_aggregate_predicates(
2447 aggregate_kind: &AggregateKind<'tcx>,
2450 let tcx = self.tcx();
2453 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2454 aggregate_kind, location
2457 let instantiated_predicates = match aggregate_kind {
2458 AggregateKind::Adt(def, _, substs, _, _) => {
2459 tcx.predicates_of(def.did).instantiate(tcx, substs)
2462 // For closures, we have some **extra requirements** we
2464 // have to check. In particular, in their upvars and
2465 // signatures, closures often reference various regions
2466 // from the surrounding function -- we call those the
2467 // closure's free regions. When we borrow-check (and hence
2468 // region-check) closures, we may find that the closure
2469 // requires certain relationships between those free
2470 // regions. However, because those free regions refer to
2471 // portions of the CFG of their caller, the closure is not
2472 // in a position to verify those relationships. In that
2473 // case, the requirements get "propagated" to us, and so
2474 // we have to solve them here where we instantiate the
2477 // Despite the opacity of the previous parapgrah, this is
2478 // actually relatively easy to understand in terms of the
2479 // desugaring. A closure gets desugared to a struct, and
2480 // these extra requirements are basically like where
2481 // clauses on the struct.
2482 AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2483 | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2484 self.prove_closure_bounds(tcx, *def_id, substs, location)
2487 AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2490 self.normalize_and_prove_instantiated_predicates(
2491 instantiated_predicates,
2492 location.to_locations(),
2496 fn prove_closure_bounds(
2498 tcx: TyCtxt<'a, 'gcx, 'tcx>,
2500 substs: SubstsRef<'tcx>,
2502 ) -> ty::InstantiatedPredicates<'tcx> {
2503 if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2504 let closure_constraints =
2505 closure_region_requirements.apply_requirements(tcx, def_id, substs);
2507 if let Some(ref mut borrowck_context) = self.borrowck_context {
2508 let bounds_mapping = closure_constraints
2511 .filter_map(|(idx, constraint)| {
2512 let ty::OutlivesPredicate(k1, r2) =
2513 constraint.no_bound_vars().unwrap_or_else(|| {
2514 bug!("query_constraint {:?} contained bound vars", constraint,);
2518 UnpackedKind::Lifetime(r1) => {
2519 // constraint is r1: r2
2520 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2521 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2522 let outlives_requirements =
2523 &closure_region_requirements.outlives_requirements[idx];
2527 outlives_requirements.category,
2528 outlives_requirements.blame_span,
2532 UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2537 let existing = borrowck_context
2539 .closure_bounds_mapping
2540 .insert(location, bounds_mapping);
2543 "Multiple closures at the same location."
2547 self.push_region_constraints(
2548 location.to_locations(),
2549 ConstraintCategory::ClosureBounds,
2550 &closure_constraints,
2554 tcx.predicates_of(def_id).instantiate(tcx, substs)
2559 trait_ref: ty::TraitRef<'tcx>,
2560 locations: Locations,
2561 category: ConstraintCategory,
2563 self.prove_predicates(
2564 Some(ty::Predicate::Trait(
2565 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2572 fn normalize_and_prove_instantiated_predicates(
2574 instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2575 locations: Locations,
2577 for predicate in instantiated_predicates.predicates {
2578 let predicate = self.normalize(predicate, locations);
2579 self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2583 fn prove_predicates(
2585 predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2586 locations: Locations,
2587 category: ConstraintCategory,
2589 for predicate in predicates {
2591 "prove_predicates(predicate={:?}, locations={:?})",
2592 predicate, locations,
2595 self.prove_predicate(predicate, locations, category);
2601 predicate: ty::Predicate<'tcx>,
2602 locations: Locations,
2603 category: ConstraintCategory,
2606 "prove_predicate(predicate={:?}, location={:?})",
2607 predicate, locations,
2610 let param_env = self.param_env;
2611 self.fully_perform_op(
2614 param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2615 ).unwrap_or_else(|NoSolution| {
2616 span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2620 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2621 self.last_span = mir.span;
2622 debug!("run_on_mir: {:?}", mir.span);
2624 for (local, local_decl) in mir.local_decls.iter_enumerated() {
2625 self.check_local(mir, local, local_decl);
2628 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2629 let mut location = Location {
2633 for stmt in &block_data.statements {
2634 if !stmt.source_info.span.is_dummy() {
2635 self.last_span = stmt.source_info.span;
2637 self.check_stmt(mir, stmt, location);
2638 location.statement_index += 1;
2641 self.check_terminator(mir, block_data.terminator(), location);
2642 self.check_iscleanup(mir, block_data);
2646 fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2648 T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2650 debug!("normalize(value={:?}, location={:?})", value, location);
2651 let param_env = self.param_env;
2652 self.fully_perform_op(
2653 location.to_locations(),
2654 ConstraintCategory::Boring,
2655 param_env.and(type_op::normalize::Normalize::new(value)),
2656 ).unwrap_or_else(|NoSolution| {
2657 span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2663 pub struct TypeckMir;
2665 impl MirPass for TypeckMir {
2666 fn run_pass<'a, 'tcx>(
2668 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2669 src: MirSource<'tcx>,
2670 mir: &mut Mir<'tcx>,
2672 let def_id = src.def_id();
2673 debug!("run_pass: {:?}", def_id);
2675 // FIXME: We don't need this MIR pass anymore.
2680 if tcx.sess.err_count() > 0 {
2681 // compiling a broken program can obviously result in a
2682 // broken MIR, so try not to report duplicate errors.
2686 if tcx.is_constructor(def_id) {
2687 // We just assume that the automatically generated struct/variant constructors are
2688 // correct. See the comment in the `mir_borrowck` implementation for an
2689 // explanation why we need this.
2693 let param_env = tcx.param_env(def_id);
2694 tcx.infer_ctxt().enter(|infcx| {
2695 type_check_internal(
2707 // For verification purposes, we just ignore the resulting
2708 // region constraint sets. Not our problem. =)
2713 trait NormalizeLocation: fmt::Debug + Copy {
2714 fn to_locations(self) -> Locations;
2717 impl NormalizeLocation for Locations {
2718 fn to_locations(self) -> Locations {
2723 impl NormalizeLocation for Location {
2724 fn to_locations(self) -> Locations {
2725 Locations::Single(self)
2729 #[derive(Debug, Default)]
2730 struct ObligationAccumulator<'tcx> {
2731 obligations: PredicateObligations<'tcx>,
2734 impl<'tcx> ObligationAccumulator<'tcx> {
2735 fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2736 let InferOk { value, obligations } = value;
2737 self.obligations.extend(obligations);
2741 fn into_vec(self) -> PredicateObligations<'tcx> {