rustc_borrowck/type_check/
mod.rs

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