]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Auto merge of #60379 - froydnj:bootstrap-progress-fixes, r=kennytm
[rust.git] / src / librustc_mir / borrow_check / nll / type_check / mod.rs
1 //! This pass type-checks the MIR to ensure it is not broken.
2
3 #![allow(unreachable_code)]
4
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,
17 };
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};
24 use either::Either;
25 use rustc::hir;
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};
34 use rustc::mir::*;
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};
42 use rustc::ty::{
43     self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType,
44     CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
45     UserTypeAnnotationIndex,
46 };
47 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
48 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
49 use rustc::ty::layout::VariantIdx;
50 use std::rc::Rc;
51 use std::{fmt, iter, mem};
52 use syntax_pos::{Span, DUMMY_SP};
53
54 macro_rules! span_mirbug {
55     ($context:expr, $elem:expr, $($message:tt)*) => ({
56         $crate::borrow_check::nll::type_check::mirbug(
57             $context.tcx(),
58             $context.last_span,
59             &format!(
60                 "broken MIR in {:?} ({:?}): {}",
61                 $context.mir_def_id,
62                 $elem,
63                 format_args!($($message)*),
64             ),
65         )
66     })
67 }
68
69 macro_rules! span_mirbug_and_err {
70     ($context:expr, $elem:expr, $($message:tt)*) => ({
71         {
72             span_mirbug!($context, $elem, $($message)*);
73             $context.error()
74         }
75     })
76 }
77
78 mod constraint_conversion;
79 pub mod free_region_relations;
80 mod input_output;
81 crate mod liveness;
82 mod relate_tys;
83
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
89 /// used.
90 ///
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.
94 ///
95 /// # Parameters
96 ///
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>,
116     mir: &Mir<'tcx>,
117     mir_def_id: DefId,
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(),
134     };
135
136     let CreateResult {
137         universal_region_relations,
138         region_bound_pairs,
139         normalized_inputs_and_output,
140     } = free_region_relations::create(
141         infcx,
142         param_env,
143         Some(implicit_region_bound),
144         universal_regions,
145         &mut constraints,
146     );
147
148     let mut borrowck_context = BorrowCheckContext {
149         universal_regions,
150         location_table,
151         borrow_set,
152         all_facts,
153         constraints: &mut constraints,
154     };
155
156     type_check_internal(
157         infcx,
158         mir_def_id,
159         param_env,
160         mir,
161         &region_bound_pairs,
162         Some(implicit_region_bound),
163         Some(&mut borrowck_context),
164         Some(&universal_region_relations),
165         |cx| {
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);
168
169             cx.borrowck_context
170                 .as_mut()
171                 .map(|bcx| translate_outlives_facts(bcx));
172         },
173     );
174
175     MirTypeckResults {
176         constraints,
177         universal_region_relations,
178     }
179 }
180
181 fn type_check_internal<'a, 'gcx, 'tcx, R>(
182     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
183     mir_def_id: DefId,
184     param_env: ty::ParamEnv<'gcx>,
185     mir: &'a Mir<'tcx>,
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,
191 ) -> R where {
192     let mut checker = TypeChecker::new(
193         infcx,
194         mir,
195         mir_def_id,
196         param_env,
197         region_bound_pairs,
198         implicit_region_bound,
199         borrowck_context,
200         universal_region_relations,
201     );
202     let errors_reported = {
203         let mut verifier = TypeVerifier::new(&mut checker, mir);
204         verifier.visit_mir(mir);
205         verifier.errors_reported
206     };
207
208     if !errors_reported {
209         // if verifier failed, don't do further checks to avoid ICEs
210         checker.typeck_mir(mir);
211     }
212
213     extra(&mut checker)
214 }
215
216 fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
217     if let Some(facts) = cx.all_facts {
218         let location_table = cx.location_table;
219         facts
220             .outlives
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((
225                             constraint.sup,
226                             constraint.sub,
227                             location_table.mid_index(from_location),
228                         )))
229                     } else {
230                         Either::Right(
231                             location_table
232                                 .all_points()
233                                 .map(move |location| (constraint.sup, constraint.sub, location)),
234                         )
235                     }
236                 },
237             ));
238     }
239 }
240
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);
246 }
247
248 enum FieldAccessError {
249     OutOfRange { field_count: usize },
250 }
251
252 /// Verifies that MIR types are sane to not crash further checks.
253 ///
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
256 /// is a problem.
257 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
258     cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
259     mir: &'b Mir<'tcx>,
260     last_span: Span,
261     mir_def_id: DefId,
262     errors_reported: bool,
263 }
264
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;
269         }
270     }
271
272     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
273         self.sanitize_place(place, location, context);
274     }
275
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);
280
281         if let Some(annotation_index) = constant.user_ty {
282             if let Err(terr) = self.cx.relate_type_and_user_type(
283                 constant.ty,
284                 ty::Variance::Invariant,
285                 &UserTypeProjection { base: annotation_index, projs: vec![], },
286                 location.to_locations(),
287                 ConstraintCategory::Boring,
288             ) {
289                 let annotation = &self.cx.user_type_annotations[annotation_index];
290                 span_mirbug!(
291                     self,
292                     constant,
293                     "bad constant user type {:?} vs {:?}: {:?}",
294                     annotation,
295                     constant.ty,
296                     terr,
297                 );
298             }
299         } else {
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 },
306                     )),
307                 ) {
308                     span_mirbug!(
309                         self,
310                         constant,
311                         "bad constant type {:?} ({:?})",
312                         constant,
313                         terr
314                     );
315                 }
316             }
317             if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
318                 let tcx = self.tcx();
319
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(),
326                 );
327             }
328         }
329     }
330
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);
335     }
336
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);
340
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 {
346                     rty
347                 } else {
348                     bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
349                 }
350             } else {
351                 local_decl.ty
352             };
353
354             if let Err(terr) = self.cx.relate_type_and_user_type(
355                 ty,
356                 ty::Variance::Invariant,
357                 user_ty,
358                 Locations::All(*span),
359                 ConstraintCategory::TypeAnnotation,
360             ) {
361                 span_mirbug!(
362                     self,
363                     local,
364                     "bad user type on variable {:?}: {:?} != {:?} ({:?})",
365                     local,
366                     local_decl.ty,
367                     local_decl.user_ty,
368                     terr,
369                 );
370             }
371         }
372     }
373
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);
378         }
379         if self.errors_reported {
380             return;
381         }
382         self.super_mir(mir);
383     }
384 }
385
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 {
388         TypeVerifier {
389             mir,
390             mir_def_id: cx.mir_def_id,
391             cx,
392             last_span: mir.span,
393             errors_reported: false,
394         }
395     }
396
397     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
398         self.cx.infcx.tcx
399     }
400
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)
404         } else {
405             ty
406         }
407     }
408
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) {
413         debug!(
414             "sanitize_constant(constant={:?}, location={:?})",
415             constant, location
416         );
417
418         let literal = constant.literal;
419
420         if let ConstValue::Unevaluated(..) = literal.val {
421             return;
422         }
423
424         debug!("sanitize_constant: expected_ty={:?}", literal.ty);
425
426         if let Err(terr) = self.cx.eq_types(
427             literal.ty,
428             constant.ty,
429             location.to_locations(),
430             ConstraintCategory::Boring,
431         ) {
432             span_mirbug!(
433                 self,
434                 constant,
435                 "constant {:?} should have type {:?} but has {:?} ({:?})",
436                 constant,
437                 literal.ty,
438                 constant.ty,
439                 terr,
440             );
441         }
442     }
443
444     /// Checks that the types internal to the `place` match up with
445     /// what would be expected.
446     fn sanitize_place(
447         &mut self,
448         place: &Place<'tcx>,
449         location: Location,
450         context: PlaceContext,
451     ) -> PlaceTy<'tcx> {
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);
458                 let check_err =
459                     |verifier: &mut TypeVerifier<'a, 'b, 'gcx, 'tcx>,
460                      place: &Place<'tcx>,
461                      ty,
462                      sty| {
463                         if let Err(terr) = verifier.cx.eq_types(
464                             sty,
465                             ty,
466                             location.to_locations(),
467                             ConstraintCategory::Boring,
468                         ) {
469                             span_mirbug!(
470                             verifier,
471                             place,
472                             "bad promoted type ({:?}: {:?}): {:?}",
473                             ty,
474                             sty,
475                             terr
476                         );
477                         };
478                     };
479                 match kind {
480                     StaticKind::Promoted(promoted) => {
481                         if !self.errors_reported {
482                             let promoted_mir = &self.mir.promoted[*promoted];
483                             self.sanitize_promoted(promoted_mir, location);
484
485                             let promoted_ty = promoted_mir.return_ty();
486                             check_err(self, place, promoted_ty, sty);
487                         }
488                     }
489                     StaticKind::Static(def_id) => {
490                         let ty = self.tcx().type_of(*def_id);
491                         let ty = self.cx.normalize(ty, location);
492
493                         check_err(self, place, ty, sty);
494                     }
495                 }
496                 PlaceTy::from_ty(sty)
497             }
498             Place::Projection(ref proj) => {
499                 let base_context = if context.is_mutating_use() {
500                     PlaceContext::MutatingUse(MutatingUseContext::Projection)
501                 } else {
502                     PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
503                 };
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);
509                     }
510                 }
511                 self.sanitize_projection(base_ty, &proj.elem, place, location)
512             }
513         };
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, &[]),
519             };
520
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
531             // it must.
532             self.cx.prove_trait_ref(
533                 trait_ref,
534                 location.to_locations(),
535                 ConstraintCategory::CopyBound,
536             );
537         }
538         place_ty
539     }
540
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.
545
546         let parent_mir = mem::replace(&mut self.mir, promoted_mir);
547
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);
554
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);
559         };
560
561         self.visit_mir(promoted_mir);
562
563         if !self.errors_reported {
564             // if verifier failed, don't do further checks to avoid ICEs
565             self.cx.typeck_mir(promoted_mir);
566         }
567
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);
574
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
582                 {
583                     // "Returning" from a promoted is an assigment to a
584                     // temporary from the user's point of view.
585                     constraint.category = ConstraintCategory::Boring;
586                 }
587                 base_bcx.constraints.outlives_constraints.push(constraint)
588             }
589
590             if !closure_bounds.is_empty() {
591                 let combined_bounds_mapping = closure_bounds
592                     .into_iter()
593                     .flat_map(|(_, value)| value)
594                     .collect();
595                 let existing = base_bcx
596                     .constraints
597                     .closure_bounds_mapping
598                     .insert(location, combined_bounds_mapping);
599                 assert!(
600                     existing.is_none(),
601                     "Multiple promoteds/closures at the same location."
602                 );
603             }
604         }
605     }
606
607     fn sanitize_projection(
608         &mut self,
609         base: PlaceTy<'tcx>,
610         pi: &PlaceElem<'tcx>,
611         place: &Place<'tcx>,
612         location: Location,
613     ) -> PlaceTy<'tcx> {
614         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
615         let tcx = self.tcx();
616         let base_ty = base.ty;
617         match *pi {
618             ProjectionElem::Deref => {
619                 let deref_ty = base_ty.builtin_deref(true);
620                 PlaceTy::from_ty(
621                     deref_ty.map(|t| t.ty).unwrap_or_else(|| {
622                         span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
623                     })
624                 )
625             }
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 {
629                     PlaceTy::from_ty(
630                         span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
631                     )
632                 } else {
633                     PlaceTy::from_ty(
634                         base_ty.builtin_index().unwrap_or_else(|| {
635                             span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
636                         }),
637                     )
638                 }
639             }
640             ProjectionElem::ConstantIndex { .. } => {
641                 // consider verifying in-bounds
642                 PlaceTy::from_ty(
643                     base_ty.builtin_index().unwrap_or_else(|| {
644                         span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
645                     }),
646                 )
647             }
648             ProjectionElem::Subslice { from, to } => PlaceTy::from_ty(
649                 match base_ty.sty {
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)
655                         } else {
656                             span_mirbug_and_err!(
657                                 self,
658                                 place,
659                                 "taking too-small slice of {:?}",
660                                 base_ty
661                             )
662                         }
663                     }
664                     ty::Slice(..) => base_ty,
665                     _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
666                 },
667             ),
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() {
671                         PlaceTy::from_ty(
672                             span_mirbug_and_err!(
673                                 self,
674                                 place,
675                                 "cast to variant #{:?} but enum only has {:?}",
676                                 index,
677                                 adt_def.variants.len()
678                             ),
679                         )
680                     } else {
681                         PlaceTy {
682                             ty: base_ty,
683                             variant_index: Some(index),
684                         }
685                     }
686                 }
687                 _ => {
688                     let ty = if let Some(name) = maybe_name {
689                         span_mirbug_and_err!(
690                             self,
691                             place,
692                             "can't downcast {:?} as {:?}",
693                             base_ty,
694                             name
695                         )
696                     } else {
697                         span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
698                     };
699                     PlaceTy::from_ty(ty)
700                 },
701             },
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(
706                         ty,
707                         fty,
708                         location.to_locations(),
709                         ConstraintCategory::Boring,
710                     ) {
711                         span_mirbug!(
712                             self,
713                             place,
714                             "bad field access ({:?}: {:?}): {:?}",
715                             ty,
716                             fty,
717                             terr
718                         );
719                     },
720                     Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
721                         self,
722                         place,
723                         "accessed field #{} but variant only has {}",
724                         field.index(),
725                         field_count
726                     ),
727                 }
728                 PlaceTy::from_ty(fty)
729             }
730         }
731     }
732
733     fn error(&mut self) -> Ty<'tcx> {
734         self.errors_reported = true;
735         self.tcx().types.err
736     }
737
738     fn field_ty(
739         &mut self,
740         parent: &dyn fmt::Debug,
741         base_ty: PlaceTy<'tcx>,
742         field: Field,
743         location: Location,
744     ) -> Result<Ty<'tcx>, FieldAccessError> {
745         let tcx = self.tcx();
746
747         let (variant, substs) = match base_ty {
748             PlaceTy { ty, variant_index: Some(variant_index) } => {
749                 match ty.sty {
750                     ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
751                     _ => bug!("can't have downcast of non-adt type"),
752                 }
753             }
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()) {
759                         Some(ty) => Ok(ty),
760                         None => Err(FieldAccessError::OutOfRange {
761                             field_count: substs.upvar_tys(def_id, tcx).count(),
762                         }),
763                     }
764                 }
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()) {
768                         return Ok(ty);
769                     }
770
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()) {
774                         Some(ty) => Ok(ty),
775                         None => Err(FieldAccessError::OutOfRange {
776                             field_count: substs.field_tys(def_id, tcx).count(),
777                         }),
778                     };
779                 }
780                 ty::Tuple(tys) => {
781                     return match tys.get(field.index()) {
782                         Some(&ty) => Ok(ty.expect_ty()),
783                         None => Err(FieldAccessError::OutOfRange {
784                             field_count: tys.len(),
785                         }),
786                     }
787                 }
788                 _ => {
789                     return Ok(span_mirbug_and_err!(
790                         self,
791                         parent,
792                         "can't project out of {:?}",
793                         base_ty
794                     ))
795                 }
796             },
797         };
798
799         if let Some(field) = variant.fields.get(field.index()) {
800             Ok(self.cx.normalize(&field.ty(tcx, substs), location))
801         } else {
802             Err(FieldAccessError::OutOfRange {
803                 field_count: variant.fields.len(),
804             })
805         }
806     }
807 }
808
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>,
816     last_span: Span,
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>,
820     mir_def_id: DefId,
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>>,
826 }
827
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>,
834 }
835
836 crate struct MirTypeckResults<'tcx> {
837     crate constraints: MirTypeckRegionConstraints<'tcx>,
838     crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
839 }
840
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.
846     ///
847     /// To keep everything in sync, do not insert this set
848     /// directly. Instead, use the `placeholder_region` helper.
849     crate placeholder_indices: PlaceholderIndices,
850
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>>,
857
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>,
866
867     crate outlives_constraints: ConstraintSet,
868
869     crate closure_bounds_mapping:
870         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
871
872     crate type_tests: Vec<TypeTest<'tcx>>,
873 }
874
875 impl MirTypeckRegionConstraints<'tcx> {
876     fn placeholder_region(
877         &mut self,
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) {
883             Some(&v) => v,
884             None => {
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);
888                 region
889             }
890         }
891     }
892 }
893
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)]
899 pub enum Locations {
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
903     /// example:
904     ///
905     /// ```
906     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
907     ///     let y = 22;
908     ///     return &y; // error
909     /// }
910     /// ```
911     ///
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.
931     ///
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.
935     All(Span),
936
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`)
940     Single(Location),
941 }
942
943 impl Locations {
944     pub fn from_location(&self) -> Option<Location> {
945         match self {
946             Locations::All(_) => None,
947             Locations::Single(from_location) => Some(*from_location),
948         }
949     }
950
951     /// Gets a span representing the location.
952     pub fn span(&self, mir: &Mir<'_>) -> Span {
953         match self {
954             Locations::All(span) => *span,
955             Locations::Single(l) => mir.source_info(*l).span,
956         }
957     }
958 }
959
960 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
961     fn new(
962         infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
963         mir: &'a Mir<'tcx>,
964         mir_def_id: DefId,
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>>,
970     ) -> Self {
971         let mut checker = Self {
972             infcx,
973             last_span: DUMMY_SP,
974             mir_def_id,
975             user_type_annotations: &mir.user_type_annotations,
976             param_env,
977             region_bound_pairs,
978             implicit_region_bound,
979             borrowck_context,
980             reported_errors: Default::default(),
981             universal_region_relations,
982         };
983         checker.check_user_type_annotations();
984         checker
985     }
986
987     /// Equate the inferred type and the annotated type for user type annotations
988     fn check_user_type_annotations(&mut self) {
989         debug!(
990             "check_user_type_annotations: user_type_annotations={:?}",
991              self.user_type_annotations
992         );
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(
996                 span, user_ty
997             );
998             match annotation {
999                 UserType::Ty(mut ty) => {
1000                     ty = self.normalize(ty, Locations::All(span));
1001
1002                     if let Err(terr) = self.eq_types(
1003                         ty,
1004                         inferred_ty,
1005                         Locations::All(span),
1006                         ConstraintCategory::BoringNoLocation,
1007                     ) {
1008                         span_mirbug!(
1009                             self,
1010                             user_annotation,
1011                             "bad user type ({:?} = {:?}): {:?}",
1012                             ty,
1013                             inferred_ty,
1014                             terr
1015                         );
1016                     }
1017
1018                     self.prove_predicate(
1019                         ty::Predicate::WellFormed(inferred_ty),
1020                         Locations::All(span),
1021                         ConstraintCategory::TypeAnnotation,
1022                     );
1023                 },
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,
1030                         )),
1031                     ) {
1032                         span_mirbug!(
1033                             self,
1034                             user_annotation,
1035                             "bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
1036                             inferred_ty,
1037                             def_id,
1038                             user_substs,
1039                             terr
1040                         );
1041                     }
1042                 },
1043             }
1044         }
1045     }
1046
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
1052     /// `locations`.
1053     ///
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>(
1058         &mut self,
1059         locations: Locations,
1060         category: ConstraintCategory,
1061         op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
1062     ) -> Fallible<R> {
1063         let (r, opt_data) = op.fully_perform(self.infcx)?;
1064
1065         if let Some(data) = &opt_data {
1066             self.push_region_constraints(locations, category, data);
1067         }
1068
1069         Ok(r)
1070     }
1071
1072     fn push_region_constraints(
1073         &mut self,
1074         locations: Locations,
1075         category: ConstraintCategory,
1076         data: &[QueryRegionConstraint<'tcx>],
1077     ) {
1078         debug!(
1079             "push_region_constraints: constraints generated at {:?} are {:#?}",
1080             locations, data
1081         );
1082
1083         if let Some(ref mut borrowck_context) = self.borrowck_context {
1084             constraint_conversion::ConstraintConversion::new(
1085                 self.infcx,
1086                 borrowck_context.universal_regions,
1087                 self.region_bound_pairs,
1088                 self.implicit_region_bound,
1089                 self.param_env,
1090                 locations,
1091                 category,
1092                 &mut borrowck_context.constraints,
1093             ).convert_all(&data);
1094         }
1095     }
1096
1097     /// Convenient wrapper around `relate_tys::relate_types` -- see
1098     /// that fn for docs.
1099     fn relate_types(
1100         &mut self,
1101         a: Ty<'tcx>,
1102         v: ty::Variance,
1103         b: Ty<'tcx>,
1104         locations: Locations,
1105         category: ConstraintCategory,
1106     ) -> Fallible<()> {
1107         relate_tys::relate_types(
1108             self.infcx,
1109             a,
1110             v,
1111             b,
1112             locations,
1113             category,
1114             self.borrowck_context.as_mut().map(|x| &mut **x),
1115         )
1116     }
1117
1118     fn sub_types(
1119         &mut self,
1120         sub: Ty<'tcx>,
1121         sup: Ty<'tcx>,
1122         locations: Locations,
1123         category: ConstraintCategory,
1124     ) -> Fallible<()> {
1125         self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
1126     }
1127
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(
1133         &mut self,
1134         sub: Ty<'tcx>,
1135         sup: Ty<'tcx>,
1136         locations: Locations,
1137         category: ConstraintCategory,
1138     ) -> Fallible<()> {
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);
1146             } else {
1147                 return Err(terr);
1148             }
1149         }
1150         Ok(())
1151     }
1152
1153     fn eq_types(
1154         &mut self,
1155         a: Ty<'tcx>,
1156         b: Ty<'tcx>,
1157         locations: Locations,
1158         category: ConstraintCategory,
1159     ) -> Fallible<()> {
1160         self.relate_types(a, ty::Variance::Invariant, b, locations, category)
1161     }
1162
1163     fn relate_type_and_user_type(
1164         &mut self,
1165         a: Ty<'tcx>,
1166         v: ty::Variance,
1167         user_ty: &UserTypeProjection,
1168         locations: Locations,
1169         category: ConstraintCategory,
1170     ) -> Fallible<()> {
1171         debug!(
1172             "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1173             a, v, user_ty, locations,
1174         );
1175
1176         let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1177         let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1178
1179         let tcx = self.infcx.tcx;
1180
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)
1185             });
1186             curr_projected_ty = projected_ty;
1187         }
1188         debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1189                 user_ty.base, annotated_type, user_ty.projs, curr_projected_ty);
1190
1191         let ty = curr_projected_ty.ty;
1192         self.relate_types(a, v, ty, locations, category)?;
1193
1194         Ok(())
1195     }
1196
1197     fn eq_opaque_type_and_type(
1198         &mut self,
1199         revealed_ty: Ty<'tcx>,
1200         anon_ty: Ty<'tcx>,
1201         anon_owner_def_id: DefId,
1202         locations: Locations,
1203         category: ConstraintCategory,
1204     ) -> Fallible<()> {
1205         debug!(
1206             "eq_opaque_type_and_type( \
1207              revealed_ty={:?}, \
1208              anon_ty={:?})",
1209             revealed_ty, anon_ty
1210         );
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(
1216             locations,
1217             category,
1218             CustomTypeOp::new(
1219                 |infcx| {
1220                     let mut obligations = ObligationAccumulator::default();
1221
1222                     let dummy_body_id = ObligationCause::dummy().body_id;
1223                     let (output_ty, opaque_type_map) =
1224                         obligations.add(infcx.instantiate_opaque_types(
1225                             anon_owner_def_id,
1226                             dummy_body_id,
1227                             param_env,
1228                             &anon_ty,
1229                         ));
1230                     debug!(
1231                         "eq_opaque_type_and_type: \
1232                          instantiated output_ty={:?} \
1233                          opaque_type_map={:#?} \
1234                          revealed_ty={:?}",
1235                         output_ty, opaque_type_map, revealed_ty
1236                     );
1237                     obligations.add(infcx
1238                         .at(&ObligationCause::dummy(), param_env)
1239                         .eq(output_ty, revealed_ty)?);
1240
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);
1245                         debug!(
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),
1249                             opaque_defn_ty
1250                         );
1251                         obligations.add(infcx
1252                             .at(&ObligationCause::dummy(), param_env)
1253                             .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1254                     }
1255
1256                     debug!("eq_opaque_type_and_type: equated");
1257
1258                     Ok(InferOk {
1259                         value: Some(opaque_type_map),
1260                         obligations: obligations.into_vec(),
1261                     })
1262                 },
1263                 || "input_output".to_string(),
1264             ),
1265         )?;
1266
1267         let universal_region_relations = match self.universal_region_relations {
1268             Some(rel) => rel,
1269             None => return Ok(()),
1270         };
1271
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(
1279                     locations,
1280                     ConstraintCategory::OpaqueType,
1281                     CustomTypeOp::new(
1282                         |_cx| {
1283                             infcx.constrain_opaque_type(
1284                                 opaque_def_id,
1285                                 &opaque_decl,
1286                                 universal_region_relations,
1287                             );
1288                             Ok(InferOk {
1289                                 value: (),
1290                                 obligations: vec![],
1291                             })
1292                         },
1293                         || "opaque_type_map".to_string(),
1294                     ),
1295                 )?;
1296             }
1297         }
1298         Ok(())
1299     }
1300
1301     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1302         self.infcx.tcx
1303     }
1304
1305     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1306         debug!("check_stmt: {:?}", stmt);
1307         let tcx = self.tcx();
1308         match stmt.kind {
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
1313                 // though.
1314                 let category = match *place {
1315                     Place::Base(PlaceBase::Local(RETURN_PLACE)) => if let Some(BorrowCheckContext {
1316                         universal_regions:
1317                             UniversalRegions {
1318                                 defining_ty: DefiningTy::Const(def_id, _),
1319                                 ..
1320                             },
1321                         ..
1322                     }) = self.borrowck_context
1323                     {
1324                         if tcx.is_static(*def_id) {
1325                             ConstraintCategory::UseAsStatic
1326                         } else {
1327                             ConstraintCategory::UseAsConst
1328                         }
1329                     } else {
1330                         ConstraintCategory::Return
1331                     },
1332                     Place::Base(PlaceBase::Local(l))
1333                         if !mir.local_decls[l].is_user_variable.is_some() => {
1334                         ConstraintCategory::Boring
1335                     }
1336                     _ => ConstraintCategory::Assignment,
1337                 };
1338
1339                 let place_ty = place.ty(mir, tcx).ty;
1340                 let rv_ty = rv.ty(mir, tcx);
1341                 if let Err(terr) =
1342                     self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1343                 {
1344                     span_mirbug!(
1345                         self,
1346                         stmt,
1347                         "bad assignment ({:?} = {:?}): {:?}",
1348                         place_ty,
1349                         rv_ty,
1350                         terr
1351                     );
1352                 }
1353
1354                 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1355                     if let Err(terr) = self.relate_type_and_user_type(
1356                         rv_ty,
1357                         ty::Variance::Invariant,
1358                         &UserTypeProjection { base: annotation_index, projs: vec![], },
1359                         location.to_locations(),
1360                         ConstraintCategory::Boring,
1361                     ) {
1362                         let annotation = &self.user_type_annotations[annotation_index];
1363                         span_mirbug!(
1364                             self,
1365                             stmt,
1366                             "bad user type on rvalue ({:?} = {:?}): {:?}",
1367                             annotation,
1368                             rv_ty,
1369                             terr
1370                         );
1371                     }
1372                 }
1373
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, &[]),
1379                     };
1380                     self.prove_trait_ref(
1381                         trait_ref,
1382                         location.to_locations(),
1383                         ConstraintCategory::SizedBound,
1384                     );
1385                 }
1386             }
1387             StatementKind::SetDiscriminant {
1388                 ref place,
1389                 variant_index,
1390             } => {
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,
1394                     _ => {
1395                         span_bug!(
1396                             stmt.source_info.span,
1397                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1398                             place,
1399                             variant_index
1400                         );
1401                     }
1402                 };
1403                 if variant_index.as_usize() >= adt.variants.len() {
1404                     span_bug!(
1405                         stmt.source_info.span,
1406                         "bad set discriminant ({:?} = {:?}): value of of range",
1407                         place,
1408                         variant_index
1409                     );
1410                 };
1411             }
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(
1415                     place_ty,
1416                     variance,
1417                     projection,
1418                     Locations::All(stmt.source_info.span),
1419                     ConstraintCategory::TypeAnnotation,
1420                 ) {
1421                     let annotation = &self.user_type_annotations[projection.base];
1422                     span_mirbug!(
1423                         self,
1424                         stmt,
1425                         "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1426                         place_ty,
1427                         annotation,
1428                         projection.projs,
1429                         terr
1430                     );
1431                 }
1432             }
1433             StatementKind::FakeRead(..)
1434             | StatementKind::StorageLive(..)
1435             | StatementKind::StorageDead(..)
1436             | StatementKind::InlineAsm { .. }
1437             | StatementKind::Retag { .. }
1438             | StatementKind::Nop => {}
1439         }
1440     }
1441
1442     fn check_terminator(
1443         &mut self,
1444         mir: &Mir<'tcx>,
1445         term: &Terminator<'tcx>,
1446         term_location: Location,
1447     ) {
1448         debug!("check_terminator: {:?}", term);
1449         let tcx = self.tcx();
1450         match term.kind {
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
1461             }
1462
1463             TerminatorKind::DropAndReplace {
1464                 ref location,
1465                 ref value,
1466                 target: _,
1467                 unwind: _,
1468             } => {
1469                 let place_ty = location.ty(mir, tcx).ty;
1470                 let rv_ty = value.ty(mir, tcx);
1471
1472                 let locations = term_location.to_locations();
1473                 if let Err(terr) =
1474                     self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1475                 {
1476                     span_mirbug!(
1477                         self,
1478                         term,
1479                         "bad DropAndReplace ({:?} = {:?}): {:?}",
1480                         place_ty,
1481                         rv_ty,
1482                         terr
1483                     );
1484                 }
1485             }
1486             TerminatorKind::SwitchInt {
1487                 ref discr,
1488                 switch_ty,
1489                 ..
1490             } => {
1491                 let discr_ty = discr.ty(mir, tcx);
1492                 if let Err(terr) = self.sub_types(
1493                     discr_ty,
1494                     switch_ty,
1495                     term_location.to_locations(),
1496                     ConstraintCategory::Assignment,
1497                 ) {
1498                     span_mirbug!(
1499                         self,
1500                         term,
1501                         "bad SwitchInt ({:?} on {:?}): {:?}",
1502                         switch_ty,
1503                         discr_ty,
1504                         terr
1505                     );
1506                 }
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);
1509                 }
1510                 // FIXME: check the values
1511             }
1512             TerminatorKind::Call {
1513                 ref func,
1514                 ref args,
1515                 ref destination,
1516                 from_hir_call,
1517                 ..
1518             } => {
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),
1523                     _ => {
1524                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1525                         return;
1526                     }
1527                 };
1528                 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1529                     term.source_info.span,
1530                     LateBoundRegionConversionTime::FnCall,
1531                     &sig,
1532                 );
1533                 let sig = self.normalize(sig, term_location);
1534                 self.check_call_dest(mir, term, &sig, destination, term_location);
1535
1536                 self.prove_predicates(
1537                     sig.inputs_and_output.iter().map(|ty| ty::Predicate::WellFormed(ty)),
1538                     term_location.to_locations(),
1539                     ConstraintCategory::Boring,
1540                 );
1541
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
1552                             .universal_regions
1553                             .to_region_vid(late_bound_region);
1554                         borrowck_context
1555                             .constraints
1556                             .liveness_constraints
1557                             .add_element(region_vid, term_location);
1558                     }
1559                 }
1560
1561                 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1562             }
1563             TerminatorKind::Assert {
1564                 ref cond, ref msg, ..
1565             } => {
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);
1569                 }
1570
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)
1574                     }
1575                     if index.ty(mir, tcx) != tcx.types.usize {
1576                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1577                     }
1578                 }
1579             }
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"),
1584                     Some(ty) => {
1585                         if let Err(terr) = self.sub_types(
1586                             value_ty,
1587                             ty,
1588                             term_location.to_locations(),
1589                             ConstraintCategory::Yield,
1590                         ) {
1591                             span_mirbug!(
1592                                 self,
1593                                 term,
1594                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1595                                 value_ty,
1596                                 ty,
1597                                 terr
1598                             );
1599                         }
1600                     }
1601                 }
1602             }
1603         }
1604     }
1605
1606     fn check_call_dest(
1607         &mut self,
1608         mir: &Mir<'tcx>,
1609         term: &Terminator<'tcx>,
1610         sig: &ty::FnSig<'tcx>,
1611         destination: &Option<(Place<'tcx>, BasicBlock)>,
1612         term_location: Location,
1613     ) {
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 {
1621                             universal_regions:
1622                                 UniversalRegions {
1623                                     defining_ty: DefiningTy::Const(def_id, _),
1624                                     ..
1625                                 },
1626                             ..
1627                         }) = self.borrowck_context
1628                         {
1629                             if tcx.is_static(*def_id) {
1630                                 ConstraintCategory::UseAsStatic
1631                             } else {
1632                                 ConstraintCategory::UseAsConst
1633                             }
1634                         } else {
1635                             ConstraintCategory::Return
1636                         }
1637                     }
1638                     Place::Base(PlaceBase::Local(l))
1639                         if !mir.local_decls[l].is_user_variable.is_some() => {
1640                         ConstraintCategory::Boring
1641                     }
1642                     _ => ConstraintCategory::Assignment,
1643                 };
1644
1645                 let locations = term_location.to_locations();
1646
1647                 if let Err(terr) =
1648                     self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1649                 {
1650                     span_mirbug!(
1651                         self,
1652                         term,
1653                         "call dest mismatch ({:?} <- {:?}): {:?}",
1654                         dest_ty,
1655                         sig.output(),
1656                         terr
1657                     );
1658                 }
1659
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);
1665                 }
1666             }
1667             None => {
1668                 if !sig.output().conservative_is_privately_uninhabited(self.tcx()) {
1669                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1670                 }
1671             }
1672         }
1673     }
1674
1675     fn check_call_inputs(
1676         &mut self,
1677         mir: &Mir<'tcx>,
1678         term: &Terminator<'tcx>,
1679         sig: &ty::FnSig<'tcx>,
1680         args: &[Operand<'tcx>],
1681         term_location: Location,
1682         from_hir_call: bool,
1683     ) {
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]
1689         } else {
1690             &sig.inputs()[..]
1691         };
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);
1694         }
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
1699             } else {
1700                 ConstraintCategory::Boring
1701             };
1702             if let Err(terr) =
1703                 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1704             {
1705                 span_mirbug!(
1706                     self,
1707                     term,
1708                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1709                     n,
1710                     fn_arg,
1711                     op_arg_ty,
1712                     terr
1713                 );
1714             }
1715         }
1716     }
1717
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)
1724             }
1725             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1726                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1727             },
1728             TerminatorKind::Resume => if !is_cleanup {
1729                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1730             },
1731             TerminatorKind::Abort => if !is_cleanup {
1732                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1733             },
1734             TerminatorKind::Return => if is_cleanup {
1735                 span_mirbug!(self, block_data, "return on cleanup block")
1736             },
1737             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1738                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1739             },
1740             TerminatorKind::Yield { resume, drop, .. } => {
1741                 if is_cleanup {
1742                     span_mirbug!(self, block_data, "yield in cleanup block")
1743                 }
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);
1747                 }
1748             }
1749             TerminatorKind::Unreachable => {}
1750             TerminatorKind::Drop { target, unwind, .. }
1751             | TerminatorKind::DropAndReplace { target, unwind, .. }
1752             | TerminatorKind::Assert {
1753                 target,
1754                 cleanup: unwind,
1755                 ..
1756             } => {
1757                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1758                 if let Some(unwind) = unwind {
1759                     if is_cleanup {
1760                         span_mirbug!(self, block_data, "unwind on cleanup block")
1761                     }
1762                     self.assert_iscleanup(mir, block_data, unwind, true);
1763                 }
1764             }
1765             TerminatorKind::Call {
1766                 ref destination,
1767                 cleanup,
1768                 ..
1769             } => {
1770                 if let &Some((_, target)) = destination {
1771                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1772                 }
1773                 if let Some(cleanup) = cleanup {
1774                     if is_cleanup {
1775                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1776                     }
1777                     self.assert_iscleanup(mir, block_data, cleanup, true);
1778                 }
1779             }
1780             TerminatorKind::FalseEdges {
1781                 real_target,
1782                 ref imaginary_targets,
1783             } => {
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);
1787                 }
1788             }
1789             TerminatorKind::FalseUnwind {
1790                 real_target,
1791                 unwind,
1792             } => {
1793                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1794                 if let Some(unwind) = unwind {
1795                     if is_cleanup {
1796                         span_mirbug!(
1797                             self,
1798                             block_data,
1799                             "cleanup in cleanup block via false unwind"
1800                         );
1801                     }
1802                     self.assert_iscleanup(mir, block_data, unwind, true);
1803                 }
1804             }
1805         }
1806     }
1807
1808     fn assert_iscleanup(
1809         &mut self,
1810         mir: &Mir<'tcx>,
1811         ctxt: &dyn fmt::Debug,
1812         bb: BasicBlock,
1813         iscleanuppad: bool,
1814     ) {
1815         if mir[bb].is_cleanup != iscleanuppad {
1816             span_mirbug!(
1817                 self,
1818                 ctxt,
1819                 "cleanuppad mismatch: {:?} should be {:?}",
1820                 bb,
1821                 iscleanuppad
1822             );
1823         }
1824     }
1825
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.
1832                 //
1833                 // Unbound parts of arguments were never required to be Sized
1834                 // - maybe we should make that a warning.
1835                 return;
1836             }
1837             LocalKind::Var | LocalKind::Temp => {}
1838         }
1839
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);
1846         }
1847     }
1848
1849     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1850         let tcx = self.tcx();
1851
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!(
1864                     self.tcx().sess,
1865                     span,
1866                     E0161,
1867                     "cannot move a value of type {0}: the size of {0} \
1868                      cannot be statically determined",
1869                     ty
1870                 );
1871
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
1877                 diag.emit();
1878             }
1879         }
1880     }
1881
1882     fn aggregate_field_ty(
1883         &mut self,
1884         ak: &AggregateKind<'tcx>,
1885         field_index: usize,
1886         location: Location,
1887     ) -> Result<Ty<'tcx>, FieldAccessError> {
1888         let tcx = self.tcx();
1889
1890         match *ak {
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))
1896                 } else {
1897                     Err(FieldAccessError::OutOfRange {
1898                         field_count: variant.fields.len(),
1899                     })
1900                 }
1901             }
1902             AggregateKind::Closure(def_id, substs) => {
1903                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1904                     Some(ty) => Ok(ty),
1905                     None => Err(FieldAccessError::OutOfRange {
1906                         field_count: substs.upvar_tys(def_id, tcx).count(),
1907                     }),
1908                 }
1909             }
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) {
1913                     Ok(ty)
1914                 } else {
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) {
1918                         Some(ty) => Ok(ty),
1919                         None => Err(FieldAccessError::OutOfRange {
1920                             field_count: substs.field_tys(def_id, tcx).count(),
1921                         }),
1922                     }
1923                 }
1924             }
1925             AggregateKind::Array(ty) => Ok(ty),
1926             AggregateKind::Tuple => {
1927                 unreachable!("This should have been covered in check_rvalues");
1928             }
1929         }
1930     }
1931
1932     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1933         let tcx = self.tcx();
1934
1935         match rvalue {
1936             Rvalue::Aggregate(ak, ops) => {
1937                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1938             }
1939
1940             Rvalue::Repeat(operand, len) => if *len > 1 {
1941                 let operand_ty = operand.ty(mir, tcx);
1942
1943                 let trait_ref = ty::TraitRef {
1944                     def_id: tcx.lang_items().copy_trait().unwrap(),
1945                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1946                 };
1947
1948                 self.prove_trait_ref(
1949                     trait_ref,
1950                     location.to_locations(),
1951                     ConstraintCategory::CopyBound,
1952                 );
1953             },
1954
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);
1960                 }
1961
1962                 let trait_ref = ty::TraitRef {
1963                     def_id: tcx.lang_items().sized_trait().unwrap(),
1964                     substs: tcx.mk_substs_trait(ty, &[]),
1965                 };
1966
1967                 self.prove_trait_ref(
1968                     trait_ref,
1969                     location.to_locations(),
1970                     ConstraintCategory::SizedBound,
1971                 );
1972             }
1973
1974             Rvalue::Cast(cast_kind, op, ty) => {
1975                 match cast_kind {
1976                     CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1977                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1978
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);
1985
1986                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1987
1988                         if let Err(terr) = self.eq_types(
1989                             ty_fn_ptr_from,
1990                             ty,
1991                             location.to_locations(),
1992                             ConstraintCategory::Cast,
1993                         ) {
1994                             span_mirbug!(
1995                                 self,
1996                                 rvalue,
1997                                 "equating {:?} with {:?} yields {:?}",
1998                                 ty_fn_ptr_from,
1999                                 ty,
2000                                 terr
2001                             );
2002                         }
2003                     }
2004
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)
2009                             }
2010                             _ => bug!(),
2011                         };
2012                         let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig, *unsafety);
2013
2014                         if let Err(terr) = self.eq_types(
2015                             ty_fn_ptr_from,
2016                             ty,
2017                             location.to_locations(),
2018                             ConstraintCategory::Cast,
2019                         ) {
2020                             span_mirbug!(
2021                                 self,
2022                                 rvalue,
2023                                 "equating {:?} with {:?} yields {:?}",
2024                                 ty_fn_ptr_from,
2025                                 ty,
2026                                 terr
2027                             );
2028                         }
2029                     }
2030
2031                     CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
2032                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
2033
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);
2040
2041                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2042
2043                         if let Err(terr) = self.eq_types(
2044                             ty_fn_ptr_from,
2045                             ty,
2046                             location.to_locations(),
2047                             ConstraintCategory::Cast,
2048                         ) {
2049                             span_mirbug!(
2050                                 self,
2051                                 rvalue,
2052                                 "equating {:?} with {:?} yields {:?}",
2053                                 ty_fn_ptr_from,
2054                                 ty,
2055                                 terr
2056                             );
2057                         }
2058                     }
2059
2060                     CastKind::Pointer(PointerCast::Unsize) => {
2061                         let &ty = ty;
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()]),
2065                         };
2066
2067                         self.prove_trait_ref(
2068                             trait_ref,
2069                             location.to_locations(),
2070                             ConstraintCategory::Cast,
2071                         );
2072                     }
2073
2074                     CastKind::Pointer(PointerCast::MutToConstPointer) => {
2075                         let ty_from = match op.ty(mir, tcx).sty {
2076                             ty::RawPtr(ty::TypeAndMut {
2077                                 ty: ty_from,
2078                                 mutbl: hir::MutMutable,
2079                             }) => ty_from,
2080                             _ => {
2081                                 span_mirbug!(
2082                                     self,
2083                                     rvalue,
2084                                     "unexpected base type for cast {:?}",
2085                                     ty,
2086                                 );
2087                                 return;
2088                             }
2089                         };
2090                         let ty_to = match ty.sty {
2091                             ty::RawPtr(ty::TypeAndMut {
2092                                 ty: ty_to,
2093                                 mutbl: hir::MutImmutable,
2094                             }) => ty_to,
2095                             _ => {
2096                                 span_mirbug!(
2097                                     self,
2098                                     rvalue,
2099                                     "unexpected target type for cast {:?}",
2100                                     ty,
2101                                 );
2102                                 return;
2103                             }
2104                         };
2105                         if let Err(terr) = self.sub_types(
2106                             ty_from,
2107                             ty_to,
2108                             location.to_locations(),
2109                             ConstraintCategory::Cast,
2110                         ) {
2111                             span_mirbug!(
2112                                 self,
2113                                 rvalue,
2114                                 "relating {:?} with {:?} yields {:?}",
2115                                 ty_from,
2116                                 ty_to,
2117                                 terr
2118                             )
2119                         }
2120                     }
2121
2122                     CastKind::Misc => {
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 {
2125                                 ty: ty_to,
2126                                 mutbl,
2127                             }) = ty.sty {
2128                                 (ty_to, mutbl)
2129                             } else {
2130                                 span_mirbug!(
2131                                     self,
2132                                     rvalue,
2133                                     "invalid cast types {:?} -> {:?}",
2134                                     op.ty(mir, tcx),
2135                                     ty,
2136                                 );
2137                                 return;
2138                             };
2139
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 {
2145                                     ty_to = ty_elem_to;
2146                                 } else {
2147                                     break;
2148                                 }
2149                             }
2150
2151                             if let hir::MutMutable = mutability {
2152                                 if let Err(terr) = self.eq_types(
2153                                     ty_from,
2154                                     ty_to,
2155                                     location.to_locations(),
2156                                     ConstraintCategory::Cast,
2157                                 ) {
2158                                     span_mirbug!(
2159                                         self,
2160                                         rvalue,
2161                                         "equating {:?} with {:?} yields {:?}",
2162                                         ty_from,
2163                                         ty_to,
2164                                         terr
2165                                     )
2166                                 }
2167                             } else {
2168                                 if let Err(terr) = self.sub_types(
2169                                     ty_from,
2170                                     ty_to,
2171                                     location.to_locations(),
2172                                     ConstraintCategory::Cast,
2173                                 ) {
2174                                     span_mirbug!(
2175                                         self,
2176                                         rvalue,
2177                                         "relating {:?} with {:?} yields {:?}",
2178                                         ty_from,
2179                                         ty_to,
2180                                         terr
2181                                     )
2182                                 }
2183                             }
2184                         }
2185                     }
2186                 }
2187             }
2188
2189             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2190                 self.add_reborrow_constraint(mir, location, region, borrowed_place);
2191             }
2192
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),
2204                     );
2205                     self.sub_types(
2206                         common_ty,
2207                         ty_left,
2208                         location.to_locations(),
2209                         ConstraintCategory::Boring
2210                     ).unwrap_or_else(|err| {
2211                         bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2212                     });
2213                     if let Err(terr) = self.sub_types(
2214                         common_ty,
2215                         ty_right,
2216                         location.to_locations(),
2217                         ConstraintCategory::Boring
2218                     ) {
2219                         span_mirbug!(
2220                             self,
2221                             rvalue,
2222                             "unexpected comparison types {:?} and {:?} yields {:?}",
2223                             ty_left,
2224                             ty_right,
2225                             terr
2226                         )
2227                     }
2228                 }
2229             }
2230
2231             Rvalue::Use(..)
2232             | Rvalue::Len(..)
2233             | Rvalue::BinaryOp(..)
2234             | Rvalue::CheckedBinaryOp(..)
2235             | Rvalue::UnaryOp(..)
2236             | Rvalue::Discriminant(..) => {}
2237         }
2238     }
2239
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> {
2244         match rvalue {
2245             Rvalue::Use(_)
2246             | Rvalue::Repeat(..)
2247             | Rvalue::Ref(..)
2248             | Rvalue::Len(..)
2249             | Rvalue::Cast(..)
2250             | Rvalue::BinaryOp(..)
2251             | Rvalue::CheckedBinaryOp(..)
2252             | Rvalue::NullaryOp(..)
2253             | Rvalue::UnaryOp(..)
2254             | Rvalue::Discriminant(..) => None,
2255
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,
2262             },
2263         }
2264     }
2265
2266     fn check_aggregate_rvalue(
2267         &mut self,
2268         mir: &Mir<'tcx>,
2269         rvalue: &Rvalue<'tcx>,
2270         aggregate_kind: &AggregateKind<'tcx>,
2271         operands: &[Operand<'tcx>],
2272         location: Location,
2273     ) {
2274         let tcx = self.tcx();
2275
2276         self.prove_aggregate_predicates(aggregate_kind, location);
2277
2278         if *aggregate_kind == AggregateKind::Tuple {
2279             // tuple rvalue field type is always the type of the op. Nothing to check here.
2280             return;
2281         }
2282
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 }) => {
2287                     span_mirbug!(
2288                         self,
2289                         rvalue,
2290                         "accessed field #{} but variant only has {}",
2291                         i,
2292                         field_count
2293                     );
2294                     continue;
2295                 }
2296             };
2297             let operand_ty = operand.ty(mir, tcx);
2298
2299             if let Err(terr) = self.sub_types(
2300                 operand_ty,
2301                 field_ty,
2302                 location.to_locations(),
2303                 ConstraintCategory::Boring,
2304             ) {
2305                 span_mirbug!(
2306                     self,
2307                     rvalue,
2308                     "{:?} is not a subtype of {:?}: {:?}",
2309                     operand_ty,
2310                     field_ty,
2311                     terr
2312                 );
2313             }
2314         }
2315     }
2316
2317     /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2318     ///
2319     /// # Parameters
2320     ///
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(
2325         &mut self,
2326         mir: &Mir<'tcx>,
2327         location: Location,
2328         borrow_region: ty::Region<'tcx>,
2329         borrowed_place: &Place<'tcx>,
2330     ) {
2331         // These constraints are only meaningful during borrowck:
2332         let BorrowCheckContext {
2333             borrow_set,
2334             location_table,
2335             all_facts,
2336             constraints,
2337             ..
2338         } = match self.borrowck_context {
2339             Some(ref mut borrowck_context) => borrowck_context,
2340             None => return,
2341         };
2342
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
2347         // example).
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((
2352                     region_vid,
2353                     *borrow_index,
2354                     location_table.mid_index(location),
2355                 ));
2356             }
2357         }
2358
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`.
2363
2364         let mut borrowed_place = borrowed_place;
2365
2366         debug!(
2367             "add_reborrow_constraint({:?}, {:?}, {:?})",
2368             location, borrow_region, borrowed_place
2369         );
2370         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2371             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2372
2373             match *elem {
2374                 ProjectionElem::Deref => {
2375                     let tcx = self.infcx.tcx;
2376                     let base_ty = base.ty(mir, tcx).ty;
2377
2378                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2379                     match base_ty.sty {
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,
2386                             });
2387
2388                             match mutbl {
2389                                 hir::Mutability::MutImmutable => {
2390                                     // Immutable reference. We don't need the base
2391                                     // to be valid for the entire lifetime of
2392                                     // the borrow.
2393                                     break;
2394                                 }
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.
2399
2400                                     // This is in order to make the following function
2401                                     // illegal:
2402                                     // ```
2403                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2404                                     //     &mut *x
2405                                     // }
2406                                     // ```
2407                                     //
2408                                     // As otherwise you could clone `&mut T` using the
2409                                     // following function:
2410                                     // ```
2411                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2412                                     //     let my_clone = unsafe_deref(&'a x);
2413                                     //     ENDREGION 'a;
2414                                     //     (my_clone, x)
2415                                     // }
2416                                     // ```
2417                                 }
2418                             }
2419                         }
2420                         ty::RawPtr(..) => {
2421                             // deref of raw pointer, guaranteed to be valid
2422                             break;
2423                         }
2424                         ty::Adt(def, _) if def.is_box() => {
2425                             // deref of `Box`, need the base to be valid - propagate
2426                         }
2427                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2428                     }
2429                 }
2430                 ProjectionElem::Field(..)
2431                 | ProjectionElem::Downcast(..)
2432                 | ProjectionElem::Index(..)
2433                 | ProjectionElem::ConstantIndex { .. }
2434                 | ProjectionElem::Subslice { .. } => {
2435                     // other field access
2436                 }
2437             }
2438
2439             // The "propagate" case. We need to check that our base is valid
2440             // for the borrow's lifetime.
2441             borrowed_place = base;
2442         }
2443     }
2444
2445     fn prove_aggregate_predicates(
2446         &mut self,
2447         aggregate_kind: &AggregateKind<'tcx>,
2448         location: Location,
2449     ) {
2450         let tcx = self.tcx();
2451
2452         debug!(
2453             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2454             aggregate_kind, location
2455         );
2456
2457         let instantiated_predicates = match aggregate_kind {
2458             AggregateKind::Adt(def, _, substs, _, _) => {
2459                 tcx.predicates_of(def.did).instantiate(tcx, substs)
2460             }
2461
2462             // For closures, we have some **extra requirements** we
2463             //
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
2475             // closure.
2476             //
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)
2485             }
2486
2487             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2488         };
2489
2490         self.normalize_and_prove_instantiated_predicates(
2491             instantiated_predicates,
2492             location.to_locations(),
2493         );
2494     }
2495
2496     fn prove_closure_bounds(
2497         &mut self,
2498         tcx: TyCtxt<'a, 'gcx, 'tcx>,
2499         def_id: DefId,
2500         substs: SubstsRef<'tcx>,
2501         location: Location,
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);
2506
2507             if let Some(ref mut borrowck_context) = self.borrowck_context {
2508                 let bounds_mapping = closure_constraints
2509                     .iter()
2510                     .enumerate()
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,);
2515                             });
2516
2517                         match k1.unpack() {
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];
2524                                 Some((
2525                                     (r1_vid, r2_vid),
2526                                     (
2527                                         outlives_requirements.category,
2528                                         outlives_requirements.blame_span,
2529                                     ),
2530                                 ))
2531                             }
2532                             UnpackedKind::Type(_) | UnpackedKind::Const(_) => None,
2533                         }
2534                     })
2535                     .collect();
2536
2537                 let existing = borrowck_context
2538                     .constraints
2539                     .closure_bounds_mapping
2540                     .insert(location, bounds_mapping);
2541                 assert!(
2542                     existing.is_none(),
2543                     "Multiple closures at the same location."
2544                 );
2545             }
2546
2547             self.push_region_constraints(
2548                 location.to_locations(),
2549                 ConstraintCategory::ClosureBounds,
2550                 &closure_constraints,
2551             );
2552         }
2553
2554         tcx.predicates_of(def_id).instantiate(tcx, substs)
2555     }
2556
2557     fn prove_trait_ref(
2558         &mut self,
2559         trait_ref: ty::TraitRef<'tcx>,
2560         locations: Locations,
2561         category: ConstraintCategory,
2562     ) {
2563         self.prove_predicates(
2564             Some(ty::Predicate::Trait(
2565                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2566             )),
2567             locations,
2568             category,
2569         );
2570     }
2571
2572     fn normalize_and_prove_instantiated_predicates(
2573         &mut self,
2574         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2575         locations: Locations,
2576     ) {
2577         for predicate in instantiated_predicates.predicates {
2578             let predicate = self.normalize(predicate, locations);
2579             self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2580         }
2581     }
2582
2583     fn prove_predicates(
2584         &mut self,
2585         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2586         locations: Locations,
2587         category: ConstraintCategory,
2588     ) {
2589         for predicate in predicates {
2590             debug!(
2591                 "prove_predicates(predicate={:?}, locations={:?})",
2592                 predicate, locations,
2593             );
2594
2595             self.prove_predicate(predicate, locations, category);
2596         }
2597     }
2598
2599     fn prove_predicate(
2600         &mut self,
2601         predicate: ty::Predicate<'tcx>,
2602         locations: Locations,
2603         category: ConstraintCategory,
2604     ) {
2605         debug!(
2606             "prove_predicate(predicate={:?}, location={:?})",
2607             predicate, locations,
2608         );
2609
2610         let param_env = self.param_env;
2611         self.fully_perform_op(
2612             locations,
2613             category,
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);
2617         })
2618     }
2619
2620     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2621         self.last_span = mir.span;
2622         debug!("run_on_mir: {:?}", mir.span);
2623
2624         for (local, local_decl) in mir.local_decls.iter_enumerated() {
2625             self.check_local(mir, local, local_decl);
2626         }
2627
2628         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2629             let mut location = Location {
2630                 block,
2631                 statement_index: 0,
2632             };
2633             for stmt in &block_data.statements {
2634                 if !stmt.source_info.span.is_dummy() {
2635                     self.last_span = stmt.source_info.span;
2636                 }
2637                 self.check_stmt(mir, stmt, location);
2638                 location.statement_index += 1;
2639             }
2640
2641             self.check_terminator(mir, block_data.terminator(), location);
2642             self.check_iscleanup(mir, block_data);
2643         }
2644     }
2645
2646     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2647     where
2648         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2649     {
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);
2658             value
2659         })
2660     }
2661 }
2662
2663 pub struct TypeckMir;
2664
2665 impl MirPass for TypeckMir {
2666     fn run_pass<'a, 'tcx>(
2667         &self,
2668         tcx: TyCtxt<'a, 'tcx, 'tcx>,
2669         src: MirSource<'tcx>,
2670         mir: &mut Mir<'tcx>,
2671     ) {
2672         let def_id = src.def_id();
2673         debug!("run_pass: {:?}", def_id);
2674
2675         // FIXME: We don't need this MIR pass anymore.
2676         if true {
2677             return;
2678         }
2679
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.
2683             return;
2684         }
2685
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.
2690             return;
2691         }
2692
2693         let param_env = tcx.param_env(def_id);
2694         tcx.infer_ctxt().enter(|infcx| {
2695             type_check_internal(
2696                 &infcx,
2697                 def_id,
2698                 param_env,
2699                 mir,
2700                 &vec![],
2701                 None,
2702                 None,
2703                 None,
2704                 |_| (),
2705             );
2706
2707             // For verification purposes, we just ignore the resulting
2708             // region constraint sets. Not our problem. =)
2709         });
2710     }
2711 }
2712
2713 trait NormalizeLocation: fmt::Debug + Copy {
2714     fn to_locations(self) -> Locations;
2715 }
2716
2717 impl NormalizeLocation for Locations {
2718     fn to_locations(self) -> Locations {
2719         self
2720     }
2721 }
2722
2723 impl NormalizeLocation for Location {
2724     fn to_locations(self) -> Locations {
2725         Locations::Single(self)
2726     }
2727 }
2728
2729 #[derive(Debug, Default)]
2730 struct ObligationAccumulator<'tcx> {
2731     obligations: PredicateObligations<'tcx>,
2732 }
2733
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);
2738         value
2739     }
2740
2741     fn into_vec(self) -> PredicateObligations<'tcx> {
2742         self.obligations
2743     }
2744 }