]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/type_check/mod.rs
Rollup merge of #95909 - vacuus:theme-build-rule, r=GuillaumeGomez
[rust.git] / compiler / rustc_borrowck / src / type_check / mod.rs
1 //! This pass type-checks the MIR to ensure it is not broken.
2
3 use std::rc::Rc;
4 use std::{fmt, iter, mem};
5
6 use either::Either;
7
8 use hir::OpaqueTyOrigin;
9 use rustc_data_structures::frozen::Frozen;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_data_structures::vec_map::VecMap;
12 use rustc_errors::struct_span_err;
13 use rustc_hir as hir;
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::LocalDefId;
16 use rustc_hir::lang_items::LangItem;
17 use rustc_index::vec::{Idx, IndexVec};
18 use rustc_infer::infer::canonical::QueryRegionConstraints;
19 use rustc_infer::infer::outlives::env::RegionBoundPairs;
20 use rustc_infer::infer::region_constraints::RegionConstraintData;
21 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
22 use rustc_infer::infer::{
23     InferCtxt, InferOk, LateBoundRegionConversionTime, NllRegionVariableOrigin,
24 };
25 use rustc_middle::mir::tcx::PlaceTy;
26 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
27 use rustc_middle::mir::AssertKind;
28 use rustc_middle::mir::*;
29 use rustc_middle::ty::adjustment::PointerCast;
30 use rustc_middle::ty::cast::CastTy;
31 use rustc_middle::ty::fold::TypeFoldable;
32 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef, UserSubsts};
33 use rustc_middle::ty::{
34     self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, OpaqueHiddenType,
35     OpaqueTypeKey, RegionVid, ToPredicate, Ty, TyCtxt, UserType, UserTypeAnnotationIndex,
36 };
37 use rustc_span::def_id::CRATE_DEF_ID;
38 use rustc_span::{Span, DUMMY_SP};
39 use rustc_target::abi::VariantIdx;
40 use rustc_trait_selection::infer::InferCtxtExt as _;
41 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
42 use rustc_trait_selection::traits::query::type_op;
43 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
44 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
45 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
46 use rustc_trait_selection::traits::query::Fallible;
47 use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligation};
48
49 use rustc_const_eval::transform::{
50     check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression,
51 };
52 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
53 use rustc_mir_dataflow::move_paths::MoveData;
54 use rustc_mir_dataflow::ResultsCursor;
55
56 use crate::{
57     borrow_set::BorrowSet,
58     constraints::{OutlivesConstraint, OutlivesConstraintSet},
59     diagnostics::UniverseInfo,
60     facts::AllFacts,
61     location::LocationTable,
62     member_constraints::MemberConstraintSet,
63     nll::ToRegionVid,
64     path_utils,
65     region_infer::values::{
66         LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
67     },
68     region_infer::{ClosureRegionRequirementsExt, TypeTest},
69     type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
70     universal_regions::{DefiningTy, UniversalRegions},
71     Upvar,
72 };
73
74 macro_rules! span_mirbug {
75     ($context:expr, $elem:expr, $($message:tt)*) => ({
76         $crate::type_check::mirbug(
77             $context.tcx(),
78             $context.last_span,
79             &format!(
80                 "broken MIR in {:?} ({:?}): {}",
81                 $context.body().source.def_id(),
82                 $elem,
83                 format_args!($($message)*),
84             ),
85         )
86     })
87 }
88
89 macro_rules! span_mirbug_and_err {
90     ($context:expr, $elem:expr, $($message:tt)*) => ({
91         {
92             span_mirbug!($context, $elem, $($message)*);
93             $context.error()
94         }
95     })
96 }
97
98 mod canonical;
99 mod constraint_conversion;
100 pub mod free_region_relations;
101 mod input_output;
102 crate mod liveness;
103 mod relate_tys;
104
105 /// Type checks the given `mir` in the context of the inference
106 /// context `infcx`. Returns any region constraints that have yet to
107 /// be proven. This result includes liveness constraints that
108 /// ensure that regions appearing in the types of all local variables
109 /// are live at all points where that local variable may later be
110 /// used.
111 ///
112 /// This phase of type-check ought to be infallible -- this is because
113 /// the original, HIR-based type-check succeeded. So if any errors
114 /// occur here, we will get a `bug!` reported.
115 ///
116 /// # Parameters
117 ///
118 /// - `infcx` -- inference context to use
119 /// - `param_env` -- parameter environment to use for trait solving
120 /// - `body` -- MIR body to type-check
121 /// - `promoted` -- map of promoted constants within `body`
122 /// - `universal_regions` -- the universal regions from `body`s function signature
123 /// - `location_table` -- MIR location map of `body`
124 /// - `borrow_set` -- information about borrows occurring in `body`
125 /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
126 /// - `flow_inits` -- results of a maybe-init dataflow analysis
127 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
128 /// - `elements` -- MIR region map
129 pub(crate) fn type_check<'mir, 'tcx>(
130     infcx: &InferCtxt<'_, 'tcx>,
131     param_env: ty::ParamEnv<'tcx>,
132     body: &Body<'tcx>,
133     promoted: &IndexVec<Promoted, Body<'tcx>>,
134     universal_regions: &Rc<UniversalRegions<'tcx>>,
135     location_table: &LocationTable,
136     borrow_set: &BorrowSet<'tcx>,
137     all_facts: &mut Option<AllFacts>,
138     flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
139     move_data: &MoveData<'tcx>,
140     elements: &Rc<RegionValueElements>,
141     upvars: &[Upvar<'tcx>],
142     use_polonius: bool,
143 ) -> MirTypeckResults<'tcx> {
144     let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
145     let mut universe_causes = FxHashMap::default();
146     universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other());
147     let mut constraints = MirTypeckRegionConstraints {
148         placeholder_indices: PlaceholderIndices::default(),
149         placeholder_index_to_region: IndexVec::default(),
150         liveness_constraints: LivenessValues::new(elements.clone()),
151         outlives_constraints: OutlivesConstraintSet::default(),
152         member_constraints: MemberConstraintSet::default(),
153         closure_bounds_mapping: Default::default(),
154         type_tests: Vec::default(),
155         universe_causes,
156     };
157
158     let CreateResult {
159         universal_region_relations,
160         region_bound_pairs,
161         normalized_inputs_and_output,
162     } = free_region_relations::create(
163         infcx,
164         param_env,
165         Some(implicit_region_bound),
166         universal_regions,
167         &mut constraints,
168     );
169
170     for u in ty::UniverseIndex::ROOT..infcx.universe() {
171         let info = UniverseInfo::other();
172         constraints.universe_causes.insert(u, info);
173     }
174
175     let mut borrowck_context = BorrowCheckContext {
176         universal_regions,
177         location_table,
178         borrow_set,
179         all_facts,
180         constraints: &mut constraints,
181         upvars,
182     };
183
184     let opaque_type_values = type_check_internal(
185         infcx,
186         param_env,
187         body,
188         promoted,
189         &region_bound_pairs,
190         implicit_region_bound,
191         &mut borrowck_context,
192         |mut cx| {
193             cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
194             liveness::generate(
195                 &mut cx,
196                 body,
197                 elements,
198                 flow_inits,
199                 move_data,
200                 location_table,
201                 use_polonius,
202             );
203
204             translate_outlives_facts(&mut cx);
205             let opaque_type_values =
206                 infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
207
208             opaque_type_values
209                 .into_iter()
210                 .map(|(opaque_type_key, decl)| {
211                     cx.fully_perform_op(
212                         Locations::All(body.span),
213                         ConstraintCategory::OpaqueType,
214                         CustomTypeOp::new(
215                             |infcx| {
216                                 infcx.register_member_constraints(
217                                     param_env,
218                                     opaque_type_key,
219                                     decl.hidden_type.ty,
220                                     decl.hidden_type.span,
221                                 );
222                                 Ok(InferOk { value: (), obligations: vec![] })
223                             },
224                             || "opaque_type_map".to_string(),
225                         ),
226                     )
227                     .unwrap();
228                     let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
229                     trace!(
230                         "finalized opaque type {:?} to {:#?}",
231                         opaque_type_key,
232                         hidden_type.ty.kind()
233                     );
234                     if hidden_type.has_infer_types_or_consts() {
235                         infcx.tcx.sess.delay_span_bug(
236                             decl.hidden_type.span,
237                             &format!("could not resolve {:#?}", hidden_type.ty.kind()),
238                         );
239                         hidden_type.ty = infcx.tcx.ty_error();
240                     }
241
242                     (opaque_type_key, (hidden_type, decl.origin))
243                 })
244                 .collect()
245         },
246     );
247
248     MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
249 }
250
251 #[instrument(
252     skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra),
253     level = "debug"
254 )]
255 fn type_check_internal<'a, 'tcx, R>(
256     infcx: &'a InferCtxt<'a, 'tcx>,
257     param_env: ty::ParamEnv<'tcx>,
258     body: &'a Body<'tcx>,
259     promoted: &'a IndexVec<Promoted, Body<'tcx>>,
260     region_bound_pairs: &'a RegionBoundPairs<'tcx>,
261     implicit_region_bound: ty::Region<'tcx>,
262     borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
263     extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
264 ) -> R {
265     let mut checker = TypeChecker::new(
266         infcx,
267         body,
268         param_env,
269         region_bound_pairs,
270         implicit_region_bound,
271         borrowck_context,
272     );
273     let errors_reported = {
274         let mut verifier = TypeVerifier::new(&mut checker, promoted);
275         verifier.visit_body(&body);
276         verifier.errors_reported
277     };
278
279     if !errors_reported {
280         // if verifier failed, don't do further checks to avoid ICEs
281         checker.typeck_mir(body);
282     }
283
284     extra(checker)
285 }
286
287 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
288     let cx = &mut typeck.borrowck_context;
289     if let Some(facts) = cx.all_facts {
290         let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
291         let location_table = cx.location_table;
292         facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
293             |constraint: &OutlivesConstraint<'_>| {
294                 if let Some(from_location) = constraint.locations.from_location() {
295                     Either::Left(iter::once((
296                         constraint.sup,
297                         constraint.sub,
298                         location_table.mid_index(from_location),
299                     )))
300                 } else {
301                     Either::Right(
302                         location_table
303                             .all_points()
304                             .map(move |location| (constraint.sup, constraint.sub, location)),
305                     )
306                 }
307             },
308         ));
309     }
310 }
311
312 #[track_caller]
313 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
314     // We sometimes see MIR failures (notably predicate failures) due to
315     // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
316     // to avoid reporting bugs in those cases.
317     tcx.sess.diagnostic().delay_span_bug(span, msg);
318 }
319
320 enum FieldAccessError {
321     OutOfRange { field_count: usize },
322 }
323
324 /// Verifies that MIR types are sane to not crash further checks.
325 ///
326 /// The sanitize_XYZ methods here take an MIR object and compute its
327 /// type, calling `span_mirbug` and returning an error type if there
328 /// is a problem.
329 struct TypeVerifier<'a, 'b, 'tcx> {
330     cx: &'a mut TypeChecker<'b, 'tcx>,
331     promoted: &'b IndexVec<Promoted, Body<'tcx>>,
332     last_span: Span,
333     errors_reported: bool,
334 }
335
336 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
337     fn visit_span(&mut self, span: &Span) {
338         if !span.is_dummy() {
339             self.last_span = *span;
340         }
341     }
342
343     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
344         self.sanitize_place(place, location, context);
345     }
346
347     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
348         self.super_constant(constant, location);
349         let ty = self.sanitize_type(constant, constant.literal.ty());
350
351         self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
352             let live_region_vid =
353                 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
354             self.cx
355                 .borrowck_context
356                 .constraints
357                 .liveness_constraints
358                 .add_element(live_region_vid, location);
359         });
360
361         if let Some(annotation_index) = constant.user_ty {
362             if let Err(terr) = self.cx.relate_type_and_user_type(
363                 constant.literal.ty(),
364                 ty::Variance::Invariant,
365                 &UserTypeProjection { base: annotation_index, projs: vec![] },
366                 location.to_locations(),
367                 ConstraintCategory::Boring,
368             ) {
369                 let annotation = &self.cx.user_type_annotations[annotation_index];
370                 span_mirbug!(
371                     self,
372                     constant,
373                     "bad constant user type {:?} vs {:?}: {:?}",
374                     annotation,
375                     constant.literal.ty(),
376                     terr,
377                 );
378             }
379         } else {
380             let tcx = self.tcx();
381             let maybe_uneval = match constant.literal {
382                 ConstantKind::Ty(ct) => match ct.val() {
383                     ty::ConstKind::Unevaluated(uv) => Some(uv),
384                     _ => None,
385                 },
386                 _ => None,
387             };
388             if let Some(uv) = maybe_uneval {
389                 if let Some(promoted) = uv.promoted {
390                     let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
391                                      promoted: &Body<'tcx>,
392                                      ty,
393                                      san_ty| {
394                         if let Err(terr) = verifier.cx.eq_types(
395                             ty,
396                             san_ty,
397                             location.to_locations(),
398                             ConstraintCategory::Boring,
399                         ) {
400                             span_mirbug!(
401                                 verifier,
402                                 promoted,
403                                 "bad promoted type ({:?}: {:?}): {:?}",
404                                 ty,
405                                 san_ty,
406                                 terr
407                             );
408                         };
409                     };
410
411                     if !self.errors_reported {
412                         let promoted_body = &self.promoted[promoted];
413                         self.sanitize_promoted(promoted_body, location);
414
415                         let promoted_ty = promoted_body.return_ty();
416                         check_err(self, promoted_body, ty, promoted_ty);
417                     }
418                 } else {
419                     if let Err(terr) = self.cx.fully_perform_op(
420                         location.to_locations(),
421                         ConstraintCategory::Boring,
422                         self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
423                             constant.literal.ty(),
424                             uv.def.did,
425                             UserSubsts { substs: uv.substs, user_self_ty: None },
426                         )),
427                     ) {
428                         span_mirbug!(
429                             self,
430                             constant,
431                             "bad constant type {:?} ({:?})",
432                             constant,
433                             terr
434                         );
435                     }
436                 }
437             } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
438                 let unnormalized_ty = tcx.type_of(static_def_id);
439                 let locations = location.to_locations();
440                 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
441                 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
442
443                 if let Err(terr) = self.cx.eq_types(
444                     literal_ty,
445                     normalized_ty,
446                     locations,
447                     ConstraintCategory::Boring,
448                 ) {
449                     span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
450                 }
451             }
452
453             if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
454                 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
455                 self.cx.normalize_and_prove_instantiated_predicates(
456                     def_id,
457                     instantiated_predicates,
458                     location.to_locations(),
459                 );
460             }
461         }
462     }
463
464     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
465         self.super_rvalue(rvalue, location);
466         let rval_ty = rvalue.ty(self.body(), self.tcx());
467         self.sanitize_type(rvalue, rval_ty);
468     }
469
470     fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
471         self.super_local_decl(local, local_decl);
472         self.sanitize_type(local_decl, local_decl.ty);
473
474         if let Some(user_ty) = &local_decl.user_ty {
475             for (user_ty, span) in user_ty.projections_and_spans() {
476                 let ty = if !local_decl.is_nonref_binding() {
477                     // If we have a binding of the form `let ref x: T = ..`
478                     // then remove the outermost reference so we can check the
479                     // type annotation for the remaining type.
480                     if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
481                         *rty
482                     } else {
483                         bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
484                     }
485                 } else {
486                     local_decl.ty
487                 };
488
489                 if let Err(terr) = self.cx.relate_type_and_user_type(
490                     ty,
491                     ty::Variance::Invariant,
492                     user_ty,
493                     Locations::All(*span),
494                     ConstraintCategory::TypeAnnotation,
495                 ) {
496                     span_mirbug!(
497                         self,
498                         local,
499                         "bad user type on variable {:?}: {:?} != {:?} ({:?})",
500                         local,
501                         local_decl.ty,
502                         local_decl.user_ty,
503                         terr,
504                     );
505                 }
506             }
507         }
508     }
509
510     fn visit_body(&mut self, body: &Body<'tcx>) {
511         self.sanitize_type(&"return type", body.return_ty());
512         for local_decl in &body.local_decls {
513             self.sanitize_type(local_decl, local_decl.ty);
514         }
515         if self.errors_reported {
516             return;
517         }
518         self.super_body(body);
519     }
520 }
521
522 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
523     fn new(
524         cx: &'a mut TypeChecker<'b, 'tcx>,
525         promoted: &'b IndexVec<Promoted, Body<'tcx>>,
526     ) -> Self {
527         TypeVerifier { promoted, last_span: cx.body.span, cx, errors_reported: false }
528     }
529
530     fn body(&self) -> &Body<'tcx> {
531         self.cx.body
532     }
533
534     fn tcx(&self) -> TyCtxt<'tcx> {
535         self.cx.infcx.tcx
536     }
537
538     fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
539         if ty.has_escaping_bound_vars() || ty.references_error() {
540             span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
541         } else {
542             ty
543         }
544     }
545
546     /// Checks that the types internal to the `place` match up with
547     /// what would be expected.
548     fn sanitize_place(
549         &mut self,
550         place: &Place<'tcx>,
551         location: Location,
552         context: PlaceContext,
553     ) -> PlaceTy<'tcx> {
554         debug!("sanitize_place: {:?}", place);
555
556         let mut place_ty = PlaceTy::from_ty(self.body().local_decls[place.local].ty);
557
558         for elem in place.projection.iter() {
559             if place_ty.variant_index.is_none() {
560                 if place_ty.ty.references_error() {
561                     assert!(self.errors_reported);
562                     return PlaceTy::from_ty(self.tcx().ty_error());
563                 }
564             }
565             place_ty = self.sanitize_projection(place_ty, elem, place, location);
566         }
567
568         if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
569             let tcx = self.tcx();
570             let trait_ref = ty::TraitRef {
571                 def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
572                 substs: tcx.mk_substs_trait(place_ty.ty, &[]),
573             };
574
575             // To have a `Copy` operand, the type `T` of the
576             // value must be `Copy`. Note that we prove that `T: Copy`,
577             // rather than using the `is_copy_modulo_regions`
578             // test. This is important because
579             // `is_copy_modulo_regions` ignores the resulting region
580             // obligations and assumes they pass. This can result in
581             // bounds from `Copy` impls being unsoundly ignored (e.g.,
582             // #29149). Note that we decide to use `Copy` before knowing
583             // whether the bounds fully apply: in effect, the rule is
584             // that if a value of some type could implement `Copy`, then
585             // it must.
586             self.cx.prove_trait_ref(
587                 trait_ref,
588                 location.to_locations(),
589                 ConstraintCategory::CopyBound,
590             );
591         }
592
593         place_ty
594     }
595
596     fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
597         // Determine the constraints from the promoted MIR by running the type
598         // checker on the promoted MIR, then transfer the constraints back to
599         // the main MIR, changing the locations to the provided location.
600
601         let parent_body = mem::replace(&mut self.cx.body, promoted_body);
602
603         // Use new sets of constraints and closure bounds so that we can
604         // modify their locations.
605         let all_facts = &mut None;
606         let mut constraints = Default::default();
607         let mut closure_bounds = Default::default();
608         let mut liveness_constraints =
609             LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
610         // Don't try to add borrow_region facts for the promoted MIR
611
612         let mut swap_constraints = |this: &mut Self| {
613             mem::swap(this.cx.borrowck_context.all_facts, all_facts);
614             mem::swap(
615                 &mut this.cx.borrowck_context.constraints.outlives_constraints,
616                 &mut constraints,
617             );
618             mem::swap(
619                 &mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
620                 &mut closure_bounds,
621             );
622             mem::swap(
623                 &mut this.cx.borrowck_context.constraints.liveness_constraints,
624                 &mut liveness_constraints,
625             );
626         };
627
628         swap_constraints(self);
629
630         self.visit_body(&promoted_body);
631
632         if !self.errors_reported {
633             // if verifier failed, don't do further checks to avoid ICEs
634             self.cx.typeck_mir(promoted_body);
635         }
636
637         self.cx.body = parent_body;
638         // Merge the outlives constraints back in, at the given location.
639         swap_constraints(self);
640
641         let locations = location.to_locations();
642         for constraint in constraints.outlives().iter() {
643             let mut constraint = constraint.clone();
644             constraint.locations = locations;
645             if let ConstraintCategory::Return(_)
646             | ConstraintCategory::UseAsConst
647             | ConstraintCategory::UseAsStatic = constraint.category
648             {
649                 // "Returning" from a promoted is an assignment to a
650                 // temporary from the user's point of view.
651                 constraint.category = ConstraintCategory::Boring;
652             }
653             self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
654         }
655         for region in liveness_constraints.rows() {
656             // If the region is live at at least one location in the promoted MIR,
657             // then add a liveness constraint to the main MIR for this region
658             // at the location provided as an argument to this method
659             if liveness_constraints.get_elements(region).next().is_some() {
660                 self.cx
661                     .borrowck_context
662                     .constraints
663                     .liveness_constraints
664                     .add_element(region, location);
665             }
666         }
667
668         if !closure_bounds.is_empty() {
669             let combined_bounds_mapping =
670                 closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
671             let existing = self
672                 .cx
673                 .borrowck_context
674                 .constraints
675                 .closure_bounds_mapping
676                 .insert(location, combined_bounds_mapping);
677             assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
678         }
679     }
680
681     fn sanitize_projection(
682         &mut self,
683         base: PlaceTy<'tcx>,
684         pi: PlaceElem<'tcx>,
685         place: &Place<'tcx>,
686         location: Location,
687     ) -> PlaceTy<'tcx> {
688         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
689         let tcx = self.tcx();
690         let base_ty = base.ty;
691         match pi {
692             ProjectionElem::Deref => {
693                 let deref_ty = base_ty.builtin_deref(true);
694                 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
695                     span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
696                 }))
697             }
698             ProjectionElem::Index(i) => {
699                 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
700                 if index_ty != tcx.types.usize {
701                     PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
702                 } else {
703                     PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
704                         span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
705                     }))
706                 }
707             }
708             ProjectionElem::ConstantIndex { .. } => {
709                 // consider verifying in-bounds
710                 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
711                     span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
712                 }))
713             }
714             ProjectionElem::Subslice { from, to, from_end } => {
715                 PlaceTy::from_ty(match base_ty.kind() {
716                     ty::Array(inner, _) => {
717                         assert!(!from_end, "array subslices should not use from_end");
718                         tcx.mk_array(*inner, to - from)
719                     }
720                     ty::Slice(..) => {
721                         assert!(from_end, "slice subslices should use from_end");
722                         base_ty
723                     }
724                     _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
725                 })
726             }
727             ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
728                 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
729                     if index.as_usize() >= adt_def.variants().len() {
730                         PlaceTy::from_ty(span_mirbug_and_err!(
731                             self,
732                             place,
733                             "cast to variant #{:?} but enum only has {:?}",
734                             index,
735                             adt_def.variants().len()
736                         ))
737                     } else {
738                         PlaceTy { ty: base_ty, variant_index: Some(index) }
739                     }
740                 }
741                 // We do not need to handle generators here, because this runs
742                 // before the generator transform stage.
743                 _ => {
744                     let ty = if let Some(name) = maybe_name {
745                         span_mirbug_and_err!(
746                             self,
747                             place,
748                             "can't downcast {:?} as {:?}",
749                             base_ty,
750                             name
751                         )
752                     } else {
753                         span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
754                     };
755                     PlaceTy::from_ty(ty)
756                 }
757             },
758             ProjectionElem::Field(field, fty) => {
759                 let fty = self.sanitize_type(place, fty);
760                 let fty = self.cx.normalize(fty, location);
761                 match self.field_ty(place, base, field, location) {
762                     Ok(ty) => {
763                         let ty = self.cx.normalize(ty, location);
764                         if let Err(terr) = self.cx.eq_types(
765                             ty,
766                             fty,
767                             location.to_locations(),
768                             ConstraintCategory::Boring,
769                         ) {
770                             span_mirbug!(
771                                 self,
772                                 place,
773                                 "bad field access ({:?}: {:?}): {:?}",
774                                 ty,
775                                 fty,
776                                 terr
777                             );
778                         }
779                     }
780                     Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
781                         self,
782                         place,
783                         "accessed field #{} but variant only has {}",
784                         field.index(),
785                         field_count
786                     ),
787                 }
788                 PlaceTy::from_ty(fty)
789             }
790         }
791     }
792
793     fn error(&mut self) -> Ty<'tcx> {
794         self.errors_reported = true;
795         self.tcx().ty_error()
796     }
797
798     fn field_ty(
799         &mut self,
800         parent: &dyn fmt::Debug,
801         base_ty: PlaceTy<'tcx>,
802         field: Field,
803         location: Location,
804     ) -> Result<Ty<'tcx>, FieldAccessError> {
805         let tcx = self.tcx();
806
807         let (variant, substs) = match base_ty {
808             PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
809                 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
810                 ty::Generator(def_id, substs, _) => {
811                     let mut variants = substs.as_generator().state_tys(def_id, tcx);
812                     let Some(mut variant) = variants.nth(variant_index.into()) else {
813                         bug!(
814                             "variant_index of generator out of range: {:?}/{:?}",
815                             variant_index,
816                             substs.as_generator().state_tys(def_id, tcx).count()
817                         );
818                     };
819                     return match variant.nth(field.index()) {
820                         Some(ty) => Ok(ty),
821                         None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
822                     };
823                 }
824                 _ => bug!("can't have downcast of non-adt non-generator type"),
825             },
826             PlaceTy { ty, variant_index: None } => match *ty.kind() {
827                 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
828                     (adt_def.variant(VariantIdx::new(0)), substs)
829                 }
830                 ty::Closure(_, substs) => {
831                     return match substs
832                         .as_closure()
833                         .tupled_upvars_ty()
834                         .tuple_fields()
835                         .get(field.index())
836                     {
837                         Some(&ty) => Ok(ty),
838                         None => Err(FieldAccessError::OutOfRange {
839                             field_count: substs.as_closure().upvar_tys().count(),
840                         }),
841                     };
842                 }
843                 ty::Generator(_, substs, _) => {
844                     // Only prefix fields (upvars and current state) are
845                     // accessible without a variant index.
846                     return match substs.as_generator().prefix_tys().nth(field.index()) {
847                         Some(ty) => Ok(ty),
848                         None => Err(FieldAccessError::OutOfRange {
849                             field_count: substs.as_generator().prefix_tys().count(),
850                         }),
851                     };
852                 }
853                 ty::Tuple(tys) => {
854                     return match tys.get(field.index()) {
855                         Some(&ty) => Ok(ty),
856                         None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
857                     };
858                 }
859                 _ => {
860                     return Ok(span_mirbug_and_err!(
861                         self,
862                         parent,
863                         "can't project out of {:?}",
864                         base_ty
865                     ));
866                 }
867             },
868         };
869
870         if let Some(field) = variant.fields.get(field.index()) {
871             Ok(self.cx.normalize(field.ty(tcx, substs), location))
872         } else {
873             Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
874         }
875     }
876 }
877
878 /// The MIR type checker. Visits the MIR and enforces all the
879 /// constraints needed for it to be valid and well-typed. Along the
880 /// way, it accrues region constraints -- these can later be used by
881 /// NLL region checking.
882 struct TypeChecker<'a, 'tcx> {
883     infcx: &'a InferCtxt<'a, 'tcx>,
884     param_env: ty::ParamEnv<'tcx>,
885     last_span: Span,
886     body: &'a Body<'tcx>,
887     /// User type annotations are shared between the main MIR and the MIR of
888     /// all of the promoted items.
889     user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
890     region_bound_pairs: &'a RegionBoundPairs<'tcx>,
891     implicit_region_bound: ty::Region<'tcx>,
892     reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
893     borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
894 }
895
896 struct BorrowCheckContext<'a, 'tcx> {
897     pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
898     location_table: &'a LocationTable,
899     all_facts: &'a mut Option<AllFacts>,
900     borrow_set: &'a BorrowSet<'tcx>,
901     pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
902     upvars: &'a [Upvar<'tcx>],
903 }
904
905 crate struct MirTypeckResults<'tcx> {
906     crate constraints: MirTypeckRegionConstraints<'tcx>,
907     crate universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
908     crate opaque_type_values: VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
909 }
910
911 /// A collection of region constraints that must be satisfied for the
912 /// program to be considered well-typed.
913 crate struct MirTypeckRegionConstraints<'tcx> {
914     /// Maps from a `ty::Placeholder` to the corresponding
915     /// `PlaceholderIndex` bit that we will use for it.
916     ///
917     /// To keep everything in sync, do not insert this set
918     /// directly. Instead, use the `placeholder_region` helper.
919     crate placeholder_indices: PlaceholderIndices,
920
921     /// Each time we add a placeholder to `placeholder_indices`, we
922     /// also create a corresponding "representative" region vid for
923     /// that wraps it. This vector tracks those. This way, when we
924     /// convert the same `ty::RePlaceholder(p)` twice, we can map to
925     /// the same underlying `RegionVid`.
926     crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
927
928     /// In general, the type-checker is not responsible for enforcing
929     /// liveness constraints; this job falls to the region inferencer,
930     /// which performs a liveness analysis. However, in some limited
931     /// cases, the MIR type-checker creates temporary regions that do
932     /// not otherwise appear in the MIR -- in particular, the
933     /// late-bound regions that it instantiates at call-sites -- and
934     /// hence it must report on their liveness constraints.
935     crate liveness_constraints: LivenessValues<RegionVid>,
936
937     crate outlives_constraints: OutlivesConstraintSet<'tcx>,
938
939     crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
940
941     crate closure_bounds_mapping:
942         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
943
944     crate universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
945
946     crate type_tests: Vec<TypeTest<'tcx>>,
947 }
948
949 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
950     fn placeholder_region(
951         &mut self,
952         infcx: &InferCtxt<'_, 'tcx>,
953         placeholder: ty::PlaceholderRegion,
954     ) -> ty::Region<'tcx> {
955         let placeholder_index = self.placeholder_indices.insert(placeholder);
956         match self.placeholder_index_to_region.get(placeholder_index) {
957             Some(&v) => v,
958             None => {
959                 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
960                 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
961                 self.placeholder_index_to_region.push(region);
962                 region
963             }
964         }
965     }
966 }
967
968 /// The `Locations` type summarizes *where* region constraints are
969 /// required to hold. Normally, this is at a particular point which
970 /// created the obligation, but for constraints that the user gave, we
971 /// want the constraint to hold at all points.
972 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
973 pub enum Locations {
974     /// Indicates that a type constraint should always be true. This
975     /// is particularly important in the new borrowck analysis for
976     /// things like the type of the return slot. Consider this
977     /// example:
978     ///
979     /// ```
980     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
981     ///     let y = 22;
982     ///     return &y; // error
983     /// }
984     /// ```
985     ///
986     /// Here, we wind up with the signature from the return type being
987     /// something like `&'1 u32` where `'1` is a universal region. But
988     /// the type of the return slot `_0` is something like `&'2 u32`
989     /// where `'2` is an existential region variable. The type checker
990     /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
991     /// older NLL analysis, we required this only at the entry point
992     /// to the function. By the nature of the constraints, this wound
993     /// up propagating to all points reachable from start (because
994     /// `'1` -- as a universal region -- is live everywhere). In the
995     /// newer analysis, though, this doesn't work: `_0` is considered
996     /// dead at the start (it has no usable value) and hence this type
997     /// equality is basically a no-op. Then, later on, when we do `_0
998     /// = &'3 y`, that region `'3` never winds up related to the
999     /// universal region `'1` and hence no error occurs. Therefore, we
1000     /// use Locations::All instead, which ensures that the `'1` and
1001     /// `'2` are equal everything. We also use this for other
1002     /// user-given type annotations; e.g., if the user wrote `let mut
1003     /// x: &'static u32 = ...`, we would ensure that all values
1004     /// assigned to `x` are of `'static` lifetime.
1005     ///
1006     /// The span points to the place the constraint arose. For example,
1007     /// it points to the type in a user-given type annotation. If
1008     /// there's no sensible span then it's DUMMY_SP.
1009     All(Span),
1010
1011     /// An outlives constraint that only has to hold at a single location,
1012     /// usually it represents a point where references flow from one spot to
1013     /// another (e.g., `x = y`)
1014     Single(Location),
1015 }
1016
1017 impl Locations {
1018     pub fn from_location(&self) -> Option<Location> {
1019         match self {
1020             Locations::All(_) => None,
1021             Locations::Single(from_location) => Some(*from_location),
1022         }
1023     }
1024
1025     /// Gets a span representing the location.
1026     pub fn span(&self, body: &Body<'_>) -> Span {
1027         match self {
1028             Locations::All(span) => *span,
1029             Locations::Single(l) => body.source_info(*l).span,
1030         }
1031     }
1032 }
1033
1034 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1035     fn new(
1036         infcx: &'a InferCtxt<'a, 'tcx>,
1037         body: &'a Body<'tcx>,
1038         param_env: ty::ParamEnv<'tcx>,
1039         region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1040         implicit_region_bound: ty::Region<'tcx>,
1041         borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1042     ) -> Self {
1043         let mut checker = Self {
1044             infcx,
1045             last_span: DUMMY_SP,
1046             body,
1047             user_type_annotations: &body.user_type_annotations,
1048             param_env,
1049             region_bound_pairs,
1050             implicit_region_bound,
1051             borrowck_context,
1052             reported_errors: Default::default(),
1053         };
1054         checker.check_user_type_annotations();
1055         checker
1056     }
1057
1058     fn body(&self) -> &Body<'tcx> {
1059         self.body
1060     }
1061
1062     fn unsized_feature_enabled(&self) -> bool {
1063         let features = self.tcx().features();
1064         features.unsized_locals || features.unsized_fn_params
1065     }
1066
1067     /// Equate the inferred type and the annotated type for user type annotations
1068     #[instrument(skip(self), level = "debug")]
1069     fn check_user_type_annotations(&mut self) {
1070         debug!(?self.user_type_annotations);
1071         for user_annotation in self.user_type_annotations {
1072             let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1073             let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1074             let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1075             match annotation {
1076                 UserType::Ty(mut ty) => {
1077                     ty = self.normalize(ty, Locations::All(span));
1078
1079                     if let Err(terr) = self.eq_types(
1080                         ty,
1081                         inferred_ty,
1082                         Locations::All(span),
1083                         ConstraintCategory::BoringNoLocation,
1084                     ) {
1085                         span_mirbug!(
1086                             self,
1087                             user_annotation,
1088                             "bad user type ({:?} = {:?}): {:?}",
1089                             ty,
1090                             inferred_ty,
1091                             terr
1092                         );
1093                     }
1094
1095                     self.prove_predicate(
1096                         ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into()))
1097                             .to_predicate(self.tcx()),
1098                         Locations::All(span),
1099                         ConstraintCategory::TypeAnnotation,
1100                     );
1101                 }
1102                 UserType::TypeOf(def_id, user_substs) => {
1103                     if let Err(terr) = self.fully_perform_op(
1104                         Locations::All(span),
1105                         ConstraintCategory::BoringNoLocation,
1106                         self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1107                             inferred_ty,
1108                             def_id,
1109                             user_substs,
1110                         )),
1111                     ) {
1112                         span_mirbug!(
1113                             self,
1114                             user_annotation,
1115                             "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1116                             inferred_ty,
1117                             def_id,
1118                             user_substs,
1119                             self.tcx().type_of(def_id),
1120                             terr,
1121                         );
1122                     }
1123                 }
1124             }
1125         }
1126     }
1127
1128     #[instrument(skip(self, data), level = "debug")]
1129     fn push_region_constraints(
1130         &mut self,
1131         locations: Locations,
1132         category: ConstraintCategory,
1133         data: &QueryRegionConstraints<'tcx>,
1134     ) {
1135         debug!("constraints generated: {:#?}", data);
1136
1137         constraint_conversion::ConstraintConversion::new(
1138             self.infcx,
1139             self.borrowck_context.universal_regions,
1140             self.region_bound_pairs,
1141             Some(self.implicit_region_bound),
1142             self.param_env,
1143             locations,
1144             category,
1145             &mut self.borrowck_context.constraints,
1146         )
1147         .convert_all(data);
1148     }
1149
1150     /// Try to relate `sub <: sup`
1151     fn sub_types(
1152         &mut self,
1153         sub: Ty<'tcx>,
1154         sup: Ty<'tcx>,
1155         locations: Locations,
1156         category: ConstraintCategory,
1157     ) -> Fallible<()> {
1158         // Use this order of parameters because the sup type is usually the
1159         // "expected" type in diagnostics.
1160         self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1161     }
1162
1163     #[instrument(skip(self, category), level = "debug")]
1164     fn eq_types(
1165         &mut self,
1166         expected: Ty<'tcx>,
1167         found: Ty<'tcx>,
1168         locations: Locations,
1169         category: ConstraintCategory,
1170     ) -> Fallible<()> {
1171         self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1172     }
1173
1174     #[instrument(skip(self), level = "debug")]
1175     fn relate_type_and_user_type(
1176         &mut self,
1177         a: Ty<'tcx>,
1178         v: ty::Variance,
1179         user_ty: &UserTypeProjection,
1180         locations: Locations,
1181         category: ConstraintCategory,
1182     ) -> Fallible<()> {
1183         let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1184         let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1185
1186         let tcx = self.infcx.tcx;
1187
1188         for proj in &user_ty.projs {
1189             let projected_ty = curr_projected_ty.projection_ty_core(
1190                 tcx,
1191                 self.param_env,
1192                 proj,
1193                 |this, field, ()| {
1194                     let ty = this.field_ty(tcx, field);
1195                     self.normalize(ty, locations)
1196                 },
1197             );
1198             curr_projected_ty = projected_ty;
1199         }
1200         debug!(
1201             "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1202             user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
1203         );
1204
1205         let ty = curr_projected_ty.ty;
1206         self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1207
1208         Ok(())
1209     }
1210
1211     fn tcx(&self) -> TyCtxt<'tcx> {
1212         self.infcx.tcx
1213     }
1214
1215     #[instrument(skip(self, body, location), level = "debug")]
1216     fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1217         let tcx = self.tcx();
1218         match stmt.kind {
1219             StatementKind::Assign(box (ref place, ref rv)) => {
1220                 // Assignments to temporaries are not "interesting";
1221                 // they are not caused by the user, but rather artifacts
1222                 // of lowering. Assignments to other sorts of places *are* interesting
1223                 // though.
1224                 let category = match place.as_local() {
1225                     Some(RETURN_PLACE) => {
1226                         let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1227                         if defining_ty.is_const() {
1228                             if tcx.is_static(defining_ty.def_id()) {
1229                                 ConstraintCategory::UseAsStatic
1230                             } else {
1231                                 ConstraintCategory::UseAsConst
1232                             }
1233                         } else {
1234                             ConstraintCategory::Return(ReturnConstraint::Normal)
1235                         }
1236                     }
1237                     Some(l)
1238                         if matches!(
1239                             body.local_decls[l].local_info,
1240                             Some(box LocalInfo::AggregateTemp)
1241                         ) =>
1242                     {
1243                         ConstraintCategory::Usage
1244                     }
1245                     Some(l) if !body.local_decls[l].is_user_variable() => {
1246                         ConstraintCategory::Boring
1247                     }
1248                     _ => ConstraintCategory::Assignment,
1249                 };
1250                 debug!(
1251                     "assignment category: {:?} {:?}",
1252                     category,
1253                     place.as_local().map(|l| &body.local_decls[l])
1254                 );
1255
1256                 let place_ty = place.ty(body, tcx).ty;
1257                 let place_ty = self.normalize(place_ty, location);
1258                 let rv_ty = rv.ty(body, tcx);
1259                 let rv_ty = self.normalize(rv_ty, location);
1260                 if let Err(terr) =
1261                     self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1262                 {
1263                     span_mirbug!(
1264                         self,
1265                         stmt,
1266                         "bad assignment ({:?} = {:?}): {:?}",
1267                         place_ty,
1268                         rv_ty,
1269                         terr
1270                     );
1271                 }
1272
1273                 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1274                     if let Err(terr) = self.relate_type_and_user_type(
1275                         rv_ty,
1276                         ty::Variance::Invariant,
1277                         &UserTypeProjection { base: annotation_index, projs: vec![] },
1278                         location.to_locations(),
1279                         ConstraintCategory::Boring,
1280                     ) {
1281                         let annotation = &self.user_type_annotations[annotation_index];
1282                         span_mirbug!(
1283                             self,
1284                             stmt,
1285                             "bad user type on rvalue ({:?} = {:?}): {:?}",
1286                             annotation,
1287                             rv_ty,
1288                             terr
1289                         );
1290                     }
1291                 }
1292
1293                 self.check_rvalue(body, rv, location);
1294                 if !self.unsized_feature_enabled() {
1295                     let trait_ref = ty::TraitRef {
1296                         def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1297                         substs: tcx.mk_substs_trait(place_ty, &[]),
1298                     };
1299                     self.prove_trait_ref(
1300                         trait_ref,
1301                         location.to_locations(),
1302                         ConstraintCategory::SizedBound,
1303                     );
1304                 }
1305             }
1306             StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
1307                 let place_ty = place.ty(body, tcx).ty;
1308                 if let Err(terr) = self.relate_type_and_user_type(
1309                     place_ty,
1310                     variance,
1311                     projection,
1312                     Locations::All(stmt.source_info.span),
1313                     ConstraintCategory::TypeAnnotation,
1314                 ) {
1315                     let annotation = &self.user_type_annotations[projection.base];
1316                     span_mirbug!(
1317                         self,
1318                         stmt,
1319                         "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1320                         place_ty,
1321                         annotation,
1322                         projection.projs,
1323                         terr
1324                     );
1325                 }
1326             }
1327             StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
1328                 ..
1329             }) => span_bug!(
1330                 stmt.source_info.span,
1331                 "Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
1332             ),
1333             StatementKind::FakeRead(..)
1334             | StatementKind::StorageLive(..)
1335             | StatementKind::StorageDead(..)
1336             | StatementKind::Retag { .. }
1337             | StatementKind::Coverage(..)
1338             | StatementKind::Nop => {}
1339             StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1340                 bug!("Statement not allowed in this MIR phase")
1341             }
1342         }
1343     }
1344
1345     #[instrument(skip(self, body, term_location), level = "debug")]
1346     fn check_terminator(
1347         &mut self,
1348         body: &Body<'tcx>,
1349         term: &Terminator<'tcx>,
1350         term_location: Location,
1351     ) {
1352         let tcx = self.tcx();
1353         match term.kind {
1354             TerminatorKind::Goto { .. }
1355             | TerminatorKind::Resume
1356             | TerminatorKind::Abort
1357             | TerminatorKind::Return
1358             | TerminatorKind::GeneratorDrop
1359             | TerminatorKind::Unreachable
1360             | TerminatorKind::Drop { .. }
1361             | TerminatorKind::FalseEdge { .. }
1362             | TerminatorKind::FalseUnwind { .. }
1363             | TerminatorKind::InlineAsm { .. } => {
1364                 // no checks needed for these
1365             }
1366
1367             TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
1368                 let place_ty = place.ty(body, tcx).ty;
1369                 let rv_ty = value.ty(body, tcx);
1370
1371                 let locations = term_location.to_locations();
1372                 if let Err(terr) =
1373                     self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1374                 {
1375                     span_mirbug!(
1376                         self,
1377                         term,
1378                         "bad DropAndReplace ({:?} = {:?}): {:?}",
1379                         place_ty,
1380                         rv_ty,
1381                         terr
1382                     );
1383                 }
1384             }
1385             TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
1386                 self.check_operand(discr, term_location);
1387
1388                 let discr_ty = discr.ty(body, tcx);
1389                 if let Err(terr) = self.sub_types(
1390                     discr_ty,
1391                     switch_ty,
1392                     term_location.to_locations(),
1393                     ConstraintCategory::Assignment,
1394                 ) {
1395                     span_mirbug!(
1396                         self,
1397                         term,
1398                         "bad SwitchInt ({:?} on {:?}): {:?}",
1399                         switch_ty,
1400                         discr_ty,
1401                         terr
1402                     );
1403                 }
1404                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1405                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1406                 }
1407                 // FIXME: check the values
1408             }
1409             TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
1410                 self.check_operand(func, term_location);
1411                 for arg in args {
1412                     self.check_operand(arg, term_location);
1413                 }
1414
1415                 let func_ty = func.ty(body, tcx);
1416                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1417                 let sig = match func_ty.kind() {
1418                     ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1419                     _ => {
1420                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1421                         return;
1422                     }
1423                 };
1424                 let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
1425                     term.source_info.span,
1426                     LateBoundRegionConversionTime::FnCall,
1427                     sig,
1428                 );
1429                 let sig = self.normalize(sig, term_location);
1430                 self.check_call_dest(body, term, &sig, destination, term_location);
1431
1432                 self.prove_predicates(
1433                     sig.inputs_and_output
1434                         .iter()
1435                         .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1436                     term_location.to_locations(),
1437                     ConstraintCategory::Boring,
1438                 );
1439
1440                 // The ordinary liveness rules will ensure that all
1441                 // regions in the type of the callee are live here. We
1442                 // then further constrain the late-bound regions that
1443                 // were instantiated at the call site to be live as
1444                 // well. The resulting is that all the input (and
1445                 // output) types in the signature must be live, since
1446                 // all the inputs that fed into it were live.
1447                 for &late_bound_region in map.values() {
1448                     let region_vid =
1449                         self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1450                     self.borrowck_context
1451                         .constraints
1452                         .liveness_constraints
1453                         .add_element(region_vid, term_location);
1454                 }
1455
1456                 self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
1457             }
1458             TerminatorKind::Assert { ref cond, ref msg, .. } => {
1459                 self.check_operand(cond, term_location);
1460
1461                 let cond_ty = cond.ty(body, tcx);
1462                 if cond_ty != tcx.types.bool {
1463                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1464                 }
1465
1466                 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
1467                     if len.ty(body, tcx) != tcx.types.usize {
1468                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1469                     }
1470                     if index.ty(body, tcx) != tcx.types.usize {
1471                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1472                     }
1473                 }
1474             }
1475             TerminatorKind::Yield { ref value, .. } => {
1476                 self.check_operand(value, term_location);
1477
1478                 let value_ty = value.ty(body, tcx);
1479                 match body.yield_ty() {
1480                     None => span_mirbug!(self, term, "yield in non-generator"),
1481                     Some(ty) => {
1482                         if let Err(terr) = self.sub_types(
1483                             value_ty,
1484                             ty,
1485                             term_location.to_locations(),
1486                             ConstraintCategory::Yield,
1487                         ) {
1488                             span_mirbug!(
1489                                 self,
1490                                 term,
1491                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1492                                 value_ty,
1493                                 ty,
1494                                 terr
1495                             );
1496                         }
1497                     }
1498                 }
1499             }
1500         }
1501     }
1502
1503     fn check_call_dest(
1504         &mut self,
1505         body: &Body<'tcx>,
1506         term: &Terminator<'tcx>,
1507         sig: &ty::FnSig<'tcx>,
1508         destination: &Option<(Place<'tcx>, BasicBlock)>,
1509         term_location: Location,
1510     ) {
1511         let tcx = self.tcx();
1512         match *destination {
1513             Some((ref dest, _target_block)) => {
1514                 let dest_ty = dest.ty(body, tcx).ty;
1515                 let dest_ty = self.normalize(dest_ty, term_location);
1516                 let category = match dest.as_local() {
1517                     Some(RETURN_PLACE) => {
1518                         if let BorrowCheckContext {
1519                             universal_regions:
1520                                 UniversalRegions {
1521                                     defining_ty:
1522                                         DefiningTy::Const(def_id, _)
1523                                         | DefiningTy::InlineConst(def_id, _),
1524                                     ..
1525                                 },
1526                             ..
1527                         } = self.borrowck_context
1528                         {
1529                             if tcx.is_static(*def_id) {
1530                                 ConstraintCategory::UseAsStatic
1531                             } else {
1532                                 ConstraintCategory::UseAsConst
1533                             }
1534                         } else {
1535                             ConstraintCategory::Return(ReturnConstraint::Normal)
1536                         }
1537                     }
1538                     Some(l) if !body.local_decls[l].is_user_variable() => {
1539                         ConstraintCategory::Boring
1540                     }
1541                     _ => ConstraintCategory::Assignment,
1542                 };
1543
1544                 let locations = term_location.to_locations();
1545
1546                 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1547                     span_mirbug!(
1548                         self,
1549                         term,
1550                         "call dest mismatch ({:?} <- {:?}): {:?}",
1551                         dest_ty,
1552                         sig.output(),
1553                         terr
1554                     );
1555                 }
1556
1557                 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1558                 // this check is done at `check_local`.
1559                 if self.unsized_feature_enabled() {
1560                     let span = term.source_info.span;
1561                     self.ensure_place_sized(dest_ty, span);
1562                 }
1563             }
1564             None => {
1565                 if !self
1566                     .tcx()
1567                     .conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
1568                 {
1569                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1570                 }
1571             }
1572         }
1573     }
1574
1575     fn check_call_inputs(
1576         &mut self,
1577         body: &Body<'tcx>,
1578         term: &Terminator<'tcx>,
1579         sig: &ty::FnSig<'tcx>,
1580         args: &[Operand<'tcx>],
1581         term_location: Location,
1582         from_hir_call: bool,
1583     ) {
1584         debug!("check_call_inputs({:?}, {:?})", sig, args);
1585         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1586             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1587         }
1588         for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1589             let op_arg_ty = op_arg.ty(body, self.tcx());
1590             let op_arg_ty = self.normalize(op_arg_ty, term_location);
1591             let category = if from_hir_call {
1592                 ConstraintCategory::CallArgument
1593             } else {
1594                 ConstraintCategory::Boring
1595             };
1596             if let Err(terr) =
1597                 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1598             {
1599                 span_mirbug!(
1600                     self,
1601                     term,
1602                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1603                     n,
1604                     fn_arg,
1605                     op_arg_ty,
1606                     terr
1607                 );
1608             }
1609         }
1610     }
1611
1612     fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1613         let is_cleanup = block_data.is_cleanup;
1614         self.last_span = block_data.terminator().source_info.span;
1615         match block_data.terminator().kind {
1616             TerminatorKind::Goto { target } => {
1617                 self.assert_iscleanup(body, block_data, target, is_cleanup)
1618             }
1619             TerminatorKind::SwitchInt { ref targets, .. } => {
1620                 for target in targets.all_targets() {
1621                     self.assert_iscleanup(body, block_data, *target, is_cleanup);
1622                 }
1623             }
1624             TerminatorKind::Resume => {
1625                 if !is_cleanup {
1626                     span_mirbug!(self, block_data, "resume on non-cleanup block!")
1627                 }
1628             }
1629             TerminatorKind::Abort => {
1630                 if !is_cleanup {
1631                     span_mirbug!(self, block_data, "abort on non-cleanup block!")
1632                 }
1633             }
1634             TerminatorKind::Return => {
1635                 if is_cleanup {
1636                     span_mirbug!(self, block_data, "return on cleanup block")
1637                 }
1638             }
1639             TerminatorKind::GeneratorDrop { .. } => {
1640                 if is_cleanup {
1641                     span_mirbug!(self, block_data, "generator_drop in cleanup block")
1642                 }
1643             }
1644             TerminatorKind::Yield { resume, drop, .. } => {
1645                 if is_cleanup {
1646                     span_mirbug!(self, block_data, "yield in cleanup block")
1647                 }
1648                 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1649                 if let Some(drop) = drop {
1650                     self.assert_iscleanup(body, block_data, drop, is_cleanup);
1651                 }
1652             }
1653             TerminatorKind::Unreachable => {}
1654             TerminatorKind::Drop { target, unwind, .. }
1655             | TerminatorKind::DropAndReplace { target, unwind, .. }
1656             | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1657                 self.assert_iscleanup(body, block_data, target, is_cleanup);
1658                 if let Some(unwind) = unwind {
1659                     if is_cleanup {
1660                         span_mirbug!(self, block_data, "unwind on cleanup block")
1661                     }
1662                     self.assert_iscleanup(body, block_data, unwind, true);
1663                 }
1664             }
1665             TerminatorKind::Call { ref destination, cleanup, .. } => {
1666                 if let &Some((_, target)) = destination {
1667                     self.assert_iscleanup(body, block_data, target, is_cleanup);
1668                 }
1669                 if let Some(cleanup) = cleanup {
1670                     if is_cleanup {
1671                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1672                     }
1673                     self.assert_iscleanup(body, block_data, cleanup, true);
1674                 }
1675             }
1676             TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1677                 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1678                 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1679             }
1680             TerminatorKind::FalseUnwind { real_target, unwind } => {
1681                 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1682                 if let Some(unwind) = unwind {
1683                     if is_cleanup {
1684                         span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1685                     }
1686                     self.assert_iscleanup(body, block_data, unwind, true);
1687                 }
1688             }
1689             TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1690                 if let Some(target) = destination {
1691                     self.assert_iscleanup(body, block_data, target, is_cleanup);
1692                 }
1693                 if let Some(cleanup) = cleanup {
1694                     if is_cleanup {
1695                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1696                     }
1697                     self.assert_iscleanup(body, block_data, cleanup, true);
1698                 }
1699             }
1700         }
1701     }
1702
1703     fn assert_iscleanup(
1704         &mut self,
1705         body: &Body<'tcx>,
1706         ctxt: &dyn fmt::Debug,
1707         bb: BasicBlock,
1708         iscleanuppad: bool,
1709     ) {
1710         if body[bb].is_cleanup != iscleanuppad {
1711             span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1712         }
1713     }
1714
1715     fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1716         match body.local_kind(local) {
1717             LocalKind::ReturnPointer | LocalKind::Arg => {
1718                 // return values of normal functions are required to be
1719                 // sized by typeck, but return values of ADT constructors are
1720                 // not because we don't include a `Self: Sized` bounds on them.
1721                 //
1722                 // Unbound parts of arguments were never required to be Sized
1723                 // - maybe we should make that a warning.
1724                 return;
1725             }
1726             LocalKind::Var | LocalKind::Temp => {}
1727         }
1728
1729         // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1730         // and nullary ops are checked in `check_call_dest`.
1731         if !self.unsized_feature_enabled() {
1732             let span = local_decl.source_info.span;
1733             let ty = local_decl.ty;
1734             self.ensure_place_sized(ty, span);
1735         }
1736     }
1737
1738     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1739         let tcx = self.tcx();
1740
1741         // Erase the regions from `ty` to get a global type.  The
1742         // `Sized` bound in no way depends on precise regions, so this
1743         // shouldn't affect `is_sized`.
1744         let erased_ty = tcx.erase_regions(ty);
1745         if !erased_ty.is_sized(tcx.at(span), self.param_env) {
1746             // in current MIR construction, all non-control-flow rvalue
1747             // expressions evaluate through `as_temp` or `into` a return
1748             // slot or local, so to find all unsized rvalues it is enough
1749             // to check all temps, return slots and locals.
1750             if self.reported_errors.replace((ty, span)).is_none() {
1751                 let mut diag = struct_span_err!(
1752                     self.tcx().sess,
1753                     span,
1754                     E0161,
1755                     "cannot move a value of type {0}: the size of {0} \
1756                      cannot be statically determined",
1757                     ty
1758                 );
1759
1760                 // While this is located in `nll::typeck` this error is not
1761                 // an NLL error, it's a required check to prevent creation
1762                 // of unsized rvalues in a call expression.
1763                 diag.emit();
1764             }
1765         }
1766     }
1767
1768     fn aggregate_field_ty(
1769         &mut self,
1770         ak: &AggregateKind<'tcx>,
1771         field_index: usize,
1772         location: Location,
1773     ) -> Result<Ty<'tcx>, FieldAccessError> {
1774         let tcx = self.tcx();
1775
1776         match *ak {
1777             AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1778                 let def = tcx.adt_def(adt_did);
1779                 let variant = &def.variant(variant_index);
1780                 let adj_field_index = active_field_index.unwrap_or(field_index);
1781                 if let Some(field) = variant.fields.get(adj_field_index) {
1782                     Ok(self.normalize(field.ty(tcx, substs), location))
1783                 } else {
1784                     Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1785                 }
1786             }
1787             AggregateKind::Closure(_, substs) => {
1788                 match substs.as_closure().upvar_tys().nth(field_index) {
1789                     Some(ty) => Ok(ty),
1790                     None => Err(FieldAccessError::OutOfRange {
1791                         field_count: substs.as_closure().upvar_tys().count(),
1792                     }),
1793                 }
1794             }
1795             AggregateKind::Generator(_, substs, _) => {
1796                 // It doesn't make sense to look at a field beyond the prefix;
1797                 // these require a variant index, and are not initialized in
1798                 // aggregate rvalues.
1799                 match substs.as_generator().prefix_tys().nth(field_index) {
1800                     Some(ty) => Ok(ty),
1801                     None => Err(FieldAccessError::OutOfRange {
1802                         field_count: substs.as_generator().prefix_tys().count(),
1803                     }),
1804                 }
1805             }
1806             AggregateKind::Array(ty) => Ok(ty),
1807             AggregateKind::Tuple => {
1808                 unreachable!("This should have been covered in check_rvalues");
1809             }
1810         }
1811     }
1812
1813     fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1814         if let Operand::Constant(constant) = op {
1815             let maybe_uneval = match constant.literal {
1816                 ConstantKind::Ty(ct) => match ct.val() {
1817                     ty::ConstKind::Unevaluated(uv) => Some(uv),
1818                     _ => None,
1819                 },
1820                 _ => None,
1821             };
1822             if let Some(uv) = maybe_uneval {
1823                 if uv.promoted.is_none() {
1824                     let tcx = self.tcx();
1825                     let def_id = uv.def.def_id_for_type_of();
1826                     if tcx.def_kind(def_id) == DefKind::InlineConst {
1827                         let predicates = self.prove_closure_bounds(
1828                             tcx,
1829                             def_id.expect_local(),
1830                             uv.substs,
1831                             location,
1832                         );
1833                         self.normalize_and_prove_instantiated_predicates(
1834                             def_id,
1835                             predicates,
1836                             location.to_locations(),
1837                         );
1838                     }
1839                 }
1840             }
1841         }
1842     }
1843
1844     fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1845         let tcx = self.tcx();
1846
1847         match rvalue {
1848             Rvalue::Aggregate(ak, ops) => {
1849                 for op in ops {
1850                     self.check_operand(op, location);
1851                 }
1852                 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1853             }
1854
1855             Rvalue::Repeat(operand, len) => {
1856                 self.check_operand(operand, location);
1857
1858                 // If the length cannot be evaluated we must assume that the length can be larger
1859                 // than 1.
1860                 // If the length is larger than 1, the repeat expression will need to copy the
1861                 // element, so we require the `Copy` trait.
1862                 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1863                     match operand {
1864                         Operand::Copy(..) | Operand::Constant(..) => {
1865                             // These are always okay: direct use of a const, or a value that can evidently be copied.
1866                         }
1867                         Operand::Move(place) => {
1868                             // Make sure that repeated elements implement `Copy`.
1869                             let span = body.source_info(location).span;
1870                             let ty = operand.ty(body, tcx);
1871                             if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
1872                                 let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
1873                                 let is_const_fn =
1874                                     is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
1875
1876                                 debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
1877
1878                                 let def_id = body.source.def_id().expect_local();
1879                                 let obligation = traits::Obligation::new(
1880                                     ObligationCause::new(
1881                                         span,
1882                                         self.tcx().hir().local_def_id_to_hir_id(def_id),
1883                                         traits::ObligationCauseCode::RepeatElementCopy {
1884                                             is_const_fn,
1885                                         },
1886                                     ),
1887                                     self.param_env,
1888                                     ty::Binder::dummy(ty::TraitRef::new(
1889                                         self.tcx().require_lang_item(
1890                                             LangItem::Copy,
1891                                             Some(self.last_span),
1892                                         ),
1893                                         tcx.mk_substs_trait(ty, &[]),
1894                                     ))
1895                                     .without_const()
1896                                     .to_predicate(self.tcx()),
1897                                 );
1898                                 self.infcx.report_selection_error(
1899                                     obligation.clone(),
1900                                     &obligation,
1901                                     &traits::SelectionError::Unimplemented,
1902                                     false,
1903                                 );
1904                             }
1905                         }
1906                     }
1907                 }
1908             }
1909
1910             &Rvalue::NullaryOp(_, ty) => {
1911                 let trait_ref = ty::TraitRef {
1912                     def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1913                     substs: tcx.mk_substs_trait(ty, &[]),
1914                 };
1915
1916                 self.prove_trait_ref(
1917                     trait_ref,
1918                     location.to_locations(),
1919                     ConstraintCategory::SizedBound,
1920                 );
1921             }
1922
1923             Rvalue::ShallowInitBox(operand, ty) => {
1924                 self.check_operand(operand, location);
1925
1926                 let trait_ref = ty::TraitRef {
1927                     def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
1928                     substs: tcx.mk_substs_trait(*ty, &[]),
1929                 };
1930
1931                 self.prove_trait_ref(
1932                     trait_ref,
1933                     location.to_locations(),
1934                     ConstraintCategory::SizedBound,
1935                 );
1936             }
1937
1938             Rvalue::Cast(cast_kind, op, ty) => {
1939                 self.check_operand(op, location);
1940
1941                 match cast_kind {
1942                     CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1943                         let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1944
1945                         // The type that we see in the fcx is like
1946                         // `foo::<'a, 'b>`, where `foo` is the path to a
1947                         // function definition. When we extract the
1948                         // signature, it comes from the `fn_sig` query,
1949                         // and hence may contain unnormalized results.
1950                         let fn_sig = self.normalize(fn_sig, location);
1951
1952                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1953
1954                         if let Err(terr) = self.eq_types(
1955                             *ty,
1956                             ty_fn_ptr_from,
1957                             location.to_locations(),
1958                             ConstraintCategory::Cast,
1959                         ) {
1960                             span_mirbug!(
1961                                 self,
1962                                 rvalue,
1963                                 "equating {:?} with {:?} yields {:?}",
1964                                 ty_fn_ptr_from,
1965                                 ty,
1966                                 terr
1967                             );
1968                         }
1969                     }
1970
1971                     CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1972                         let sig = match op.ty(body, tcx).kind() {
1973                             ty::Closure(_, substs) => substs.as_closure().sig(),
1974                             _ => bug!(),
1975                         };
1976                         let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1977
1978                         if let Err(terr) = self.eq_types(
1979                             *ty,
1980                             ty_fn_ptr_from,
1981                             location.to_locations(),
1982                             ConstraintCategory::Cast,
1983                         ) {
1984                             span_mirbug!(
1985                                 self,
1986                                 rvalue,
1987                                 "equating {:?} with {:?} yields {:?}",
1988                                 ty_fn_ptr_from,
1989                                 ty,
1990                                 terr
1991                             );
1992                         }
1993                     }
1994
1995                     CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1996                         let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1997
1998                         // The type that we see in the fcx is like
1999                         // `foo::<'a, 'b>`, where `foo` is the path to a
2000                         // function definition. When we extract the
2001                         // signature, it comes from the `fn_sig` query,
2002                         // and hence may contain unnormalized results.
2003                         let fn_sig = self.normalize(fn_sig, location);
2004
2005                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
2006
2007                         if let Err(terr) = self.eq_types(
2008                             *ty,
2009                             ty_fn_ptr_from,
2010                             location.to_locations(),
2011                             ConstraintCategory::Cast,
2012                         ) {
2013                             span_mirbug!(
2014                                 self,
2015                                 rvalue,
2016                                 "equating {:?} with {:?} yields {:?}",
2017                                 ty_fn_ptr_from,
2018                                 ty,
2019                                 terr
2020                             );
2021                         }
2022                     }
2023
2024                     CastKind::Pointer(PointerCast::Unsize) => {
2025                         let &ty = ty;
2026                         let trait_ref = ty::TraitRef {
2027                             def_id: tcx
2028                                 .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
2029                             substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
2030                         };
2031
2032                         self.prove_trait_ref(
2033                             trait_ref,
2034                             location.to_locations(),
2035                             ConstraintCategory::Cast,
2036                         );
2037                     }
2038
2039                     CastKind::Pointer(PointerCast::MutToConstPointer) => {
2040                         let ty::RawPtr(ty::TypeAndMut {
2041                             ty: ty_from,
2042                             mutbl: hir::Mutability::Mut,
2043                         }) = op.ty(body, tcx).kind() else {
2044                             span_mirbug!(
2045                                 self,
2046                                 rvalue,
2047                                 "unexpected base type for cast {:?}",
2048                                 ty,
2049                             );
2050                             return;
2051                         };
2052                         let ty::RawPtr(ty::TypeAndMut {
2053                             ty: ty_to,
2054                             mutbl: hir::Mutability::Not,
2055                         }) = ty.kind() else {
2056                             span_mirbug!(
2057                                 self,
2058                                 rvalue,
2059                                 "unexpected target type for cast {:?}",
2060                                 ty,
2061                             );
2062                             return;
2063                         };
2064                         if let Err(terr) = self.sub_types(
2065                             *ty_from,
2066                             *ty_to,
2067                             location.to_locations(),
2068                             ConstraintCategory::Cast,
2069                         ) {
2070                             span_mirbug!(
2071                                 self,
2072                                 rvalue,
2073                                 "relating {:?} with {:?} yields {:?}",
2074                                 ty_from,
2075                                 ty_to,
2076                                 terr
2077                             );
2078                         }
2079                     }
2080
2081                     CastKind::Pointer(PointerCast::ArrayToPointer) => {
2082                         let ty_from = op.ty(body, tcx);
2083
2084                         let opt_ty_elem_mut = match ty_from.kind() {
2085                             ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2086                                 match array_ty.kind() {
2087                                     ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2088                                     _ => None,
2089                                 }
2090                             }
2091                             _ => None,
2092                         };
2093
2094                         let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2095                             span_mirbug!(
2096                                 self,
2097                                 rvalue,
2098                                 "ArrayToPointer cast from unexpected type {:?}",
2099                                 ty_from,
2100                             );
2101                             return;
2102                         };
2103
2104                         let (ty_to, ty_to_mut) = match ty.kind() {
2105                             ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2106                                 (ty_to, *ty_to_mut)
2107                             }
2108                             _ => {
2109                                 span_mirbug!(
2110                                     self,
2111                                     rvalue,
2112                                     "ArrayToPointer cast to unexpected type {:?}",
2113                                     ty,
2114                                 );
2115                                 return;
2116                             }
2117                         };
2118
2119                         if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2120                             span_mirbug!(
2121                                 self,
2122                                 rvalue,
2123                                 "ArrayToPointer cast from const {:?} to mut {:?}",
2124                                 ty,
2125                                 ty_to
2126                             );
2127                             return;
2128                         }
2129
2130                         if let Err(terr) = self.sub_types(
2131                             *ty_elem,
2132                             *ty_to,
2133                             location.to_locations(),
2134                             ConstraintCategory::Cast,
2135                         ) {
2136                             span_mirbug!(
2137                                 self,
2138                                 rvalue,
2139                                 "relating {:?} with {:?} yields {:?}",
2140                                 ty_elem,
2141                                 ty_to,
2142                                 terr
2143                             )
2144                         }
2145                     }
2146
2147                     CastKind::Misc => {
2148                         let ty_from = op.ty(body, tcx);
2149                         let cast_ty_from = CastTy::from_ty(ty_from);
2150                         let cast_ty_to = CastTy::from_ty(*ty);
2151                         match (cast_ty_from, cast_ty_to) {
2152                             (None, _)
2153                             | (_, None | Some(CastTy::FnPtr))
2154                             | (Some(CastTy::Float), Some(CastTy::Ptr(_)))
2155                             | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
2156                                 span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
2157                             }
2158                             (
2159                                 Some(CastTy::Int(_)),
2160                                 Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
2161                             )
2162                             | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
2163                             | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
2164                             | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
2165                         }
2166                     }
2167                 }
2168             }
2169
2170             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2171                 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2172             }
2173
2174             Rvalue::BinaryOp(
2175                 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2176                 box (left, right),
2177             ) => {
2178                 self.check_operand(left, location);
2179                 self.check_operand(right, location);
2180
2181                 let ty_left = left.ty(body, tcx);
2182                 match ty_left.kind() {
2183                     // Types with regions are comparable if they have a common super-type.
2184                     ty::RawPtr(_) | ty::FnPtr(_) => {
2185                         let ty_right = right.ty(body, tcx);
2186                         let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2187                             kind: TypeVariableOriginKind::MiscVariable,
2188                             span: body.source_info(location).span,
2189                         });
2190                         self.sub_types(
2191                             ty_left,
2192                             common_ty,
2193                             location.to_locations(),
2194                             ConstraintCategory::Boring,
2195                         )
2196                         .unwrap_or_else(|err| {
2197                             bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2198                         });
2199                         if let Err(terr) = self.sub_types(
2200                             ty_right,
2201                             common_ty,
2202                             location.to_locations(),
2203                             ConstraintCategory::Boring,
2204                         ) {
2205                             span_mirbug!(
2206                                 self,
2207                                 rvalue,
2208                                 "unexpected comparison types {:?} and {:?} yields {:?}",
2209                                 ty_left,
2210                                 ty_right,
2211                                 terr
2212                             )
2213                         }
2214                     }
2215                     // For types with no regions we can just check that the
2216                     // both operands have the same type.
2217                     ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2218                         if ty_left == right.ty(body, tcx) => {}
2219                     // Other types are compared by trait methods, not by
2220                     // `Rvalue::BinaryOp`.
2221                     _ => span_mirbug!(
2222                         self,
2223                         rvalue,
2224                         "unexpected comparison types {:?} and {:?}",
2225                         ty_left,
2226                         right.ty(body, tcx)
2227                     ),
2228                 }
2229             }
2230
2231             Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2232                 self.check_operand(operand, location);
2233             }
2234
2235             Rvalue::BinaryOp(_, box (left, right))
2236             | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2237                 self.check_operand(left, location);
2238                 self.check_operand(right, location);
2239             }
2240
2241             Rvalue::AddressOf(..)
2242             | Rvalue::ThreadLocalRef(..)
2243             | Rvalue::Len(..)
2244             | Rvalue::Discriminant(..) => {}
2245         }
2246     }
2247
2248     /// If this rvalue supports a user-given type annotation, then
2249     /// extract and return it. This represents the final type of the
2250     /// rvalue and will be unified with the inferred type.
2251     fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2252         match rvalue {
2253             Rvalue::Use(_)
2254             | Rvalue::ThreadLocalRef(_)
2255             | Rvalue::Repeat(..)
2256             | Rvalue::Ref(..)
2257             | Rvalue::AddressOf(..)
2258             | Rvalue::Len(..)
2259             | Rvalue::Cast(..)
2260             | Rvalue::ShallowInitBox(..)
2261             | Rvalue::BinaryOp(..)
2262             | Rvalue::CheckedBinaryOp(..)
2263             | Rvalue::NullaryOp(..)
2264             | Rvalue::UnaryOp(..)
2265             | Rvalue::Discriminant(..) => None,
2266
2267             Rvalue::Aggregate(aggregate, _) => match **aggregate {
2268                 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2269                 AggregateKind::Array(_) => None,
2270                 AggregateKind::Tuple => None,
2271                 AggregateKind::Closure(_, _) => None,
2272                 AggregateKind::Generator(_, _, _) => None,
2273             },
2274         }
2275     }
2276
2277     fn check_aggregate_rvalue(
2278         &mut self,
2279         body: &Body<'tcx>,
2280         rvalue: &Rvalue<'tcx>,
2281         aggregate_kind: &AggregateKind<'tcx>,
2282         operands: &[Operand<'tcx>],
2283         location: Location,
2284     ) {
2285         let tcx = self.tcx();
2286
2287         self.prove_aggregate_predicates(aggregate_kind, location);
2288
2289         if *aggregate_kind == AggregateKind::Tuple {
2290             // tuple rvalue field type is always the type of the op. Nothing to check here.
2291             return;
2292         }
2293
2294         for (i, operand) in operands.iter().enumerate() {
2295             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2296                 Ok(field_ty) => field_ty,
2297                 Err(FieldAccessError::OutOfRange { field_count }) => {
2298                     span_mirbug!(
2299                         self,
2300                         rvalue,
2301                         "accessed field #{} but variant only has {}",
2302                         i,
2303                         field_count
2304                     );
2305                     continue;
2306                 }
2307             };
2308             let operand_ty = operand.ty(body, tcx);
2309             let operand_ty = self.normalize(operand_ty, location);
2310
2311             if let Err(terr) = self.sub_types(
2312                 operand_ty,
2313                 field_ty,
2314                 location.to_locations(),
2315                 ConstraintCategory::Boring,
2316             ) {
2317                 span_mirbug!(
2318                     self,
2319                     rvalue,
2320                     "{:?} is not a subtype of {:?}: {:?}",
2321                     operand_ty,
2322                     field_ty,
2323                     terr
2324                 );
2325             }
2326         }
2327     }
2328
2329     /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2330     ///
2331     /// # Parameters
2332     ///
2333     /// - `location`: the location `L` where the borrow expression occurs
2334     /// - `borrow_region`: the region `'a` associated with the borrow
2335     /// - `borrowed_place`: the place `P` being borrowed
2336     fn add_reborrow_constraint(
2337         &mut self,
2338         body: &Body<'tcx>,
2339         location: Location,
2340         borrow_region: ty::Region<'tcx>,
2341         borrowed_place: &Place<'tcx>,
2342     ) {
2343         // These constraints are only meaningful during borrowck:
2344         let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2345             self.borrowck_context;
2346
2347         // In Polonius mode, we also push a `loan_issued_at` fact
2348         // linking the loan to the region (in some cases, though,
2349         // there is no loan associated with this borrow expression --
2350         // that occurs when we are borrowing an unsafe place, for
2351         // example).
2352         if let Some(all_facts) = all_facts {
2353             let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2354             if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2355                 let region_vid = borrow_region.to_region_vid();
2356                 all_facts.loan_issued_at.push((
2357                     region_vid,
2358                     borrow_index,
2359                     location_table.mid_index(location),
2360                 ));
2361             }
2362         }
2363
2364         // If we are reborrowing the referent of another reference, we
2365         // need to add outlives relationships. In a case like `&mut
2366         // *p`, where the `p` has type `&'b mut Foo`, for example, we
2367         // need to ensure that `'b: 'a`.
2368
2369         debug!(
2370             "add_reborrow_constraint({:?}, {:?}, {:?})",
2371             location, borrow_region, borrowed_place
2372         );
2373
2374         let mut cursor = borrowed_place.projection.as_ref();
2375         let tcx = self.infcx.tcx;
2376         let field = path_utils::is_upvar_field_projection(
2377             tcx,
2378             &self.borrowck_context.upvars,
2379             borrowed_place.as_ref(),
2380             body,
2381         );
2382         let category = if let Some(field) = field {
2383             ConstraintCategory::ClosureUpvar(field)
2384         } else {
2385             ConstraintCategory::Boring
2386         };
2387
2388         while let [proj_base @ .., elem] = cursor {
2389             cursor = proj_base;
2390
2391             debug!("add_reborrow_constraint - iteration {:?}", elem);
2392
2393             match elem {
2394                 ProjectionElem::Deref => {
2395                     let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2396
2397                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2398                     match base_ty.kind() {
2399                         ty::Ref(ref_region, _, mutbl) => {
2400                             constraints.outlives_constraints.push(OutlivesConstraint {
2401                                 sup: ref_region.to_region_vid(),
2402                                 sub: borrow_region.to_region_vid(),
2403                                 locations: location.to_locations(),
2404                                 category,
2405                                 variance_info: ty::VarianceDiagInfo::default(),
2406                             });
2407
2408                             match mutbl {
2409                                 hir::Mutability::Not => {
2410                                     // Immutable reference. We don't need the base
2411                                     // to be valid for the entire lifetime of
2412                                     // the borrow.
2413                                     break;
2414                                 }
2415                                 hir::Mutability::Mut => {
2416                                     // Mutable reference. We *do* need the base
2417                                     // to be valid, because after the base becomes
2418                                     // invalid, someone else can use our mutable deref.
2419
2420                                     // This is in order to make the following function
2421                                     // illegal:
2422                                     // ```
2423                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2424                                     //     &mut *x
2425                                     // }
2426                                     // ```
2427                                     //
2428                                     // As otherwise you could clone `&mut T` using the
2429                                     // following function:
2430                                     // ```
2431                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2432                                     //     let my_clone = unsafe_deref(&'a x);
2433                                     //     ENDREGION 'a;
2434                                     //     (my_clone, x)
2435                                     // }
2436                                     // ```
2437                                 }
2438                             }
2439                         }
2440                         ty::RawPtr(..) => {
2441                             // deref of raw pointer, guaranteed to be valid
2442                             break;
2443                         }
2444                         ty::Adt(def, _) if def.is_box() => {
2445                             // deref of `Box`, need the base to be valid - propagate
2446                         }
2447                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2448                     }
2449                 }
2450                 ProjectionElem::Field(..)
2451                 | ProjectionElem::Downcast(..)
2452                 | ProjectionElem::Index(..)
2453                 | ProjectionElem::ConstantIndex { .. }
2454                 | ProjectionElem::Subslice { .. } => {
2455                     // other field access
2456                 }
2457             }
2458         }
2459     }
2460
2461     fn prove_aggregate_predicates(
2462         &mut self,
2463         aggregate_kind: &AggregateKind<'tcx>,
2464         location: Location,
2465     ) {
2466         let tcx = self.tcx();
2467
2468         debug!(
2469             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2470             aggregate_kind, location
2471         );
2472
2473         let (def_id, instantiated_predicates) = match aggregate_kind {
2474             AggregateKind::Adt(adt_did, _, substs, _, _) => {
2475                 (*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs))
2476             }
2477
2478             // For closures, we have some **extra requirements** we
2479             //
2480             // have to check. In particular, in their upvars and
2481             // signatures, closures often reference various regions
2482             // from the surrounding function -- we call those the
2483             // closure's free regions. When we borrow-check (and hence
2484             // region-check) closures, we may find that the closure
2485             // requires certain relationships between those free
2486             // regions. However, because those free regions refer to
2487             // portions of the CFG of their caller, the closure is not
2488             // in a position to verify those relationships. In that
2489             // case, the requirements get "propagated" to us, and so
2490             // we have to solve them here where we instantiate the
2491             // closure.
2492             //
2493             // Despite the opacity of the previous paragraph, this is
2494             // actually relatively easy to understand in terms of the
2495             // desugaring. A closure gets desugared to a struct, and
2496             // these extra requirements are basically like where
2497             // clauses on the struct.
2498             AggregateKind::Closure(def_id, substs)
2499             | AggregateKind::Generator(def_id, substs, _) => {
2500                 (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location))
2501             }
2502
2503             AggregateKind::Array(_) | AggregateKind::Tuple => {
2504                 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2505             }
2506         };
2507
2508         self.normalize_and_prove_instantiated_predicates(
2509             def_id,
2510             instantiated_predicates,
2511             location.to_locations(),
2512         );
2513     }
2514
2515     fn prove_closure_bounds(
2516         &mut self,
2517         tcx: TyCtxt<'tcx>,
2518         def_id: LocalDefId,
2519         substs: SubstsRef<'tcx>,
2520         location: Location,
2521     ) -> ty::InstantiatedPredicates<'tcx> {
2522         if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
2523         {
2524             let closure_constraints = QueryRegionConstraints {
2525                 outlives: closure_region_requirements.apply_requirements(
2526                     tcx,
2527                     def_id.to_def_id(),
2528                     substs,
2529                 ),
2530
2531                 // Presently, closures never propagate member
2532                 // constraints to their parents -- they are enforced
2533                 // locally.  This is largely a non-issue as member
2534                 // constraints only come from `-> impl Trait` and
2535                 // friends which don't appear (thus far...) in
2536                 // closures.
2537                 member_constraints: vec![],
2538             };
2539
2540             let bounds_mapping = closure_constraints
2541                 .outlives
2542                 .iter()
2543                 .enumerate()
2544                 .filter_map(|(idx, constraint)| {
2545                     let ty::OutlivesPredicate(k1, r2) =
2546                         constraint.no_bound_vars().unwrap_or_else(|| {
2547                             bug!("query_constraint {:?} contained bound vars", constraint,);
2548                         });
2549
2550                     match k1.unpack() {
2551                         GenericArgKind::Lifetime(r1) => {
2552                             // constraint is r1: r2
2553                             let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
2554                             let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
2555                             let outlives_requirements =
2556                                 &closure_region_requirements.outlives_requirements[idx];
2557                             Some((
2558                                 (r1_vid, r2_vid),
2559                                 (outlives_requirements.category, outlives_requirements.blame_span),
2560                             ))
2561                         }
2562                         GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
2563                     }
2564                 })
2565                 .collect();
2566
2567             let existing = self
2568                 .borrowck_context
2569                 .constraints
2570                 .closure_bounds_mapping
2571                 .insert(location, bounds_mapping);
2572             assert!(existing.is_none(), "Multiple closures at the same location.");
2573
2574             self.push_region_constraints(
2575                 location.to_locations(),
2576                 ConstraintCategory::ClosureBounds,
2577                 &closure_constraints,
2578             );
2579         }
2580
2581         tcx.predicates_of(def_id).instantiate(tcx, substs)
2582     }
2583
2584     #[instrument(skip(self, body), level = "debug")]
2585     fn typeck_mir(&mut self, body: &Body<'tcx>) {
2586         self.last_span = body.span;
2587         debug!(?body.span);
2588
2589         for (local, local_decl) in body.local_decls.iter_enumerated() {
2590             self.check_local(&body, local, local_decl);
2591         }
2592
2593         for (block, block_data) in body.basic_blocks().iter_enumerated() {
2594             let mut location = Location { block, statement_index: 0 };
2595             for stmt in &block_data.statements {
2596                 if !stmt.source_info.span.is_dummy() {
2597                     self.last_span = stmt.source_info.span;
2598                 }
2599                 self.check_stmt(body, stmt, location);
2600                 location.statement_index += 1;
2601             }
2602
2603             self.check_terminator(&body, block_data.terminator(), location);
2604             self.check_iscleanup(&body, block_data);
2605         }
2606     }
2607 }
2608
2609 trait NormalizeLocation: fmt::Debug + Copy {
2610     fn to_locations(self) -> Locations;
2611 }
2612
2613 impl NormalizeLocation for Locations {
2614     fn to_locations(self) -> Locations {
2615         self
2616     }
2617 }
2618
2619 impl NormalizeLocation for Location {
2620     fn to_locations(self) -> Locations {
2621         Locations::Single(self)
2622     }
2623 }
2624
2625 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2626 /// this is not canonicalized - it directly affects the main `InferCtxt`
2627 /// that we use during MIR borrowchecking.
2628 #[derive(Debug)]
2629 pub(super) struct InstantiateOpaqueType<'tcx> {
2630     pub base_universe: Option<ty::UniverseIndex>,
2631     pub region_constraints: Option<RegionConstraintData<'tcx>>,
2632     pub obligations: Vec<PredicateObligation<'tcx>>,
2633 }
2634
2635 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2636     type Output = ();
2637     /// We use this type itself to store the information used
2638     /// when reporting errors. Since this is not a query, we don't
2639     /// re-run anything during error reporting - we just use the information
2640     /// we saved to help extract an error from the already-existing region
2641     /// constraints in our `InferCtxt`
2642     type ErrorInfo = InstantiateOpaqueType<'tcx>;
2643
2644     fn fully_perform(mut self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2645         let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2646             Ok(InferOk { value: (), obligations: self.obligations.clone() })
2647         })?;
2648         self.region_constraints = Some(region_constraints);
2649         output.error_info = Some(self);
2650         Ok(output)
2651     }
2652 }