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