1use rustc_abi::{ExternAbi, FIRST_VARIANT, Size};
4use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5use rustc_hir::LangItem;
6use rustc_hir::attrs::InlineAttr;
7use rustc_index::IndexVec;
8use rustc_index::bit_set::DenseBitSet;
9use rustc_infer::infer::TyCtxtInferExt;
10use rustc_infer::traits::{Obligation, ObligationCause};
11use rustc_middle::mir::coverage::CoverageKind;
12use rustc_middle::mir::visit::{MutatingUseContext, NonUseContext, PlaceContext, Visitor};
13use rustc_middle::mir::*;
14use rustc_middle::ty::adjustment::PointerCoercion;
15use rustc_middle::ty::print::with_no_trimmed_paths;
16use rustc_middle::ty::{
17 self, InstanceKind, ScalarInt, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast, Variance,
18};
19use rustc_middle::{bug, span_bug};
20use rustc_mir_dataflow::debuginfo::debuginfo_locals;
21use rustc_trait_selection::traits::ObligationCtxt;
22
23use crate::util::{self, most_packed_projection};
24
25#[derive(Copy, Clone, Debug, PartialEq, Eq)]
26enum EdgeKind {
27 Unwind,
28 Normal,
29}
30
31pub(super) struct Validator {
32 pub when: String,
34}
35
36impl<'tcx> crate::MirPass<'tcx> for Validator {
37 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
38 if matches!(body.source.instance, InstanceKind::Intrinsic(..) | InstanceKind::Virtual(..)) {
43 return;
44 }
45 let def_id = body.source.def_id();
46 let typing_env = body.typing_env(tcx);
47 let can_unwind = if body.phase <= MirPhase::Runtime(RuntimePhase::Initial) {
48 true
50 } else if !tcx.def_kind(def_id).is_fn_like() {
51 true
52 } else {
53 let body_ty = tcx.type_of(def_id).skip_binder();
54 let body_abi = match body_ty.kind() {
55 ty::FnDef(..) => body_ty.fn_sig(tcx).abi(),
56 ty::Closure(..) => ExternAbi::RustCall,
57 ty::CoroutineClosure(..) => ExternAbi::RustCall,
58 ty::Coroutine(..) => ExternAbi::Rust,
59 ty::Error(_) => return,
61 _ => span_bug!(body.span, "unexpected body ty: {body_ty}"),
62 };
63
64 ty::layout::fn_can_unwind(tcx, Some(def_id), body_abi)
65 };
66
67 let mut cfg_checker = CfgChecker {
68 when: &self.when,
69 body,
70 tcx,
71 unwind_edge_count: 0,
72 reachable_blocks: traversal::reachable_as_bitset(body),
73 value_cache: FxHashSet::default(),
74 can_unwind,
75 };
76 cfg_checker.visit_body(body);
77 cfg_checker.check_cleanup_control_flow();
78
79 for (location, msg) in validate_types(tcx, typing_env, body, body) {
81 cfg_checker.fail(location, msg);
82 }
83
84 for (location, msg) in validate_debuginfos(body) {
86 cfg_checker.fail(location, msg);
87 }
88
89 if let MirPhase::Runtime(_) = body.phase
90 && let ty::InstanceKind::Item(_) = body.source.instance
91 && body.has_free_regions()
92 {
93 cfg_checker.fail(
94 Location::START,
95 format!("Free regions in optimized {} MIR", body.phase.name()),
96 );
97 }
98 }
99
100 fn is_required(&self) -> bool {
101 true
102 }
103}
104
105struct CfgChecker<'a, 'tcx> {
112 when: &'a str,
113 body: &'a Body<'tcx>,
114 tcx: TyCtxt<'tcx>,
115 unwind_edge_count: usize,
116 reachable_blocks: DenseBitSet<BasicBlock>,
117 value_cache: FxHashSet<u128>,
118 can_unwind: bool,
121}
122
123impl<'a, 'tcx> CfgChecker<'a, 'tcx> {
124 #[track_caller]
125 fn fail(&self, location: Location, msg: impl AsRef<str>) {
126 if self.tcx.dcx().has_errors().is_none() {
128 span_bug!(
129 self.body.source_info(location).span,
130 "broken MIR in {:?} ({}) at {:?}:\n{}",
131 self.body.source.instance,
132 self.when,
133 location,
134 msg.as_ref(),
135 );
136 }
137 }
138
139 fn check_edge(&mut self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) {
140 if bb == START_BLOCK {
141 self.fail(location, "start block must not have predecessors")
142 }
143 if let Some(bb) = self.body.basic_blocks.get(bb) {
144 let src = self.body.basic_blocks.get(location.block).unwrap();
145 match (src.is_cleanup, bb.is_cleanup, edge_kind) {
146 (false, false, EdgeKind::Normal) => {}
148 (true, true, EdgeKind::Normal) => {}
150 (false, true, EdgeKind::Unwind) => {
152 self.unwind_edge_count += 1;
153 }
154 _ => self.fail(
156 location,
157 format!(
158 "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})",
159 edge_kind, bb, src.is_cleanup, bb.is_cleanup,
160 ),
161 ),
162 }
163 } else {
164 self.fail(location, format!("encountered jump to invalid basic block {bb:?}"))
165 }
166 }
167
168 fn check_cleanup_control_flow(&self) {
169 if self.unwind_edge_count <= 1 {
170 return;
171 }
172 let doms = self.body.basic_blocks.dominators();
173 let mut post_contract_node = FxHashMap::default();
174 let mut dom_path = vec![];
176 let mut get_post_contract_node = |mut bb| {
177 let root = loop {
178 if let Some(root) = post_contract_node.get(&bb) {
179 break *root;
180 }
181 let parent = doms.immediate_dominator(bb).unwrap();
182 dom_path.push(bb);
183 if !self.body.basic_blocks[parent].is_cleanup {
184 break bb;
185 }
186 bb = parent;
187 };
188 for bb in dom_path.drain(..) {
189 post_contract_node.insert(bb, root);
190 }
191 root
192 };
193
194 let mut parent = IndexVec::from_elem(None, &self.body.basic_blocks);
195 for (bb, bb_data) in self.body.basic_blocks.iter_enumerated() {
196 if !bb_data.is_cleanup || !self.reachable_blocks.contains(bb) {
197 continue;
198 }
199 let bb = get_post_contract_node(bb);
200 for s in bb_data.terminator().successors() {
201 let s = get_post_contract_node(s);
202 if s == bb {
203 continue;
204 }
205 let parent = &mut parent[bb];
206 match parent {
207 None => {
208 *parent = Some(s);
209 }
210 Some(e) if *e == s => (),
211 Some(e) => self.fail(
212 Location { block: bb, statement_index: 0 },
213 format!(
214 "Cleanup control flow violation: The blocks dominated by {:?} have edges to both {:?} and {:?}",
215 bb,
216 s,
217 *e
218 )
219 ),
220 }
221 }
222 }
223
224 let mut stack = FxHashSet::default();
226 for (mut bb, parent) in parent.iter_enumerated_mut() {
227 stack.clear();
228 stack.insert(bb);
229 loop {
230 let Some(parent) = parent.take() else { break };
231 let no_cycle = stack.insert(parent);
232 if !no_cycle {
233 self.fail(
234 Location { block: bb, statement_index: 0 },
235 format!(
236 "Cleanup control flow violation: Cycle involving edge {bb:?} -> {parent:?}",
237 ),
238 );
239 break;
240 }
241 bb = parent;
242 }
243 }
244 }
245
246 fn check_unwind_edge(&mut self, location: Location, unwind: UnwindAction) {
247 let is_cleanup = self.body.basic_blocks[location.block].is_cleanup;
248 match unwind {
249 UnwindAction::Cleanup(unwind) => {
250 if is_cleanup {
251 self.fail(location, "`UnwindAction::Cleanup` in cleanup block");
252 }
253 self.check_edge(location, unwind, EdgeKind::Unwind);
254 }
255 UnwindAction::Continue => {
256 if is_cleanup {
257 self.fail(location, "`UnwindAction::Continue` in cleanup block");
258 }
259
260 if !self.can_unwind {
261 self.fail(location, "`UnwindAction::Continue` in no-unwind function");
262 }
263 }
264 UnwindAction::Terminate(UnwindTerminateReason::InCleanup) => {
265 if !is_cleanup {
266 self.fail(
267 location,
268 "`UnwindAction::Terminate(InCleanup)` in a non-cleanup block",
269 );
270 }
271 }
272 UnwindAction::Unreachable | UnwindAction::Terminate(UnwindTerminateReason::Abi) => (),
274 }
275 }
276
277 fn is_critical_call_edge(&self, target: Option<BasicBlock>, unwind: UnwindAction) -> bool {
278 let Some(target) = target else { return false };
279 matches!(unwind, UnwindAction::Cleanup(_) | UnwindAction::Terminate(_))
280 && self.body.basic_blocks.predecessors()[target].len() > 1
281 }
282}
283
284impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
285 fn visit_local(&mut self, local: Local, _context: PlaceContext, location: Location) {
286 if self.body.local_decls.get(local).is_none() {
287 self.fail(
288 location,
289 format!("local {local:?} has no corresponding declaration in `body.local_decls`"),
290 );
291 }
292 }
293
294 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
295 match &statement.kind {
296 StatementKind::AscribeUserType(..) => {
297 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
298 self.fail(
299 location,
300 "`AscribeUserType` should have been removed after drop lowering phase",
301 );
302 }
303 }
304 StatementKind::FakeRead(..) => {
305 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
306 self.fail(
307 location,
308 "`FakeRead` should have been removed after drop lowering phase",
309 );
310 }
311 }
312 StatementKind::SetDiscriminant { .. } => {
313 if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial) {
314 self.fail(location, "`SetDiscriminant`is not allowed until deaggregation");
315 }
316 }
317 StatementKind::Coverage(kind) => {
318 if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup)
319 && let CoverageKind::BlockMarker { .. } | CoverageKind::SpanMarker { .. } = kind
320 {
321 self.fail(
322 location,
323 format!("{kind:?} should have been removed after analysis"),
324 );
325 }
326 }
327 StatementKind::Assign(..)
328 | StatementKind::StorageLive(_)
329 | StatementKind::StorageDead(_)
330 | StatementKind::Intrinsic(_)
331 | StatementKind::ConstEvalCounter
332 | StatementKind::PlaceMention(..)
333 | StatementKind::BackwardIncompatibleDropHint { .. }
334 | StatementKind::Nop => {}
335 }
336
337 self.super_statement(statement, location);
338 }
339
340 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
341 match &terminator.kind {
342 TerminatorKind::Goto { target } => {
343 self.check_edge(location, *target, EdgeKind::Normal);
344 }
345 TerminatorKind::SwitchInt { targets, discr: _ } => {
346 for (_, target) in targets.iter() {
347 self.check_edge(location, target, EdgeKind::Normal);
348 }
349 self.check_edge(location, targets.otherwise(), EdgeKind::Normal);
350
351 self.value_cache.clear();
352 self.value_cache.extend(targets.iter().map(|(value, _)| value));
353 let has_duplicates = targets.iter().len() != self.value_cache.len();
354 if has_duplicates {
355 self.fail(
356 location,
357 format!(
358 "duplicated values in `SwitchInt` terminator: {:?}",
359 terminator.kind,
360 ),
361 );
362 }
363 }
364 TerminatorKind::Drop { target, unwind, drop, .. } => {
365 self.check_edge(location, *target, EdgeKind::Normal);
366 self.check_unwind_edge(location, *unwind);
367 if let Some(drop) = drop {
368 self.check_edge(location, *drop, EdgeKind::Normal);
369 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
370 self.fail(
371 location,
372 "`async drop` should have been removed after drop elaboration",
373 );
374 }
375 }
376 }
377 TerminatorKind::Call { func, args, .. }
378 | TerminatorKind::TailCall { func, args, .. } => {
379 if let TerminatorKind::Call { target, unwind, destination, .. } = terminator.kind {
381 if let Some(target) = target {
382 self.check_edge(location, target, EdgeKind::Normal);
383 }
384 self.check_unwind_edge(location, unwind);
385
386 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Optimized)
392 && self.is_critical_call_edge(target, unwind)
393 {
394 self.fail(
395 location,
396 format!(
397 "encountered critical edge in `Call` terminator {:?}",
398 terminator.kind,
399 ),
400 );
401 }
402
403 if most_packed_projection(self.tcx, &self.body.local_decls, destination)
406 .is_some()
407 {
408 self.fail(
410 location,
411 format!(
412 "encountered packed place in `Call` terminator destination: {:?}",
413 terminator.kind,
414 ),
415 );
416 }
417 }
418
419 for arg in args {
420 if let Operand::Move(place) = &arg.node {
421 if most_packed_projection(self.tcx, &self.body.local_decls, *place)
422 .is_some()
423 {
424 self.fail(
426 location,
427 format!(
428 "encountered `Move` of a packed place in `Call` terminator: {:?}",
429 terminator.kind,
430 ),
431 );
432 }
433 }
434 }
435
436 if let ty::FnDef(did, ..) = *func.ty(&self.body.local_decls, self.tcx).kind()
437 && self.body.phase >= MirPhase::Runtime(RuntimePhase::Optimized)
438 && matches!(self.tcx.codegen_fn_attrs(did).inline, InlineAttr::Force { .. })
439 {
440 self.fail(location, "`#[rustc_force_inline]`-annotated function not inlined");
441 }
442 }
443 TerminatorKind::Assert { target, unwind, .. } => {
444 self.check_edge(location, *target, EdgeKind::Normal);
445 self.check_unwind_edge(location, *unwind);
446 }
447 TerminatorKind::Yield { resume, drop, .. } => {
448 if self.body.coroutine.is_none() {
449 self.fail(location, "`Yield` cannot appear outside coroutine bodies");
450 }
451 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
452 self.fail(location, "`Yield` should have been replaced by coroutine lowering");
453 }
454 self.check_edge(location, *resume, EdgeKind::Normal);
455 if let Some(drop) = drop {
456 self.check_edge(location, *drop, EdgeKind::Normal);
457 }
458 }
459 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
460 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
461 self.fail(
462 location,
463 "`FalseEdge` should have been removed after drop elaboration",
464 );
465 }
466 self.check_edge(location, *real_target, EdgeKind::Normal);
467 self.check_edge(location, *imaginary_target, EdgeKind::Normal);
468 }
469 TerminatorKind::FalseUnwind { real_target, unwind } => {
470 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
471 self.fail(
472 location,
473 "`FalseUnwind` should have been removed after drop elaboration",
474 );
475 }
476 self.check_edge(location, *real_target, EdgeKind::Normal);
477 self.check_unwind_edge(location, *unwind);
478 }
479 TerminatorKind::InlineAsm { targets, unwind, .. } => {
480 for &target in targets {
481 self.check_edge(location, target, EdgeKind::Normal);
482 }
483 self.check_unwind_edge(location, *unwind);
484 }
485 TerminatorKind::CoroutineDrop => {
486 if self.body.coroutine.is_none() {
487 self.fail(location, "`CoroutineDrop` cannot appear outside coroutine bodies");
488 }
489 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
490 self.fail(
491 location,
492 "`CoroutineDrop` should have been replaced by coroutine lowering",
493 );
494 }
495 }
496 TerminatorKind::UnwindResume => {
497 let bb = location.block;
498 if !self.body.basic_blocks[bb].is_cleanup {
499 self.fail(location, "Cannot `UnwindResume` from non-cleanup basic block")
500 }
501 if !self.can_unwind {
502 self.fail(location, "Cannot `UnwindResume` in a function that cannot unwind")
503 }
504 }
505 TerminatorKind::UnwindTerminate(_) => {
506 let bb = location.block;
507 if !self.body.basic_blocks[bb].is_cleanup {
508 self.fail(location, "Cannot `UnwindTerminate` from non-cleanup basic block")
509 }
510 }
511 TerminatorKind::Return => {
512 let bb = location.block;
513 if self.body.basic_blocks[bb].is_cleanup {
514 self.fail(location, "Cannot `Return` from cleanup basic block")
515 }
516 }
517 TerminatorKind::Unreachable => {}
518 }
519
520 self.super_terminator(terminator, location);
521 }
522
523 fn visit_source_scope(&mut self, scope: SourceScope) {
524 if self.body.source_scopes.get(scope).is_none() {
525 self.tcx.dcx().span_bug(
526 self.body.span,
527 format!(
528 "broken MIR in {:?} ({}):\ninvalid source scope {:?}",
529 self.body.source.instance, self.when, scope,
530 ),
531 );
532 }
533 }
534}
535
536pub(super) fn validate_types<'tcx>(
542 tcx: TyCtxt<'tcx>,
543 typing_env: ty::TypingEnv<'tcx>,
544 body: &Body<'tcx>,
545 caller_body: &Body<'tcx>,
546) -> Vec<(Location, String)> {
547 let mut type_checker = TypeChecker { body, caller_body, tcx, typing_env, failures: Vec::new() };
548 with_no_trimmed_paths!({
553 type_checker.visit_body(body);
554 });
555 type_checker.failures
556}
557
558struct TypeChecker<'a, 'tcx> {
559 body: &'a Body<'tcx>,
560 caller_body: &'a Body<'tcx>,
561 tcx: TyCtxt<'tcx>,
562 typing_env: ty::TypingEnv<'tcx>,
563 failures: Vec<(Location, String)>,
564}
565
566impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
567 fn fail(&mut self, location: Location, msg: impl Into<String>) {
568 self.failures.push((location, msg.into()));
569 }
570
571 fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
574 if src == dest {
576 return true;
578 }
579
580 if (src, dest).has_opaque_types() {
586 return true;
587 }
588
589 let variance = if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
592 Variance::Invariant
593 } else {
594 Variance::Covariant
595 };
596
597 crate::util::relate_types(self.tcx, self.typing_env, variance, src, dest)
598 }
599
600 fn predicate_must_hold_modulo_regions(
602 &self,
603 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
604 ) -> bool {
605 let pred: ty::Predicate<'tcx> = pred.upcast(self.tcx);
606
607 if pred.has_opaque_types() {
613 return true;
614 }
615
616 let (infcx, param_env) = self.tcx.infer_ctxt().build_with_typing_env(self.typing_env);
617 let ocx = ObligationCtxt::new(&infcx);
618 ocx.register_obligation(Obligation::new(
619 self.tcx,
620 ObligationCause::dummy(),
621 param_env,
622 pred,
623 ));
624 ocx.evaluate_obligations_error_on_ambiguity().is_empty()
625 }
626}
627
628impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
629 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
630 if self.tcx.sess.opts.unstable_opts.validate_mir
632 && self.body.phase < MirPhase::Runtime(RuntimePhase::Initial)
633 {
634 if let Operand::Copy(place) = operand {
636 let ty = place.ty(&self.body.local_decls, self.tcx).ty;
637
638 if !self.tcx.type_is_copy_modulo_regions(self.typing_env, ty) {
639 self.fail(location, format!("`Operand::Copy` with non-`Copy` type {ty}"));
640 }
641 }
642 }
643
644 self.super_operand(operand, location);
645 }
646
647 fn visit_projection_elem(
648 &mut self,
649 place_ref: PlaceRef<'tcx>,
650 elem: PlaceElem<'tcx>,
651 context: PlaceContext,
652 location: Location,
653 ) {
654 match elem {
655 ProjectionElem::Deref
656 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) =>
657 {
658 let base_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
659
660 if base_ty.is_box() {
661 self.fail(location, format!("{base_ty} dereferenced after ElaborateBoxDerefs"))
662 }
663 }
664 ProjectionElem::Field(f, ty) => {
665 let parent_ty = place_ref.ty(&self.body.local_decls, self.tcx);
666 let fail_out_of_bounds = |this: &mut Self, location| {
667 this.fail(location, format!("Out of bounds field {f:?} for {parent_ty:?}"));
668 };
669 let check_equal = |this: &mut Self, location, f_ty| {
670 if !this.mir_assign_valid_types(ty, f_ty) {
671 this.fail(
672 location,
673 format!(
674 "Field projection `{place_ref:?}.{f:?}` specified type `{ty}`, but actual type is `{f_ty}`"
675 )
676 )
677 }
678 };
679
680 let kind = match parent_ty.ty.kind() {
681 &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
682 self.tcx.type_of(def_id).instantiate(self.tcx, args).skip_norm_wip().kind()
683 }
684 kind => kind,
685 };
686
687 match kind {
688 ty::Tuple(fields) => {
689 let Some(f_ty) = fields.get(f.as_usize()) else {
690 fail_out_of_bounds(self, location);
691 return;
692 };
693 check_equal(self, location, *f_ty);
694 }
695 ty::Pat(base, _) => check_equal(self, location, *base),
697 ty::Adt(adt_def, args) => {
698 if self.tcx.is_lang_item(adt_def.did(), LangItem::DynMetadata) {
700 self.fail(
701 location,
702 format!(
703 "You can't project to field {f:?} of `DynMetadata` because \
704 layout is weird and thinks it doesn't have fields."
705 ),
706 );
707 }
708
709 if adt_def.repr().simd() {
710 self.fail(
711 location,
712 format!(
713 "Projecting into SIMD type {adt_def:?} is banned by MCP#838"
714 ),
715 );
716 }
717
718 let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT);
719 let Some(field) = adt_def.variant(var).fields.get(f) else {
720 fail_out_of_bounds(self, location);
721 return;
722 };
723 check_equal(self, location, field.ty(self.tcx, args).skip_norm_wip());
724 }
725 ty::Closure(_, args) => {
726 let args = args.as_closure();
727 let Some(&f_ty) = args.upvar_tys().get(f.as_usize()) else {
728 fail_out_of_bounds(self, location);
729 return;
730 };
731 check_equal(self, location, f_ty);
732 }
733 ty::CoroutineClosure(_, args) => {
734 let args = args.as_coroutine_closure();
735 let Some(&f_ty) = args.upvar_tys().get(f.as_usize()) else {
736 fail_out_of_bounds(self, location);
737 return;
738 };
739 check_equal(self, location, f_ty);
740 }
741 &ty::Coroutine(def_id, args) => {
742 let f_ty = if let Some(var) = parent_ty.variant_index {
743 let layout = if def_id == self.caller_body.source.def_id() {
749 self.caller_body
750 .coroutine_layout_raw()
751 .or_else(|| self.tcx.coroutine_layout(def_id, args).ok())
752 } else if self.tcx.needs_coroutine_by_move_body_def_id(def_id)
753 && let ty::ClosureKind::FnOnce =
754 args.as_coroutine().kind_ty().to_opt_closure_kind().unwrap()
755 && self.caller_body.source.def_id()
756 == self.tcx.coroutine_by_move_body_def_id(def_id)
757 {
758 self.caller_body.coroutine_layout_raw()
760 } else {
761 self.tcx.coroutine_layout(def_id, args).ok()
762 };
763
764 let Some(layout) = layout else {
765 self.fail(
766 location,
767 format!("No coroutine layout for {parent_ty:?}"),
768 );
769 return;
770 };
771
772 let Some(&local) = layout.variant_fields[var].get(f) else {
773 fail_out_of_bounds(self, location);
774 return;
775 };
776
777 let Some(f_ty) = layout.field_tys.get(local) else {
778 self.fail(
779 location,
780 format!("Out of bounds local {local:?} for {parent_ty:?}"),
781 );
782 return;
783 };
784
785 ty::EarlyBinder::bind(self.tcx, f_ty.ty)
786 .instantiate(self.tcx, args)
787 .skip_norm_wip()
788 } else if let Some(&f_ty) = args.as_coroutine().upvar_tys().get(f.index()) {
789 f_ty
790 } else {
791 fail_out_of_bounds(self, location);
792 return;
793 };
794
795 check_equal(self, location, f_ty);
796 }
797 _ => {
798 self.fail(location, format!("{:?} does not have fields", parent_ty.ty));
799 }
800 }
801 }
802 ProjectionElem::Index(index) => {
803 let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
804 match indexed_ty.kind() {
805 ty::Array(_, _) | ty::Slice(_) => {}
806 _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
807 }
808
809 let index_ty = self.body.local_decls[index].ty;
810 if index_ty != self.tcx.types.usize {
811 self.fail(location, format!("bad index ({index_ty} != usize)"))
812 }
813 }
814 ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
815 let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
816 match indexed_ty.kind() {
817 ty::Array(_, _) => {
818 if from_end {
819 self.fail(location, "arrays should not be indexed from end");
820 }
821 }
822 ty::Slice(_) => {}
823 _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
824 }
825
826 if from_end {
827 if offset > min_length {
828 self.fail(
829 location,
830 format!(
831 "constant index with offset -{offset} out of bounds of min length {min_length}"
832 ),
833 );
834 }
835 } else {
836 if offset >= min_length {
837 self.fail(
838 location,
839 format!(
840 "constant index with offset {offset} out of bounds of min length {min_length}"
841 ),
842 );
843 }
844 }
845 }
846 ProjectionElem::Subslice { from, to, from_end } => {
847 let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
848 match indexed_ty.kind() {
849 ty::Array(_, _) => {
850 if from_end {
851 self.fail(location, "arrays should not be subsliced from end");
852 }
853 }
854 ty::Slice(_) => {
855 if !from_end {
856 self.fail(location, "slices should be subsliced from end");
857 }
858 }
859 _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
860 }
861
862 if !from_end && from > to {
863 self.fail(location, "backwards subslice {from}..{to}");
864 }
865 }
866 ProjectionElem::OpaqueCast(ty)
867 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) =>
868 {
869 self.fail(
870 location,
871 format!("explicit opaque type cast to `{ty}` after `PostAnalysisNormalize`"),
872 )
873 }
874 ProjectionElem::UnwrapUnsafeBinder(unwrapped_ty) => {
875 let binder_ty = place_ref.ty(&self.body.local_decls, self.tcx);
876 let ty::UnsafeBinder(binder_ty) = *binder_ty.ty.kind() else {
877 self.fail(
878 location,
879 format!("WrapUnsafeBinder does not produce a ty::UnsafeBinder"),
880 );
881 return;
882 };
883 let binder_inner_ty = self.tcx.instantiate_bound_regions_with_erased(*binder_ty);
884 if !self.mir_assign_valid_types(unwrapped_ty, binder_inner_ty) {
885 self.fail(
886 location,
887 format!(
888 "Cannot unwrap unsafe binder {binder_ty:?} into type {unwrapped_ty}"
889 ),
890 );
891 }
892 }
893 _ => {}
894 }
895 self.super_projection_elem(place_ref, elem, context, location);
896 }
897
898 fn visit_var_debug_info(&mut self, debuginfo: &VarDebugInfo<'tcx>) {
899 if let Some(VarDebugInfoFragment { ty, ref projection }) = debuginfo.composite {
900 if ty.is_union() || ty.is_enum() {
901 self.fail(
902 START_BLOCK.start_location(),
903 format!("invalid type {ty} in debuginfo for {:?}", debuginfo.name),
904 );
905 }
906 if projection.is_empty() {
907 self.fail(
908 START_BLOCK.start_location(),
909 format!("invalid empty projection in debuginfo for {:?}", debuginfo.name),
910 );
911 }
912 if projection.iter().any(|p| !matches!(p, PlaceElem::Field(..))) {
913 self.fail(
914 START_BLOCK.start_location(),
915 format!(
916 "illegal projection {:?} in debuginfo for {:?}",
917 projection, debuginfo.name
918 ),
919 );
920 }
921 }
922 match debuginfo.value {
923 VarDebugInfoContents::Const(_) => {}
924 VarDebugInfoContents::Place(place) => {
925 if place.projection.iter().any(|p| !p.can_use_in_debuginfo()) {
926 self.fail(
927 START_BLOCK.start_location(),
928 format!("illegal place {:?} in debuginfo for {:?}", place, debuginfo.name),
929 );
930 }
931 }
932 }
933 self.super_var_debug_info(debuginfo);
934 }
935
936 fn visit_place(&mut self, place: &Place<'tcx>, cntxt: PlaceContext, location: Location) {
937 let _ = place.ty(&self.body.local_decls, self.tcx);
939
940 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial)
941 && place.projection.len() > 1
942 && cntxt != PlaceContext::NonUse(NonUseContext::VarDebugInfo)
943 && place.projection[1..].contains(&ProjectionElem::Deref)
944 {
945 self.fail(
946 location,
947 format!("place {place:?} has deref as a later projection (it is only permitted as the first projection)"),
948 );
949 }
950
951 let mut projections_iter = place.projection.iter();
953 while let Some(proj) = projections_iter.next() {
954 if matches!(proj, ProjectionElem::Downcast(..)) {
955 if !matches!(projections_iter.next(), Some(ProjectionElem::Field(..))) {
956 self.fail(
957 location,
958 format!(
959 "place {place:?} has `Downcast` projection not followed by `Field`"
960 ),
961 );
962 }
963 }
964 }
965
966 if let ClearCrossCrate::Set(LocalInfo::DerefTemp) =
967 self.body.local_decls[place.local].local_info
968 && !place.is_indirect_first_projection()
969 {
970 if cntxt != PlaceContext::MutatingUse(MutatingUseContext::Store)
971 || place.as_local().is_none()
972 {
973 self.fail(
974 location,
975 format!("`DerefTemp` locals must only be dereferenced or directly assigned to"),
976 );
977 }
978 }
979
980 if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial)
981 && let Some(i) = place
982 .projection
983 .iter()
984 .position(|elem| matches!(elem, ProjectionElem::Subslice { .. }))
985 && let Some(tail) = place.projection.get(i + 1..)
986 && tail.iter().any(|elem| {
987 matches!(
988 elem,
989 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. }
990 )
991 })
992 {
993 self.fail(
994 location,
995 format!("place {place:?} has `ConstantIndex` or `Subslice` after `Subslice`"),
996 );
997 }
998
999 self.super_place(place, cntxt, location);
1000 }
1001
1002 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1003 macro_rules! check_kinds {
1004 ($t:expr, $text:literal, $typat:pat) => {
1005 if !matches!(($t).kind(), $typat) {
1006 self.fail(location, format!($text, $t));
1007 }
1008 };
1009 }
1010 match rvalue {
1011 Rvalue::Use(_, _) => {}
1012 Rvalue::CopyForDeref(_) => {
1013 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1014 self.fail(location, "`CopyForDeref` should have been removed in runtime MIR");
1015 }
1016 }
1017 Rvalue::Aggregate(kind, fields) => match **kind {
1018 AggregateKind::Tuple => {}
1019 AggregateKind::Array(dest) => {
1020 for src in fields {
1021 if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1022 self.fail(location, "array field has the wrong type");
1023 }
1024 }
1025 }
1026 AggregateKind::Adt(def_id, idx, args, _, Some(field)) => {
1027 let adt_def = self.tcx.adt_def(def_id);
1028 assert!(adt_def.is_union());
1029 assert_eq!(idx, FIRST_VARIANT);
1030 let dest_ty = self.tcx.normalize_erasing_regions(
1031 self.typing_env,
1032 adt_def.non_enum_variant().fields[field].ty(self.tcx, args),
1033 );
1034 if let [field] = fields.raw.as_slice() {
1035 let src_ty = field.ty(self.body, self.tcx);
1036 if !self.mir_assign_valid_types(src_ty, dest_ty) {
1037 self.fail(location, "union field has the wrong type");
1038 }
1039 } else {
1040 self.fail(location, "unions should have one initialized field");
1041 }
1042 }
1043 AggregateKind::Adt(def_id, idx, args, _, None) => {
1044 let adt_def = self.tcx.adt_def(def_id);
1045 assert!(!adt_def.is_union());
1046 let variant = &adt_def.variants()[idx];
1047 if variant.fields.len() != fields.len() {
1048 self.fail(location, format!(
1049 "adt {def_id:?} has the wrong number of initialized fields, expected {}, found {}",
1050 fields.len(),
1051 variant.fields.len(),
1052 ));
1053 }
1054 for (src, dest) in std::iter::zip(fields, &variant.fields) {
1055 let dest_ty = self
1056 .tcx
1057 .normalize_erasing_regions(self.typing_env, dest.ty(self.tcx, args));
1058 if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest_ty) {
1059 self.fail(location, "adt field has the wrong type");
1060 }
1061 }
1062 }
1063 AggregateKind::Closure(_, args) => {
1064 let upvars = args.as_closure().upvar_tys();
1065 if upvars.len() != fields.len() {
1066 self.fail(location, "closure has the wrong number of initialized fields");
1067 }
1068 for (src, dest) in std::iter::zip(fields, upvars) {
1069 if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1070 self.fail(location, "closure field has the wrong type");
1071 }
1072 }
1073 }
1074 AggregateKind::Coroutine(_, args) => {
1075 let upvars = args.as_coroutine().upvar_tys();
1076 if upvars.len() != fields.len() {
1077 self.fail(location, "coroutine has the wrong number of initialized fields");
1078 }
1079 for (src, dest) in std::iter::zip(fields, upvars) {
1080 if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1081 self.fail(location, "coroutine field has the wrong type");
1082 }
1083 }
1084 }
1085 AggregateKind::CoroutineClosure(_, args) => {
1086 let upvars = args.as_coroutine_closure().upvar_tys();
1087 if upvars.len() != fields.len() {
1088 self.fail(
1089 location,
1090 "coroutine-closure has the wrong number of initialized fields",
1091 );
1092 }
1093 for (src, dest) in std::iter::zip(fields, upvars) {
1094 if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1095 self.fail(location, "coroutine-closure field has the wrong type");
1096 }
1097 }
1098 }
1099 AggregateKind::RawPtr(pointee_ty, mutability) => {
1100 if !matches!(self.body.phase, MirPhase::Runtime(_)) {
1101 self.fail(location, "RawPtr should be in runtime MIR only");
1105 }
1106
1107 if let [data_ptr, metadata] = fields.raw.as_slice() {
1108 let data_ptr_ty = data_ptr.ty(self.body, self.tcx);
1109 let metadata_ty = metadata.ty(self.body, self.tcx);
1110 if let ty::RawPtr(in_pointee, in_mut) = data_ptr_ty.kind() {
1111 if *in_mut != mutability {
1112 self.fail(location, "input and output mutability must match");
1113 }
1114
1115 if !in_pointee.is_sized(self.tcx, self.typing_env) {
1117 self.fail(location, "input pointer must be thin");
1118 }
1119 } else {
1120 self.fail(
1121 location,
1122 "first operand to raw pointer aggregate must be a raw pointer",
1123 );
1124 }
1125
1126 if pointee_ty.is_slice() {
1128 if !self.mir_assign_valid_types(metadata_ty, self.tcx.types.usize) {
1129 self.fail(location, "slice metadata must be usize");
1130 }
1131 } else if pointee_ty.is_sized(self.tcx, self.typing_env) {
1132 if metadata_ty != self.tcx.types.unit {
1133 self.fail(location, "metadata for pointer-to-thin must be unit");
1134 }
1135 }
1136 } else {
1137 self.fail(location, "raw pointer aggregate must have 2 fields");
1138 }
1139 }
1140 },
1141 Rvalue::Ref(_, BorrowKind::Fake(_), _) => {
1142 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1143 self.fail(
1144 location,
1145 "`Assign` statement with a `Fake` borrow should have been removed in runtime MIR",
1146 );
1147 }
1148 }
1149 Rvalue::Ref(..) | Rvalue::Reborrow(..) => {}
1150 Rvalue::BinaryOp(op, vals) => {
1151 use BinOp::*;
1152 let a = vals.0.ty(&self.body.local_decls, self.tcx);
1153 let b = vals.1.ty(&self.body.local_decls, self.tcx);
1154 if crate::util::binop_right_homogeneous(*op) {
1155 if let Eq | Lt | Le | Ne | Ge | Gt = op {
1156 if !self.mir_assign_valid_types(a, b) {
1158 self.fail(
1159 location,
1160 format!("Cannot {op:?} compare incompatible types {a} and {b}"),
1161 );
1162 }
1163 } else if a != b {
1164 self.fail(
1165 location,
1166 format!("Cannot perform binary op {op:?} on unequal types {a} and {b}"),
1167 );
1168 }
1169 }
1170
1171 match op {
1172 Offset => {
1173 check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..));
1174 if b != self.tcx.types.isize && b != self.tcx.types.usize {
1175 self.fail(location, format!("Cannot offset by non-isize type {b}"));
1176 }
1177 }
1178 Eq | Lt | Le | Ne | Ge | Gt => {
1179 for x in [a, b] {
1180 check_kinds!(
1181 x,
1182 "Cannot {op:?} compare type {:?}",
1183 ty::Bool
1184 | ty::Char
1185 | ty::Int(..)
1186 | ty::Uint(..)
1187 | ty::Float(..)
1188 | ty::RawPtr(..)
1189 | ty::FnPtr(..)
1190 )
1191 }
1192 }
1193 Cmp => {
1194 for x in [a, b] {
1195 check_kinds!(
1196 x,
1197 "Cannot three-way compare non-integer type {:?}",
1198 ty::Char | ty::Uint(..) | ty::Int(..)
1199 )
1200 }
1201 }
1202 AddUnchecked | AddWithOverflow | SubUnchecked | SubWithOverflow
1203 | MulUnchecked | MulWithOverflow | Shl | ShlUnchecked | Shr | ShrUnchecked => {
1204 for x in [a, b] {
1205 check_kinds!(
1206 x,
1207 "Cannot {op:?} non-integer type {:?}",
1208 ty::Uint(..) | ty::Int(..)
1209 )
1210 }
1211 }
1212 BitAnd | BitOr | BitXor => {
1213 for x in [a, b] {
1214 check_kinds!(
1215 x,
1216 "Cannot perform bitwise op {op:?} on type {:?}",
1217 ty::Uint(..) | ty::Int(..) | ty::Bool
1218 )
1219 }
1220 }
1221 Add | Sub | Mul | Div | Rem => {
1222 for x in [a, b] {
1223 check_kinds!(
1224 x,
1225 "Cannot perform arithmetic {op:?} on type {:?}",
1226 ty::Uint(..) | ty::Int(..) | ty::Float(..)
1227 )
1228 }
1229 }
1230 }
1231 }
1232 Rvalue::UnaryOp(op, operand) => {
1233 let a = operand.ty(&self.body.local_decls, self.tcx);
1234 match op {
1235 UnOp::Neg => {
1236 check_kinds!(a, "Cannot negate type {:?}", ty::Int(..) | ty::Float(..))
1237 }
1238 UnOp::Not => {
1239 check_kinds!(
1240 a,
1241 "Cannot binary not type {:?}",
1242 ty::Int(..) | ty::Uint(..) | ty::Bool
1243 );
1244 }
1245 UnOp::PtrMetadata => {
1246 check_kinds!(
1247 a,
1248 "Cannot PtrMetadata non-pointer non-reference type {:?}",
1249 ty::RawPtr(..) | ty::Ref(..)
1250 );
1251 }
1252 }
1253 }
1254 Rvalue::Cast(kind, operand, target_type) => {
1255 let op_ty = operand.ty(self.body, self.tcx);
1256 match kind {
1257 CastKind::PointerWithExposedProvenance | CastKind::PointerExposeProvenance => {}
1259 CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
1260 check_kinds!(
1262 op_ty,
1263 "CastKind::{kind:?} input must be a fn item, not {:?}",
1264 ty::FnDef(..)
1265 );
1266 check_kinds!(
1267 target_type,
1268 "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1269 ty::FnPtr(..)
1270 );
1271 }
1272 CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
1273 check_kinds!(
1275 op_ty,
1276 "CastKind::{kind:?} input must be a fn pointer, not {:?}",
1277 ty::FnPtr(..)
1278 );
1279 check_kinds!(
1280 target_type,
1281 "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1282 ty::FnPtr(..)
1283 );
1284 }
1285 CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(..), _) => {
1286 check_kinds!(
1288 op_ty,
1289 "CastKind::{kind:?} input must be a closure, not {:?}",
1290 ty::Closure(..)
1291 );
1292 check_kinds!(
1293 target_type,
1294 "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1295 ty::FnPtr(..)
1296 );
1297 }
1298 CastKind::PointerCoercion(PointerCoercion::MutToConstPointer, _) => {
1299 check_kinds!(
1301 op_ty,
1302 "CastKind::{kind:?} input must be a raw mut pointer, not {:?}",
1303 ty::RawPtr(_, Mutability::Mut)
1304 );
1305 check_kinds!(
1306 target_type,
1307 "CastKind::{kind:?} output must be a raw const pointer, not {:?}",
1308 ty::RawPtr(_, Mutability::Not)
1309 );
1310 if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup) {
1311 self.fail(location, format!("After borrowck, MIR disallows {kind:?}"));
1312 }
1313 }
1314 CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, _) => {
1315 check_kinds!(
1317 op_ty,
1318 "CastKind::{kind:?} input must be a raw pointer, not {:?}",
1319 ty::RawPtr(..)
1320 );
1321 check_kinds!(
1322 target_type,
1323 "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1324 ty::RawPtr(..)
1325 );
1326 if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup) {
1327 self.fail(location, format!("After borrowck, MIR disallows {kind:?}"));
1328 }
1329 }
1330 CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
1331 if !self.predicate_must_hold_modulo_regions(ty::TraitRef::new(
1334 self.tcx,
1335 self.tcx.require_lang_item(
1336 LangItem::CoerceUnsized,
1337 self.body.source_info(location).span,
1338 ),
1339 [op_ty, *target_type],
1340 )) {
1341 self.fail(location, format!("Unsize coercion, but `{op_ty}` isn't coercible to `{target_type}`"));
1342 }
1343 }
1344 CastKind::IntToInt | CastKind::IntToFloat => {
1345 let input_valid = op_ty.is_integral() || op_ty.is_char() || op_ty.is_bool();
1346 let target_valid = target_type.is_numeric() || target_type.is_char();
1347 if !input_valid || !target_valid {
1348 self.fail(
1349 location,
1350 format!("Wrong cast kind {kind:?} for the type {op_ty}"),
1351 );
1352 }
1353 }
1354 CastKind::FnPtrToPtr => {
1355 check_kinds!(
1356 op_ty,
1357 "CastKind::{kind:?} input must be a fn pointer, not {:?}",
1358 ty::FnPtr(..)
1359 );
1360 check_kinds!(
1361 target_type,
1362 "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1363 ty::RawPtr(..)
1364 );
1365 }
1366 CastKind::PtrToPtr => {
1367 check_kinds!(
1368 op_ty,
1369 "CastKind::{kind:?} input must be a raw pointer, not {:?}",
1370 ty::RawPtr(..)
1371 );
1372 check_kinds!(
1373 target_type,
1374 "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1375 ty::RawPtr(..)
1376 );
1377 }
1378 CastKind::FloatToFloat | CastKind::FloatToInt => {
1379 if !op_ty.is_floating_point() || !target_type.is_numeric() {
1380 self.fail(
1381 location,
1382 format!(
1383 "Trying to cast non 'Float' as {kind:?} into {target_type:?}"
1384 ),
1385 );
1386 }
1387 }
1388 CastKind::Transmute => {
1389 if !self
1393 .tcx
1394 .normalize_erasing_regions(
1395 self.typing_env,
1396 Unnormalized::new_wip(op_ty),
1397 )
1398 .is_sized(self.tcx, self.typing_env)
1399 {
1400 self.fail(
1401 location,
1402 format!("Cannot transmute from non-`Sized` type {op_ty}"),
1403 );
1404 }
1405 if !self
1406 .tcx
1407 .normalize_erasing_regions(
1408 self.typing_env,
1409 Unnormalized::new_wip(*target_type),
1410 )
1411 .is_sized(self.tcx, self.typing_env)
1412 {
1413 self.fail(
1414 location,
1415 format!("Cannot transmute to non-`Sized` type {target_type:?}"),
1416 );
1417 }
1418 }
1419 CastKind::Subtype => {
1420 if !util::sub_types(self.tcx, self.typing_env, op_ty, *target_type) {
1421 self.fail(
1422 location,
1423 format!("Failed subtyping {op_ty} and {target_type}"),
1424 )
1425 }
1426 }
1427 }
1428 }
1429 Rvalue::Repeat(_, _)
1430 | Rvalue::ThreadLocalRef(_)
1431 | Rvalue::RawPtr(_, _)
1432 | Rvalue::Discriminant(_) => {}
1433
1434 Rvalue::WrapUnsafeBinder(op, ty) => {
1435 let unwrapped_ty = op.ty(self.body, self.tcx);
1436 let ty::UnsafeBinder(binder_ty) = *ty.kind() else {
1437 self.fail(
1438 location,
1439 format!("WrapUnsafeBinder does not produce a ty::UnsafeBinder"),
1440 );
1441 return;
1442 };
1443 let binder_inner_ty = self.tcx.instantiate_bound_regions_with_erased(*binder_ty);
1444 if !self.mir_assign_valid_types(unwrapped_ty, binder_inner_ty) {
1445 self.fail(
1446 location,
1447 format!("Cannot wrap {unwrapped_ty} into unsafe binder {binder_ty:?}"),
1448 );
1449 }
1450 }
1451 }
1452 self.super_rvalue(rvalue, location);
1453 }
1454
1455 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1456 match &statement.kind {
1457 StatementKind::Assign((dest, rvalue)) => {
1458 let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
1460 let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
1461
1462 if !self.mir_assign_valid_types(right_ty, left_ty) {
1463 self.fail(
1464 location,
1465 format!(
1466 "encountered `{:?}` with incompatible types:\n\
1467 left-hand side has type: {}\n\
1468 right-hand side has type: {}",
1469 statement.kind, left_ty, right_ty,
1470 ),
1471 );
1472 }
1473
1474 if let Some(local) = dest.as_local()
1475 && let ClearCrossCrate::Set(LocalInfo::DerefTemp) =
1476 self.body.local_decls[local].local_info
1477 && !matches!(rvalue, Rvalue::CopyForDeref(_))
1478 {
1479 self.fail(location, "assignment to a `DerefTemp` must use `CopyForDeref`")
1480 }
1481 }
1482 StatementKind::AscribeUserType(..) => {
1483 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1484 self.fail(
1485 location,
1486 "`AscribeUserType` should have been removed after drop lowering phase",
1487 );
1488 }
1489 }
1490 StatementKind::FakeRead(..) => {
1491 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1492 self.fail(
1493 location,
1494 "`FakeRead` should have been removed after drop lowering phase",
1495 );
1496 }
1497 }
1498 StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(op)) => {
1499 let ty = op.ty(&self.body.local_decls, self.tcx);
1500 if !ty.is_bool() {
1501 self.fail(
1502 location,
1503 format!("`assume` argument must be `bool`, but got: `{ty}`"),
1504 );
1505 }
1506 }
1507 StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(
1508 CopyNonOverlapping { src, dst, count },
1509 )) => {
1510 let src_ty = src.ty(&self.body.local_decls, self.tcx);
1511 let op_src_ty = if let Some(src_deref) = src_ty.builtin_deref(true) {
1512 src_deref
1513 } else {
1514 self.fail(
1515 location,
1516 format!("Expected src to be ptr in copy_nonoverlapping, got: {src_ty}"),
1517 );
1518 return;
1519 };
1520 let dst_ty = dst.ty(&self.body.local_decls, self.tcx);
1521 let op_dst_ty = if let Some(dst_deref) = dst_ty.builtin_deref(true) {
1522 dst_deref
1523 } else {
1524 self.fail(
1525 location,
1526 format!("Expected dst to be ptr in copy_nonoverlapping, got: {dst_ty}"),
1527 );
1528 return;
1529 };
1530 if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) {
1533 self.fail(location, format!("bad arg ({op_src_ty} != {op_dst_ty})"));
1534 }
1535
1536 let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx);
1537 if op_cnt_ty != self.tcx.types.usize {
1538 self.fail(location, format!("bad arg ({op_cnt_ty} != usize)"))
1539 }
1540 }
1541 StatementKind::SetDiscriminant { place, .. } => {
1542 if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial) {
1543 self.fail(location, "`SetDiscriminant`is not allowed until deaggregation");
1544 }
1545 let pty = place.ty(&self.body.local_decls, self.tcx).ty;
1546 if !matches!(
1547 pty.kind(),
1548 ty::Adt(..)
1549 | ty::Coroutine(..)
1550 | ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. })
1551 ) {
1552 self.fail(
1553 location,
1554 format!(
1555 "`SetDiscriminant` is only allowed on ADTs and coroutines, not {pty}"
1556 ),
1557 );
1558 }
1559 }
1560 StatementKind::StorageLive(_)
1561 | StatementKind::StorageDead(_)
1562 | StatementKind::Coverage(_)
1563 | StatementKind::ConstEvalCounter
1564 | StatementKind::PlaceMention(..)
1565 | StatementKind::BackwardIncompatibleDropHint { .. }
1566 | StatementKind::Nop => {}
1567 }
1568
1569 self.super_statement(statement, location);
1570 }
1571
1572 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1573 match &terminator.kind {
1574 TerminatorKind::SwitchInt { targets, discr } => {
1575 let switch_ty = discr.ty(&self.body.local_decls, self.tcx);
1576
1577 let target_width = self.tcx.sess.target.pointer_width;
1578
1579 let size = Size::from_bits(match switch_ty.kind() {
1580 ty::Uint(uint) => uint.normalize(target_width).bit_width().unwrap(),
1581 ty::Int(int) => int.normalize(target_width).bit_width().unwrap(),
1582 ty::Char => 32,
1583 ty::Bool => 1,
1584 other => bug!("unhandled type: {:?}", other),
1585 });
1586
1587 for (value, _) in targets.iter() {
1588 if ScalarInt::try_from_uint(value, size).is_none() {
1589 self.fail(
1590 location,
1591 format!("the value {value:#x} is not a proper {switch_ty}"),
1592 )
1593 }
1594 }
1595 }
1596 TerminatorKind::Call { func, .. } | TerminatorKind::TailCall { func, .. } => {
1597 let func_ty = func.ty(&self.body.local_decls, self.tcx);
1598 match func_ty.kind() {
1599 ty::FnPtr(..) | ty::FnDef(..) => {}
1600 _ => self.fail(
1601 location,
1602 format!(
1603 "encountered non-callable type {func_ty} in `{}` terminator",
1604 terminator.kind.name()
1605 ),
1606 ),
1607 }
1608
1609 if let TerminatorKind::TailCall { .. } = terminator.kind {
1610 }
1613 }
1614 TerminatorKind::Assert { cond, .. } => {
1615 let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
1616 if cond_ty != self.tcx.types.bool {
1617 self.fail(
1618 location,
1619 format!(
1620 "encountered non-boolean condition of type {cond_ty} in `Assert` terminator"
1621 ),
1622 );
1623 }
1624 }
1625 TerminatorKind::Goto { .. }
1626 | TerminatorKind::Drop { .. }
1627 | TerminatorKind::Yield { .. }
1628 | TerminatorKind::FalseEdge { .. }
1629 | TerminatorKind::FalseUnwind { .. }
1630 | TerminatorKind::InlineAsm { .. }
1631 | TerminatorKind::CoroutineDrop
1632 | TerminatorKind::UnwindResume
1633 | TerminatorKind::UnwindTerminate(_)
1634 | TerminatorKind::Return
1635 | TerminatorKind::Unreachable => {}
1636 }
1637
1638 self.super_terminator(terminator, location);
1639 }
1640
1641 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
1642 if let ClearCrossCrate::Set(LocalInfo::DerefTemp) = local_decl.local_info {
1643 if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1644 self.fail(
1645 START_BLOCK.start_location(),
1646 "`DerefTemp` should have been removed in runtime MIR",
1647 );
1648 } else if local_decl.ty.builtin_deref(true).is_none() {
1649 self.fail(
1650 START_BLOCK.start_location(),
1651 "`DerefTemp` should only be used for dereferenceable types",
1652 )
1653 }
1654 }
1655
1656 self.super_local_decl(local, local_decl);
1657 }
1658}
1659
1660pub(super) fn validate_debuginfos<'tcx>(body: &Body<'tcx>) -> Vec<(Location, String)> {
1661 let mut debuginfo_checker =
1662 DebuginfoChecker { debuginfo_locals: debuginfo_locals(body), failures: Vec::new() };
1663 debuginfo_checker.visit_body(body);
1664 debuginfo_checker.failures
1665}
1666
1667struct DebuginfoChecker {
1668 debuginfo_locals: DenseBitSet<Local>,
1669 failures: Vec<(Location, String)>,
1670}
1671
1672impl<'tcx> Visitor<'tcx> for DebuginfoChecker {
1673 fn visit_statement_debuginfo(
1674 &mut self,
1675 stmt_debuginfo: &StmtDebugInfo<'tcx>,
1676 location: Location,
1677 ) {
1678 let local = match stmt_debuginfo {
1679 StmtDebugInfo::AssignRef(local, _) | StmtDebugInfo::InvalidAssign(local) => *local,
1680 };
1681 if !self.debuginfo_locals.contains(local) {
1682 self.failures.push((location, format!("{local:?} is not in debuginfo")));
1683 }
1684 }
1685}