1use 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
76pub(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: ®ion_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 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 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 tcx.dcx().span_delayed_bug(span, msg);
207}
208
209enum FieldAccessError {
210 OutOfRange { field_count: usize },
211}
212
213struct 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 promoted: &'a IndexSlice<Promoted, Body<'tcx>>,
225 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 polonius_liveness: Option<PoloniusLivenessContext>,
239}
240
241pub(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#[derive(Clone)] pub(crate) struct MirTypeckRegionConstraints<'tcx> {
256 pub(crate) placeholder_indices: PlaceholderIndices<'tcx>,
262
263 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
269
270 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 pub(crate) fn placeholder_region(
290 &mut self,
291 infcx: &InferCtxt<'tcx>,
292 placeholder: ty::PlaceholderRegion<'tcx>,
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#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
312pub enum Locations {
313 All(Span),
349
350 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 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 #[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 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 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 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 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 let parent_body = mem::replace(&mut self.body, promoted_body);
501
502 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 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 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 constraint.category = ConstraintCategory::Boring;
538 }
539 self.constraints.outlives_constraints.push(constraint)
540 }
541
542 for (closure_def_id, args, _locations) in deferred_closure_requirements {
549 self.deferred_closure_requirements.push((closure_def_id, args, locations));
550 }
551
552 #[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 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 }
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 }
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 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 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 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 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 if !self.unsized_feature_enabled() {
985 match self.body.local_kind(local) {
986 LocalKind::ReturnPointer | LocalKind::Arg => {
987 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 len.try_to_target_usize(tcx).is_none_or(|len| len > 1) {
1025 match operand {
1026 Operand::Copy(..) | Operand::Constant(..) | Operand::RuntimeChecks(_) => {
1027 }
1030 Operand::Move(place) => {
1031 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::ShallowInitBox(_operand, ty) => {
1050 let trait_ref =
1051 ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Sized, span), [*ty]);
1052
1053 self.prove_trait_ref(
1054 trait_ref,
1055 location.to_locations(),
1056 ConstraintCategory::SizedBound,
1057 );
1058 }
1059
1060 Rvalue::Cast(cast_kind, op, ty) => {
1061 match *cast_kind {
1062 CastKind::PointerCoercion(
1063 PointerCoercion::ReifyFnPointer(target_safety),
1064 coercion_source,
1065 ) => {
1066 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1067 let src_ty = op.ty(self.body, tcx);
1068 let mut src_sig = src_ty.fn_sig(tcx);
1069 if let ty::FnDef(def_id, _) = src_ty.kind()
1070 && let ty::FnPtr(_, target_hdr) = *ty.kind()
1071 && tcx.codegen_fn_attrs(def_id).safe_target_features
1072 && target_hdr.safety.is_safe()
1073 && let Some(safe_sig) = tcx.adjust_target_feature_sig(
1074 *def_id,
1075 src_sig,
1076 self.body.source.def_id(),
1077 )
1078 {
1079 src_sig = safe_sig;
1080 }
1081
1082 if src_sig.safety().is_safe() && target_safety.is_unsafe() {
1083 src_sig = tcx.safe_to_unsafe_sig(src_sig);
1084 }
1085
1086 if src_sig.has_bound_regions()
1101 && let ty::FnPtr(target_fn_tys, target_hdr) = *ty.kind()
1102 && let target_sig = target_fn_tys.with(target_hdr)
1103 && let Some(target_sig) = target_sig.no_bound_vars()
1104 {
1105 let src_sig = self.infcx.instantiate_binder_with_fresh_vars(
1106 span,
1107 BoundRegionConversionTime::HigherRankedType,
1108 src_sig,
1109 );
1110 let src_ty = Ty::new_fn_ptr(self.tcx(), ty::Binder::dummy(src_sig));
1111 self.prove_predicate(
1112 ty::ClauseKind::WellFormed(src_ty.into()),
1113 location.to_locations(),
1114 ConstraintCategory::Cast {
1115 is_raw_ptr_dyn_type_cast: false,
1116 is_implicit_coercion,
1117 unsize_to: None,
1118 },
1119 );
1120
1121 let src_ty = self.normalize(src_ty, location);
1122 if let Err(terr) = self.sub_types(
1123 src_ty,
1124 *ty,
1125 location.to_locations(),
1126 ConstraintCategory::Cast {
1127 is_raw_ptr_dyn_type_cast: false,
1128 is_implicit_coercion,
1129 unsize_to: None,
1130 },
1131 ) {
1132 span_mirbug!(
1133 self,
1134 rvalue,
1135 "equating {:?} with {:?} yields {:?}",
1136 target_sig,
1137 src_sig,
1138 terr
1139 );
1140 };
1141 }
1142
1143 let src_ty = Ty::new_fn_ptr(tcx, src_sig);
1144 self.prove_predicate(
1149 ty::ClauseKind::WellFormed(src_ty.into()),
1150 location.to_locations(),
1151 ConstraintCategory::Cast {
1152 is_raw_ptr_dyn_type_cast: false,
1153 is_implicit_coercion,
1154 unsize_to: None,
1155 },
1156 );
1157
1158 let src_ty = self.normalize(src_ty, location);
1164 if let Err(terr) = self.sub_types(
1165 src_ty,
1166 *ty,
1167 location.to_locations(),
1168 ConstraintCategory::Cast {
1169 is_raw_ptr_dyn_type_cast: false,
1170 is_implicit_coercion,
1171 unsize_to: None,
1172 },
1173 ) {
1174 span_mirbug!(
1175 self,
1176 rvalue,
1177 "equating {:?} with {:?} yields {:?}",
1178 src_ty,
1179 ty,
1180 terr
1181 );
1182 }
1183 }
1184
1185 CastKind::PointerCoercion(
1186 PointerCoercion::ClosureFnPointer(safety),
1187 coercion_source,
1188 ) => {
1189 let sig = match op.ty(self.body, tcx).kind() {
1190 ty::Closure(_, args) => args.as_closure().sig(),
1191 _ => bug!(),
1192 };
1193 let ty_fn_ptr_from =
1194 Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, safety));
1195
1196 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1197 if let Err(terr) = self.sub_types(
1198 ty_fn_ptr_from,
1199 *ty,
1200 location.to_locations(),
1201 ConstraintCategory::Cast {
1202 is_raw_ptr_dyn_type_cast: false,
1203 is_implicit_coercion,
1204 unsize_to: None,
1205 },
1206 ) {
1207 span_mirbug!(
1208 self,
1209 rvalue,
1210 "equating {:?} with {:?} yields {:?}",
1211 ty_fn_ptr_from,
1212 ty,
1213 terr
1214 );
1215 }
1216 }
1217
1218 CastKind::PointerCoercion(
1219 PointerCoercion::UnsafeFnPointer,
1220 coercion_source,
1221 ) => {
1222 let fn_sig = op.ty(self.body, tcx).fn_sig(tcx);
1223
1224 let fn_sig = self.normalize(fn_sig, location);
1230
1231 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1232
1233 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1234 if let Err(terr) = self.sub_types(
1235 ty_fn_ptr_from,
1236 *ty,
1237 location.to_locations(),
1238 ConstraintCategory::Cast {
1239 is_raw_ptr_dyn_type_cast: false,
1240 is_implicit_coercion,
1241 unsize_to: None,
1242 },
1243 ) {
1244 span_mirbug!(
1245 self,
1246 rvalue,
1247 "equating {:?} with {:?} yields {:?}",
1248 ty_fn_ptr_from,
1249 ty,
1250 terr
1251 );
1252 }
1253 }
1254
1255 CastKind::PointerCoercion(PointerCoercion::Unsize, coercion_source) => {
1256 let &ty = ty;
1257 let trait_ref = ty::TraitRef::new(
1258 tcx,
1259 tcx.require_lang_item(LangItem::CoerceUnsized, span),
1260 [op.ty(self.body, tcx), ty],
1261 );
1262
1263 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1264 let unsize_to = fold_regions(tcx, ty, |r, _| {
1265 if let ty::ReVar(_) = r.kind() { tcx.lifetimes.re_erased } else { r }
1266 });
1267 self.prove_trait_ref(
1268 trait_ref,
1269 location.to_locations(),
1270 ConstraintCategory::Cast {
1271 is_raw_ptr_dyn_type_cast: false,
1272 is_implicit_coercion,
1273 unsize_to: Some(unsize_to),
1274 },
1275 );
1276 }
1277
1278 CastKind::PointerCoercion(
1279 PointerCoercion::MutToConstPointer,
1280 coercion_source,
1281 ) => {
1282 let ty::RawPtr(ty_from, hir::Mutability::Mut) =
1283 op.ty(self.body, tcx).kind()
1284 else {
1285 span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,);
1286 return;
1287 };
1288 let ty::RawPtr(ty_to, hir::Mutability::Not) = ty.kind() else {
1289 span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,);
1290 return;
1291 };
1292 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1293 if let Err(terr) = self.sub_types(
1294 *ty_from,
1295 *ty_to,
1296 location.to_locations(),
1297 ConstraintCategory::Cast {
1298 is_raw_ptr_dyn_type_cast: false,
1299 is_implicit_coercion,
1300 unsize_to: None,
1301 },
1302 ) {
1303 span_mirbug!(
1304 self,
1305 rvalue,
1306 "relating {:?} with {:?} yields {:?}",
1307 ty_from,
1308 ty_to,
1309 terr
1310 );
1311 }
1312 }
1313
1314 CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, coercion_source) => {
1315 let ty_from = op.ty(self.body, tcx);
1316
1317 let opt_ty_elem_mut = match ty_from.kind() {
1318 ty::RawPtr(array_ty, array_mut) => match array_ty.kind() {
1319 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
1320 _ => None,
1321 },
1322 _ => None,
1323 };
1324
1325 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
1326 span_mirbug!(
1327 self,
1328 rvalue,
1329 "ArrayToPointer cast from unexpected type {:?}",
1330 ty_from,
1331 );
1332 return;
1333 };
1334
1335 let (ty_to, ty_to_mut) = match ty.kind() {
1336 ty::RawPtr(ty_to, ty_to_mut) => (ty_to, *ty_to_mut),
1337 _ => {
1338 span_mirbug!(
1339 self,
1340 rvalue,
1341 "ArrayToPointer cast to unexpected type {:?}",
1342 ty,
1343 );
1344 return;
1345 }
1346 };
1347
1348 if ty_to_mut.is_mut() && ty_mut.is_not() {
1349 span_mirbug!(
1350 self,
1351 rvalue,
1352 "ArrayToPointer cast from const {:?} to mut {:?}",
1353 ty,
1354 ty_to
1355 );
1356 return;
1357 }
1358
1359 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1360 if let Err(terr) = self.sub_types(
1361 *ty_elem,
1362 *ty_to,
1363 location.to_locations(),
1364 ConstraintCategory::Cast {
1365 is_raw_ptr_dyn_type_cast: false,
1366 is_implicit_coercion,
1367 unsize_to: None,
1368 },
1369 ) {
1370 span_mirbug!(
1371 self,
1372 rvalue,
1373 "relating {:?} with {:?} yields {:?}",
1374 ty_elem,
1375 ty_to,
1376 terr
1377 )
1378 }
1379 }
1380
1381 CastKind::PointerExposeProvenance => {
1382 let ty_from = op.ty(self.body, tcx);
1383 let cast_ty_from = CastTy::from_ty(ty_from);
1384 let cast_ty_to = CastTy::from_ty(*ty);
1385 match (cast_ty_from, cast_ty_to) {
1386 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
1387 _ => {
1388 span_mirbug!(
1389 self,
1390 rvalue,
1391 "Invalid PointerExposeProvenance cast {:?} -> {:?}",
1392 ty_from,
1393 ty
1394 )
1395 }
1396 }
1397 }
1398
1399 CastKind::PointerWithExposedProvenance => {
1400 let ty_from = op.ty(self.body, tcx);
1401 let cast_ty_from = CastTy::from_ty(ty_from);
1402 let cast_ty_to = CastTy::from_ty(*ty);
1403 match (cast_ty_from, cast_ty_to) {
1404 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
1405 _ => {
1406 span_mirbug!(
1407 self,
1408 rvalue,
1409 "Invalid PointerWithExposedProvenance cast {:?} -> {:?}",
1410 ty_from,
1411 ty
1412 )
1413 }
1414 }
1415 }
1416 CastKind::IntToInt => {
1417 let ty_from = op.ty(self.body, tcx);
1418 let cast_ty_from = CastTy::from_ty(ty_from);
1419 let cast_ty_to = CastTy::from_ty(*ty);
1420 match (cast_ty_from, cast_ty_to) {
1421 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
1422 _ => {
1423 span_mirbug!(
1424 self,
1425 rvalue,
1426 "Invalid IntToInt cast {:?} -> {:?}",
1427 ty_from,
1428 ty
1429 )
1430 }
1431 }
1432 }
1433 CastKind::IntToFloat => {
1434 let ty_from = op.ty(self.body, tcx);
1435 let cast_ty_from = CastTy::from_ty(ty_from);
1436 let cast_ty_to = CastTy::from_ty(*ty);
1437 match (cast_ty_from, cast_ty_to) {
1438 (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
1439 _ => {
1440 span_mirbug!(
1441 self,
1442 rvalue,
1443 "Invalid IntToFloat cast {:?} -> {:?}",
1444 ty_from,
1445 ty
1446 )
1447 }
1448 }
1449 }
1450 CastKind::FloatToInt => {
1451 let ty_from = op.ty(self.body, tcx);
1452 let cast_ty_from = CastTy::from_ty(ty_from);
1453 let cast_ty_to = CastTy::from_ty(*ty);
1454 match (cast_ty_from, cast_ty_to) {
1455 (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
1456 _ => {
1457 span_mirbug!(
1458 self,
1459 rvalue,
1460 "Invalid FloatToInt cast {:?} -> {:?}",
1461 ty_from,
1462 ty
1463 )
1464 }
1465 }
1466 }
1467 CastKind::FloatToFloat => {
1468 let ty_from = op.ty(self.body, tcx);
1469 let cast_ty_from = CastTy::from_ty(ty_from);
1470 let cast_ty_to = CastTy::from_ty(*ty);
1471 match (cast_ty_from, cast_ty_to) {
1472 (Some(CastTy::Float), Some(CastTy::Float)) => (),
1473 _ => {
1474 span_mirbug!(
1475 self,
1476 rvalue,
1477 "Invalid FloatToFloat cast {:?} -> {:?}",
1478 ty_from,
1479 ty
1480 )
1481 }
1482 }
1483 }
1484 CastKind::FnPtrToPtr => {
1485 let ty_from = op.ty(self.body, tcx);
1486 let cast_ty_from = CastTy::from_ty(ty_from);
1487 let cast_ty_to = CastTy::from_ty(*ty);
1488 match (cast_ty_from, cast_ty_to) {
1489 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
1490 _ => {
1491 span_mirbug!(
1492 self,
1493 rvalue,
1494 "Invalid FnPtrToPtr cast {:?} -> {:?}",
1495 ty_from,
1496 ty
1497 )
1498 }
1499 }
1500 }
1501 CastKind::PtrToPtr => {
1502 let ty_from = op.ty(self.body, tcx);
1503 let Some(CastTy::Ptr(src)) = CastTy::from_ty(ty_from) else {
1504 unreachable!();
1505 };
1506 let Some(CastTy::Ptr(dst)) = CastTy::from_ty(*ty) else {
1507 unreachable!();
1508 };
1509
1510 if self.infcx.type_is_sized_modulo_regions(self.infcx.param_env, dst.ty) {
1511 let trait_ref = ty::TraitRef::new(
1517 tcx,
1518 tcx.require_lang_item(LangItem::Sized, self.last_span),
1519 [dst.ty],
1520 );
1521 self.prove_trait_ref(
1522 trait_ref,
1523 location.to_locations(),
1524 ConstraintCategory::Cast {
1525 is_raw_ptr_dyn_type_cast: false,
1526 is_implicit_coercion: true,
1527 unsize_to: None,
1528 },
1529 );
1530 } else if let ty::Dynamic(src_tty, src_lt) =
1531 *self.struct_tail(src.ty, location).kind()
1532 && let ty::Dynamic(dst_tty, dst_lt) =
1533 *self.struct_tail(dst.ty, location).kind()
1534 {
1535 match (src_tty.principal(), dst_tty.principal()) {
1536 (Some(_), Some(_)) => {
1537 let src_obj = Ty::new_dynamic(
1547 tcx,
1548 tcx.mk_poly_existential_predicates(
1549 &src_tty.without_auto_traits().collect::<Vec<_>>(),
1550 ),
1551 src_lt,
1552 );
1553 let dst_obj = Ty::new_dynamic(
1554 tcx,
1555 tcx.mk_poly_existential_predicates(
1556 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1557 ),
1558 dst_lt,
1559 );
1560
1561 debug!(?src_tty, ?dst_tty, ?src_obj, ?dst_obj);
1562
1563 self.sub_types(
1572 src_obj,
1573 dst_obj,
1574 location.to_locations(),
1575 ConstraintCategory::Cast {
1576 is_raw_ptr_dyn_type_cast: true,
1577 is_implicit_coercion: false,
1578 unsize_to: None,
1579 },
1580 )
1581 .unwrap();
1582 }
1583 (None, None) => {
1584 self.constraints.outlives_constraints.push(
1587 OutlivesConstraint {
1588 sup: src_lt.as_var(),
1589 sub: dst_lt.as_var(),
1590 locations: location.to_locations(),
1591 span: location.to_locations().span(self.body),
1592 category: ConstraintCategory::Cast {
1593 is_raw_ptr_dyn_type_cast: true,
1594 is_implicit_coercion: false,
1595 unsize_to: None,
1596 },
1597 variance_info: ty::VarianceDiagInfo::default(),
1598 from_closure: false,
1599 },
1600 );
1601 }
1602 (None, Some(_)) => bug!(
1603 "introducing a principal should have errored in HIR typeck"
1604 ),
1605 (Some(_), None) => {
1606 bug!("dropping the principal should have been an unsizing cast")
1607 }
1608 }
1609 }
1610 }
1611 CastKind::Transmute => {
1612 let ty_from = op.ty(self.body, tcx);
1613 match ty_from.kind() {
1614 ty::Pat(base, _) if base == ty => {}
1615 _ => span_mirbug!(
1616 self,
1617 rvalue,
1618 "Unexpected CastKind::Transmute {ty_from:?} -> {ty:?}, which is not permitted in Analysis MIR",
1619 ),
1620 }
1621 }
1622 CastKind::Subtype => {
1623 bug!("CastKind::Subtype shouldn't exist in borrowck")
1624 }
1625 }
1626 }
1627
1628 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1629 self.add_reborrow_constraint(location, *region, borrowed_place);
1630 }
1631
1632 Rvalue::BinaryOp(
1633 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
1634 box (left, right),
1635 ) => {
1636 let ty_left = left.ty(self.body, tcx);
1637 match ty_left.kind() {
1638 ty::RawPtr(_, _) | ty::FnPtr(..) => {
1640 let ty_right = right.ty(self.body, tcx);
1641 let common_ty =
1642 self.infcx.next_ty_var(self.body.source_info(location).span);
1643 self.sub_types(
1644 ty_left,
1645 common_ty,
1646 location.to_locations(),
1647 ConstraintCategory::CallArgument(None),
1648 )
1649 .unwrap_or_else(|err| {
1650 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
1651 });
1652 if let Err(terr) = self.sub_types(
1653 ty_right,
1654 common_ty,
1655 location.to_locations(),
1656 ConstraintCategory::CallArgument(None),
1657 ) {
1658 span_mirbug!(
1659 self,
1660 rvalue,
1661 "unexpected comparison types {:?} and {:?} yields {:?}",
1662 ty_left,
1663 ty_right,
1664 terr
1665 )
1666 }
1667 }
1668 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
1671 if ty_left == right.ty(self.body, tcx) => {}
1672 _ => span_mirbug!(
1675 self,
1676 rvalue,
1677 "unexpected comparison types {:?} and {:?}",
1678 ty_left,
1679 right.ty(self.body, tcx)
1680 ),
1681 }
1682 }
1683
1684 Rvalue::WrapUnsafeBinder(op, ty) => {
1685 let operand_ty = op.ty(self.body, self.tcx());
1686 let ty::UnsafeBinder(binder_ty) = *ty.kind() else {
1687 unreachable!();
1688 };
1689 let expected_ty = self.infcx.instantiate_binder_with_fresh_vars(
1690 self.body().source_info(location).span,
1691 BoundRegionConversionTime::HigherRankedType,
1692 binder_ty.into(),
1693 );
1694 self.sub_types(
1695 operand_ty,
1696 expected_ty,
1697 location.to_locations(),
1698 ConstraintCategory::Boring,
1699 )
1700 .unwrap();
1701 }
1702
1703 Rvalue::Use(_)
1704 | Rvalue::UnaryOp(_, _)
1705 | Rvalue::CopyForDeref(_)
1706 | Rvalue::BinaryOp(..)
1707 | Rvalue::RawPtr(..)
1708 | Rvalue::ThreadLocalRef(..)
1709 | Rvalue::Discriminant(..) => {}
1710 }
1711 }
1712
1713 #[instrument(level = "debug", skip(self))]
1714 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1715 self.super_operand(op, location);
1716 if let Operand::Constant(constant) = op {
1717 let maybe_uneval = match constant.const_ {
1718 Const::Val(..) | Const::Ty(_, _) => None,
1719 Const::Unevaluated(uv, _) => Some(uv),
1720 };
1721
1722 if let Some(uv) = maybe_uneval {
1723 if uv.promoted.is_none() {
1724 let tcx = self.tcx();
1725 let def_id = uv.def;
1726 if tcx.def_kind(def_id) == DefKind::InlineConst {
1727 let def_id = def_id.expect_local();
1728 let predicates = self.prove_closure_bounds(
1729 tcx,
1730 def_id,
1731 uv.args,
1732 location.to_locations(),
1733 );
1734 self.normalize_and_prove_instantiated_predicates(
1735 def_id.to_def_id(),
1736 predicates,
1737 location.to_locations(),
1738 );
1739 }
1740 }
1741 }
1742 }
1743 }
1744
1745 #[instrument(level = "debug", skip(self))]
1746 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, location: Location) {
1747 self.super_const_operand(constant, location);
1748 let ty = constant.const_.ty();
1749
1750 self.infcx.tcx.for_each_free_region(&ty, |live_region| {
1751 let live_region_vid = self.universal_regions.to_region_vid(live_region);
1752 self.constraints.liveness_constraints.add_location(live_region_vid, location);
1753 });
1754
1755 let locations = location.to_locations();
1756 if let Some(annotation_index) = constant.user_ty {
1757 if let Err(terr) = self.relate_type_and_user_type(
1758 constant.const_.ty(),
1759 ty::Invariant,
1760 &UserTypeProjection { base: annotation_index, projs: vec![] },
1761 locations,
1762 ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg),
1763 ) {
1764 let annotation = &self.user_type_annotations[annotation_index];
1765 span_mirbug!(
1766 self,
1767 constant,
1768 "bad constant user type {:?} vs {:?}: {:?}",
1769 annotation,
1770 constant.const_.ty(),
1771 terr,
1772 );
1773 }
1774 } else {
1775 let tcx = self.tcx();
1776 let maybe_uneval = match constant.const_ {
1777 Const::Ty(_, ct) => match ct.kind() {
1778 ty::ConstKind::Unevaluated(uv) => {
1779 Some(UnevaluatedConst { def: uv.def, args: uv.args, promoted: None })
1780 }
1781 _ => None,
1782 },
1783 Const::Unevaluated(uv, _) => Some(uv),
1784 _ => None,
1785 };
1786
1787 if let Some(uv) = maybe_uneval {
1788 if let Some(promoted) = uv.promoted {
1789 let promoted_body = &self.promoted[promoted];
1790 self.check_promoted(promoted_body, location);
1791 let promoted_ty = promoted_body.return_ty();
1792 if let Err(terr) =
1793 self.eq_types(ty, promoted_ty, locations, ConstraintCategory::Boring)
1794 {
1795 span_mirbug!(
1796 self,
1797 promoted,
1798 "bad promoted type ({:?}: {:?}): {:?}",
1799 ty,
1800 promoted_ty,
1801 terr
1802 );
1803 };
1804 } else {
1805 self.ascribe_user_type(
1806 constant.const_.ty(),
1807 ty::UserType::new(ty::UserTypeKind::TypeOf(
1808 uv.def,
1809 UserArgs { args: uv.args, user_self_ty: None },
1810 )),
1811 locations.span(self.body),
1812 );
1813 }
1814 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
1815 let unnormalized_ty = tcx.type_of(static_def_id).instantiate_identity();
1816 let normalized_ty = self.normalize(unnormalized_ty, locations);
1817 let literal_ty = constant.const_.ty().builtin_deref(true).unwrap();
1818
1819 if let Err(terr) =
1820 self.eq_types(literal_ty, normalized_ty, locations, ConstraintCategory::Boring)
1821 {
1822 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
1823 }
1824 } else if let Const::Ty(_, ct) = constant.const_
1825 && let ty::ConstKind::Param(p) = ct.kind()
1826 {
1827 let body_def_id = self.universal_regions.defining_ty.def_id();
1828 let const_param = tcx.generics_of(body_def_id).const_param(p, tcx);
1829 self.ascribe_user_type(
1830 constant.const_.ty(),
1831 ty::UserType::new(ty::UserTypeKind::TypeOf(
1832 const_param.def_id,
1833 UserArgs {
1834 args: self.universal_regions.defining_ty.args(),
1835 user_self_ty: None,
1836 },
1837 )),
1838 locations.span(self.body),
1839 );
1840 }
1841
1842 if let ty::FnDef(def_id, args) = *constant.const_.ty().kind() {
1843 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, args);
1844 self.normalize_and_prove_instantiated_predicates(
1845 def_id,
1846 instantiated_predicates,
1847 locations,
1848 );
1849
1850 assert_eq!(tcx.trait_impl_of_assoc(def_id), None);
1851 self.prove_predicates(
1852 args.types().map(|ty| ty::ClauseKind::WellFormed(ty.into())),
1853 locations,
1854 ConstraintCategory::Boring,
1855 );
1856 }
1857 }
1858 }
1859
1860 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1861 self.super_place(place, context, location);
1862 let tcx = self.tcx();
1863 let place_ty = place.ty(self.body, tcx);
1864 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
1865 let trait_ref = ty::TraitRef::new(
1866 tcx,
1867 tcx.require_lang_item(LangItem::Copy, self.last_span),
1868 [place_ty.ty],
1869 );
1870
1871 self.prove_trait_ref(trait_ref, location.to_locations(), ConstraintCategory::CopyBound);
1883 }
1884 }
1885
1886 fn visit_projection_elem(
1887 &mut self,
1888 place: PlaceRef<'tcx>,
1889 elem: PlaceElem<'tcx>,
1890 context: PlaceContext,
1891 location: Location,
1892 ) {
1893 let tcx = self.tcx();
1894 let base_ty = place.ty(self.body(), tcx);
1895 match elem {
1896 ProjectionElem::Deref
1899 | ProjectionElem::Index(_)
1900 | ProjectionElem::ConstantIndex { .. }
1901 | ProjectionElem::Subslice { .. }
1902 | ProjectionElem::Downcast(..) => {}
1903 ProjectionElem::Field(field, fty) => {
1904 let fty = self.normalize(fty, location);
1905 let ty = PlaceTy::field_ty(tcx, base_ty.ty, base_ty.variant_index, field);
1906 let ty = self.normalize(ty, location);
1907 debug!(?fty, ?ty);
1908
1909 if let Err(terr) = self.relate_types(
1910 ty,
1911 context.ambient_variance(),
1912 fty,
1913 location.to_locations(),
1914 ConstraintCategory::Boring,
1915 ) {
1916 span_mirbug!(self, place, "bad field access ({:?}: {:?}): {:?}", ty, fty, terr);
1917 }
1918 }
1919 ProjectionElem::OpaqueCast(ty) => {
1920 let ty = self.normalize(ty, location);
1921 self.relate_types(
1922 ty,
1923 context.ambient_variance(),
1924 base_ty.ty,
1925 location.to_locations(),
1926 ConstraintCategory::TypeAnnotation(AnnotationSource::OpaqueCast),
1927 )
1928 .unwrap();
1929 }
1930 ProjectionElem::UnwrapUnsafeBinder(ty) => {
1931 let ty::UnsafeBinder(binder_ty) = *base_ty.ty.kind() else {
1932 unreachable!();
1933 };
1934 let found_ty = self.infcx.instantiate_binder_with_fresh_vars(
1935 self.body.source_info(location).span,
1936 BoundRegionConversionTime::HigherRankedType,
1937 binder_ty.into(),
1938 );
1939 self.relate_types(
1940 ty,
1941 context.ambient_variance(),
1942 found_ty,
1943 location.to_locations(),
1944 ConstraintCategory::Boring,
1945 )
1946 .unwrap();
1947 }
1948 }
1949 }
1950}
1951
1952impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1953 fn check_call_dest(
1954 &mut self,
1955 term: &Terminator<'tcx>,
1956 sig: &ty::FnSig<'tcx>,
1957 destination: Place<'tcx>,
1958 is_diverging: bool,
1959 term_location: Location,
1960 ) {
1961 let tcx = self.tcx();
1962 if is_diverging {
1963 let output_ty = self.tcx().erase_and_anonymize_regions(sig.output());
1966 if !output_ty
1967 .is_privately_uninhabited(self.tcx(), self.infcx.typing_env(self.infcx.param_env))
1968 {
1969 span_mirbug!(self, term, "call to non-diverging function {:?} w/o dest", sig);
1970 }
1971 } else {
1972 let dest_ty = destination.ty(self.body, tcx).ty;
1973 let dest_ty = self.normalize(dest_ty, term_location);
1974 let category = match destination.as_local() {
1975 Some(RETURN_PLACE) => {
1976 if let DefiningTy::Const(def_id, _) | DefiningTy::InlineConst(def_id, _) =
1977 self.universal_regions.defining_ty
1978 {
1979 if tcx.is_static(def_id) {
1980 ConstraintCategory::UseAsStatic
1981 } else {
1982 ConstraintCategory::UseAsConst
1983 }
1984 } else {
1985 ConstraintCategory::Return(ReturnConstraint::Normal)
1986 }
1987 }
1988 Some(l) if !self.body.local_decls[l].is_user_variable() => {
1989 ConstraintCategory::Boring
1990 }
1991 _ => ConstraintCategory::Assignment,
1993 };
1994
1995 let locations = term_location.to_locations();
1996
1997 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1998 span_mirbug!(
1999 self,
2000 term,
2001 "call dest mismatch ({:?} <- {:?}): {:?}",
2002 dest_ty,
2003 sig.output(),
2004 terr
2005 );
2006 }
2007
2008 if self.unsized_feature_enabled() {
2011 let span = term.source_info.span;
2012 self.ensure_place_sized(dest_ty, span);
2013 }
2014 }
2015 }
2016
2017 #[instrument(level = "debug", skip(self, term, func, term_location, call_source))]
2018 fn check_call_inputs(
2019 &mut self,
2020 term: &Terminator<'tcx>,
2021 func: &Operand<'tcx>,
2022 sig: &ty::FnSig<'tcx>,
2023 args: &[Spanned<Operand<'tcx>>],
2024 term_location: Location,
2025 call_source: CallSource,
2026 ) {
2027 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
2028 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
2029 }
2030
2031 let func_ty = func.ty(self.body, self.infcx.tcx);
2032 if let ty::FnDef(def_id, _) = *func_ty.kind() {
2033 if let Some(name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract)) =
2037 self.tcx().intrinsic(def_id).map(|i| i.name)
2038 {
2039 let idx = match name {
2040 sym::simd_shuffle => 2,
2041 _ => 1,
2042 };
2043 if !matches!(args[idx], Spanned { node: Operand::Constant(_), .. }) {
2044 self.tcx().dcx().emit_err(SimdIntrinsicArgConst {
2045 span: term.source_info.span,
2046 arg: idx + 1,
2047 intrinsic: name.to_string(),
2048 });
2049 }
2050 }
2051 }
2052 debug!(?func_ty);
2053
2054 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
2055 let op_arg_ty = op_arg.node.ty(self.body, self.tcx());
2056
2057 let op_arg_ty = self.normalize(op_arg_ty, term_location);
2058 let category = if call_source.from_hir_call() {
2059 ConstraintCategory::CallArgument(Some(
2060 self.infcx.tcx.erase_and_anonymize_regions(func_ty),
2061 ))
2062 } else {
2063 ConstraintCategory::Boring
2064 };
2065 if let Err(terr) =
2066 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
2067 {
2068 span_mirbug!(
2069 self,
2070 term,
2071 "bad arg #{:?} ({:?} <- {:?}): {:?}",
2072 n,
2073 fn_arg,
2074 op_arg_ty,
2075 terr
2076 );
2077 }
2078 }
2079 }
2080
2081 fn check_iscleanup(&mut self, block_data: &BasicBlockData<'tcx>) {
2082 let is_cleanup = block_data.is_cleanup;
2083 match block_data.terminator().kind {
2084 TerminatorKind::Goto { target } => {
2085 self.assert_iscleanup(block_data, target, is_cleanup)
2086 }
2087 TerminatorKind::SwitchInt { ref targets, .. } => {
2088 for target in targets.all_targets() {
2089 self.assert_iscleanup(block_data, *target, is_cleanup);
2090 }
2091 }
2092 TerminatorKind::UnwindResume => {
2093 if !is_cleanup {
2094 span_mirbug!(self, block_data, "resume on non-cleanup block!")
2095 }
2096 }
2097 TerminatorKind::UnwindTerminate(_) => {
2098 if !is_cleanup {
2099 span_mirbug!(self, block_data, "terminate on non-cleanup block!")
2100 }
2101 }
2102 TerminatorKind::Return => {
2103 if is_cleanup {
2104 span_mirbug!(self, block_data, "return on cleanup block")
2105 }
2106 }
2107 TerminatorKind::TailCall { .. } => {
2108 if is_cleanup {
2109 span_mirbug!(self, block_data, "tailcall on cleanup block")
2110 }
2111 }
2112 TerminatorKind::CoroutineDrop { .. } => {
2113 if is_cleanup {
2114 span_mirbug!(self, block_data, "coroutine_drop in cleanup block")
2115 }
2116 }
2117 TerminatorKind::Yield { resume, drop, .. } => {
2118 if is_cleanup {
2119 span_mirbug!(self, block_data, "yield in cleanup block")
2120 }
2121 self.assert_iscleanup(block_data, resume, is_cleanup);
2122 if let Some(drop) = drop {
2123 self.assert_iscleanup(block_data, drop, is_cleanup);
2124 }
2125 }
2126 TerminatorKind::Unreachable => {}
2127 TerminatorKind::Drop { target, unwind, drop, .. } => {
2128 self.assert_iscleanup(block_data, target, is_cleanup);
2129 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2130 if let Some(drop) = drop {
2131 self.assert_iscleanup(block_data, drop, is_cleanup);
2132 }
2133 }
2134 TerminatorKind::Assert { target, unwind, .. } => {
2135 self.assert_iscleanup(block_data, target, is_cleanup);
2136 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2137 }
2138 TerminatorKind::Call { ref target, unwind, .. } => {
2139 if let &Some(target) = target {
2140 self.assert_iscleanup(block_data, target, is_cleanup);
2141 }
2142 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2143 }
2144 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
2145 self.assert_iscleanup(block_data, real_target, is_cleanup);
2146 self.assert_iscleanup(block_data, imaginary_target, is_cleanup);
2147 }
2148 TerminatorKind::FalseUnwind { real_target, unwind } => {
2149 self.assert_iscleanup(block_data, real_target, is_cleanup);
2150 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2151 }
2152 TerminatorKind::InlineAsm { ref targets, unwind, .. } => {
2153 for &target in targets {
2154 self.assert_iscleanup(block_data, target, is_cleanup);
2155 }
2156 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2157 }
2158 }
2159 }
2160
2161 fn assert_iscleanup(&mut self, ctxt: &dyn fmt::Debug, bb: BasicBlock, iscleanuppad: bool) {
2162 if self.body[bb].is_cleanup != iscleanuppad {
2163 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
2164 }
2165 }
2166
2167 fn assert_iscleanup_unwind(
2168 &mut self,
2169 ctxt: &dyn fmt::Debug,
2170 unwind: UnwindAction,
2171 is_cleanup: bool,
2172 ) {
2173 match unwind {
2174 UnwindAction::Cleanup(unwind) => {
2175 if is_cleanup {
2176 span_mirbug!(self, ctxt, "unwind on cleanup block")
2177 }
2178 self.assert_iscleanup(ctxt, unwind, true);
2179 }
2180 UnwindAction::Continue => {
2181 if is_cleanup {
2182 span_mirbug!(self, ctxt, "unwind on cleanup block")
2183 }
2184 }
2185 UnwindAction::Unreachable | UnwindAction::Terminate(_) => (),
2186 }
2187 }
2188
2189 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
2190 let tcx = self.tcx();
2191
2192 let erased_ty = tcx.erase_and_anonymize_regions(ty);
2196 if !erased_ty.is_sized(tcx, self.infcx.typing_env(self.infcx.param_env)) {
2198 if self.reported_errors.replace((ty, span)).is_none() {
2203 self.tcx().dcx().emit_err(MoveUnsized { ty, span });
2207 }
2208 }
2209 }
2210
2211 fn aggregate_field_ty(
2212 &mut self,
2213 ak: &AggregateKind<'tcx>,
2214 field_index: FieldIdx,
2215 location: Location,
2216 ) -> Result<Ty<'tcx>, FieldAccessError> {
2217 let tcx = self.tcx();
2218
2219 match *ak {
2220 AggregateKind::Adt(adt_did, variant_index, args, _, active_field_index) => {
2221 let def = tcx.adt_def(adt_did);
2222 let variant = &def.variant(variant_index);
2223 let adj_field_index = active_field_index.unwrap_or(field_index);
2224 if let Some(field) = variant.fields.get(adj_field_index) {
2225 Ok(self.normalize(field.ty(tcx, args), location))
2226 } else {
2227 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
2228 }
2229 }
2230 AggregateKind::Closure(_, args) => {
2231 match args.as_closure().upvar_tys().get(field_index.as_usize()) {
2232 Some(ty) => Ok(*ty),
2233 None => Err(FieldAccessError::OutOfRange {
2234 field_count: args.as_closure().upvar_tys().len(),
2235 }),
2236 }
2237 }
2238 AggregateKind::Coroutine(_, args) => {
2239 match args.as_coroutine().prefix_tys().get(field_index.as_usize()) {
2243 Some(ty) => Ok(*ty),
2244 None => Err(FieldAccessError::OutOfRange {
2245 field_count: args.as_coroutine().prefix_tys().len(),
2246 }),
2247 }
2248 }
2249 AggregateKind::CoroutineClosure(_, args) => {
2250 match args.as_coroutine_closure().upvar_tys().get(field_index.as_usize()) {
2251 Some(ty) => Ok(*ty),
2252 None => Err(FieldAccessError::OutOfRange {
2253 field_count: args.as_coroutine_closure().upvar_tys().len(),
2254 }),
2255 }
2256 }
2257 AggregateKind::Array(ty) => Ok(ty),
2258 AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2259 unreachable!("This should have been covered in check_rvalues");
2260 }
2261 }
2262 }
2263
2264 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2268 match rvalue {
2269 Rvalue::Use(_)
2270 | Rvalue::ThreadLocalRef(_)
2271 | Rvalue::Repeat(..)
2272 | Rvalue::Ref(..)
2273 | Rvalue::RawPtr(..)
2274 | Rvalue::Cast(..)
2275 | Rvalue::ShallowInitBox(..)
2276 | Rvalue::BinaryOp(..)
2277 | Rvalue::CopyForDeref(..)
2278 | Rvalue::UnaryOp(..)
2279 | Rvalue::Discriminant(..)
2280 | Rvalue::WrapUnsafeBinder(..) => None,
2281
2282 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2283 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2284 AggregateKind::Array(_) => None,
2285 AggregateKind::Tuple => None,
2286 AggregateKind::Closure(_, _) => None,
2287 AggregateKind::Coroutine(_, _) => None,
2288 AggregateKind::CoroutineClosure(_, _) => None,
2289 AggregateKind::RawPtr(_, _) => None,
2290 },
2291 }
2292 }
2293
2294 fn check_aggregate_rvalue(
2295 &mut self,
2296 rvalue: &Rvalue<'tcx>,
2297 aggregate_kind: &AggregateKind<'tcx>,
2298 operands: &IndexSlice<FieldIdx, Operand<'tcx>>,
2299 location: Location,
2300 ) {
2301 let tcx = self.tcx();
2302
2303 self.prove_aggregate_predicates(aggregate_kind, location);
2304
2305 if *aggregate_kind == AggregateKind::Tuple {
2306 return;
2308 }
2309
2310 if let AggregateKind::RawPtr(..) = aggregate_kind {
2311 bug!("RawPtr should only be in runtime MIR");
2312 }
2313
2314 for (i, operand) in operands.iter_enumerated() {
2315 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2316 Ok(field_ty) => field_ty,
2317 Err(FieldAccessError::OutOfRange { field_count }) => {
2318 span_mirbug!(
2319 self,
2320 rvalue,
2321 "accessed field #{} but variant only has {}",
2322 i.as_u32(),
2323 field_count,
2324 );
2325 continue;
2326 }
2327 };
2328 let operand_ty = operand.ty(self.body, tcx);
2329 let operand_ty = self.normalize(operand_ty, location);
2330
2331 if let Err(terr) = self.sub_types(
2332 operand_ty,
2333 field_ty,
2334 location.to_locations(),
2335 ConstraintCategory::Boring,
2336 ) {
2337 span_mirbug!(
2338 self,
2339 rvalue,
2340 "{:?} is not a subtype of {:?}: {:?}",
2341 operand_ty,
2342 field_ty,
2343 terr
2344 );
2345 }
2346 }
2347 }
2348
2349 fn add_reborrow_constraint(
2357 &mut self,
2358 location: Location,
2359 borrow_region: ty::Region<'tcx>,
2360 borrowed_place: &Place<'tcx>,
2361 ) {
2362 let Self { borrow_set, location_table, polonius_facts, constraints, .. } = self;
2364
2365 if let Some(polonius_facts) = polonius_facts {
2371 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2372 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2373 let region_vid = borrow_region.as_var();
2374 polonius_facts.loan_issued_at.push((
2375 region_vid.into(),
2376 borrow_index,
2377 location_table.mid_index(location),
2378 ));
2379 }
2380 }
2381
2382 debug!(
2388 "add_reborrow_constraint({:?}, {:?}, {:?})",
2389 location, borrow_region, borrowed_place
2390 );
2391
2392 let tcx = self.infcx.tcx;
2393 let def = self.body.source.def_id().expect_local();
2394 let upvars = tcx.closure_captures(def);
2395 let field =
2396 path_utils::is_upvar_field_projection(tcx, upvars, borrowed_place.as_ref(), self.body);
2397 let category = if let Some(field) = field {
2398 ConstraintCategory::ClosureUpvar(field)
2399 } else {
2400 ConstraintCategory::Boring
2401 };
2402
2403 for (base, elem) in borrowed_place.as_ref().iter_projections().rev() {
2404 debug!("add_reborrow_constraint - iteration {:?}", elem);
2405
2406 match elem {
2407 ProjectionElem::Deref => {
2408 let base_ty = base.ty(self.body, tcx).ty;
2409
2410 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2411 match base_ty.kind() {
2412 ty::Ref(ref_region, _, mutbl) => {
2413 constraints.outlives_constraints.push(OutlivesConstraint {
2414 sup: ref_region.as_var(),
2415 sub: borrow_region.as_var(),
2416 locations: location.to_locations(),
2417 span: location.to_locations().span(self.body),
2418 category,
2419 variance_info: ty::VarianceDiagInfo::default(),
2420 from_closure: false,
2421 });
2422
2423 match mutbl {
2424 hir::Mutability::Not => {
2425 break;
2429 }
2430 hir::Mutability::Mut => {
2431 }
2453 }
2454 }
2455 ty::RawPtr(..) => {
2456 break;
2458 }
2459 ty::Adt(def, _) if def.is_box() => {
2460 }
2462 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2463 }
2464 }
2465 ProjectionElem::Field(..)
2466 | ProjectionElem::Downcast(..)
2467 | ProjectionElem::OpaqueCast(..)
2468 | ProjectionElem::Index(..)
2469 | ProjectionElem::ConstantIndex { .. }
2470 | ProjectionElem::Subslice { .. }
2471 | ProjectionElem::UnwrapUnsafeBinder(_) => {
2472 }
2474 }
2475 }
2476 }
2477
2478 fn prove_aggregate_predicates(
2479 &mut self,
2480 aggregate_kind: &AggregateKind<'tcx>,
2481 location: Location,
2482 ) {
2483 let tcx = self.tcx();
2484
2485 debug!(
2486 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2487 aggregate_kind, location
2488 );
2489
2490 let (def_id, instantiated_predicates) = match *aggregate_kind {
2491 AggregateKind::Adt(adt_did, _, args, _, _) => {
2492 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, args))
2493 }
2494
2495 AggregateKind::Closure(def_id, args)
2515 | AggregateKind::CoroutineClosure(def_id, args)
2516 | AggregateKind::Coroutine(def_id, args) => (
2517 def_id,
2518 self.prove_closure_bounds(
2519 tcx,
2520 def_id.expect_local(),
2521 args,
2522 location.to_locations(),
2523 ),
2524 ),
2525
2526 AggregateKind::Array(_) | AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2527 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2528 }
2529 };
2530
2531 self.normalize_and_prove_instantiated_predicates(
2532 def_id,
2533 instantiated_predicates,
2534 location.to_locations(),
2535 );
2536 }
2537
2538 fn prove_closure_bounds(
2539 &mut self,
2540 tcx: TyCtxt<'tcx>,
2541 def_id: LocalDefId,
2542 args: GenericArgsRef<'tcx>,
2543 locations: Locations,
2544 ) -> ty::InstantiatedPredicates<'tcx> {
2545 let root_def_id = self.root_cx.root_def_id();
2546 self.deferred_closure_requirements.push((def_id, args, locations));
2549
2550 let typeck_root_args = ty::GenericArgs::identity_for_item(tcx, root_def_id);
2552
2553 let parent_args = match tcx.def_kind(def_id) {
2554 DefKind::Closure => {
2558 &args[..typeck_root_args.len()]
2562 }
2563 DefKind::InlineConst => args.as_inline_const().parent_args(),
2564 other => bug!("unexpected item {:?}", other),
2565 };
2566 let parent_args = tcx.mk_args(parent_args);
2567
2568 assert_eq!(typeck_root_args.len(), parent_args.len());
2569 if let Err(_) = self.eq_args(
2570 typeck_root_args,
2571 parent_args,
2572 locations,
2573 ConstraintCategory::BoringNoLocation,
2574 ) {
2575 span_mirbug!(
2576 self,
2577 def_id,
2578 "could not relate closure to parent {:?} != {:?}",
2579 typeck_root_args,
2580 parent_args
2581 );
2582 }
2583
2584 tcx.predicates_of(def_id).instantiate(tcx, args)
2585 }
2586}
2587
2588trait NormalizeLocation: fmt::Debug + Copy {
2589 fn to_locations(self) -> Locations;
2590}
2591
2592impl NormalizeLocation for Locations {
2593 fn to_locations(self) -> Locations {
2594 self
2595 }
2596}
2597
2598impl NormalizeLocation for Location {
2599 fn to_locations(self) -> Locations {
2600 Locations::Single(self)
2601 }
2602}
2603
2604#[derive(Debug)]
2608pub(super) struct InstantiateOpaqueType<'tcx> {
2609 pub base_universe: Option<ty::UniverseIndex>,
2610 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2611 pub obligations: PredicateObligations<'tcx>,
2612}
2613
2614impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2615 type Output = ();
2616 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2622
2623 fn fully_perform(
2624 mut self,
2625 infcx: &InferCtxt<'tcx>,
2626 root_def_id: LocalDefId,
2627 span: Span,
2628 ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed> {
2629 let (mut output, region_constraints) =
2630 scrape_region_constraints(infcx, root_def_id, "InstantiateOpaqueType", span, |ocx| {
2631 ocx.register_obligations(self.obligations.clone());
2632 Ok(())
2633 })?;
2634 self.region_constraints = Some(region_constraints);
2635 output.error_info = Some(self);
2636 Ok(output)
2637 }
2638}