rustc_mir_transform/
validate.rs

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