Skip to main content

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_data_structures::fx::{FxHashMap, FxHashSet};
5use rustc_hir::attrs::InlineAttr;
6use rustc_hir::attrs::lang_items::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::visit::{MutatingUseContext, NonUseContext, PlaceContext, Visitor};
12use rustc_middle::mir::*;
13use rustc_middle::ty::adjustment::PointerCoercion;
14use rustc_middle::ty::print::with_no_trimmed_paths;
15use rustc_middle::ty::{
16    self, InstanceKind, ScalarInt, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast, Variance,
17};
18use rustc_mir_dataflow::debuginfo::debuginfo_locals;
19use rustc_span::{bug, span_bug};
20use rustc_trait_selection::traits::ObligationCtxt;
21
22use crate::PassPolicy;
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    /// Describes at which point in the pipeline this validation is happening.
33    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        // FIXME(JakobDegen): These bodies never instantiated in codegend anyway, so it's not
39        // terribly important that they pass the validator. However, I think other passes might
40        // still see them, in which case they might be surprised. It would probably be better if we
41        // didn't put this through the MIR pipeline at all.
42        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            // In this case `AbortUnwindingCalls` haven't yet been executed.
49            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                // No need to do MIR validation on error bodies
60                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        // Also run the TypeChecker.
80        for (location, msg) in validate_types(tcx, typing_env, body, body) {
81            cfg_checker.fail(location, msg);
82        }
83
84        // Ensure that debuginfo records are not emitted for locals that are not in debuginfo.
85        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 policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
101        PassPolicy::optional(true)
102    }
103}
104
105/// This checker covers basic properties of the control-flow graph, (dis)allowed statements and terminators.
106/// Everything checked here must be stable under substitution of generic parameters. In other words,
107/// this is about the *structure* of the MIR, not the *contents*.
108///
109/// Everything that depends on types, or otherwise can be affected by generic parameters,
110/// must be checked in `TypeChecker`.
111struct 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    // If `false`, then the MIR must not contain `UnwindAction::Continue` or
119    // `TerminatorKind::Resume`.
120    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        // We might see broken MIR when other errors have already occurred.
127        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                // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges
147                (false, false, EdgeKind::Normal) => {}
148                // Cleanup blocks can jump to cleanup blocks along non-unwind edges
149                (true, true, EdgeKind::Normal) => {}
150                // Non-cleanup blocks can jump to cleanup blocks along unwind edges
151                (false, true, EdgeKind::Unwind) => {
152                    self.unwind_edge_count += 1;
153                }
154                // All other jumps are invalid
155                _ => 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        // Reusing the allocation across invocations of the closure
175        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        // Check for cycles
225        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            // These are allowed everywhere.
273            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                    && kind.is_removed_after_analysis()
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                // FIXME(explicit_tail_calls): refactor this & add tail-call specific checks
380                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                    // The code generation assumes that there are no critical call edges. The
387                    // assumption is used to simplify inserting code that should be executed along
388                    // the return edge from the call. FIXME(tmiasko): Since this is a strictly code
389                    // generation concern, the code generation should be responsible for handling
390                    // it.
391                    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                    // The call destination place and Operand::Move place used as an argument might
404                    // be passed by a reference to the callee. Consequently they cannot be packed.
405                    if most_packed_projection(self.tcx, &self.body.local_decls, destination)
406                        .is_some()
407                    {
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 most_packed_projection(self.tcx, &self.body.local_decls, *place)
422                            .is_some()
423                        {
424                            // This is bad! The callee will expect the memory to be aligned.
425                            self.fail(
426                                location,
427                                format!(
428                                    "encountered `Move` of a packed place in `Call` terminator: {:?}",
429                                    terminator.kind,
430                                ),
431                            );
432                        }
433
434                        // Call arguments are moved by reference, so they must be plain locals
435                        // or the contents of a box; other moved places violate MIR invariants.
436                        if self.tcx.sess.opts.unstable_opts.validate_mir
437                            && self.body.phase < MirPhase::Runtime(RuntimePhase::Initial)
438                        {
439                            let is_plain_local = place.projection.is_empty();
440                            let is_box_deref =
441                                matches!(place.projection.as_ref(), [ProjectionElem::Deref])
442                                    && self.body.local_decls[place.local].ty.is_box();
443                            if !is_plain_local && !is_box_deref {
444                                self.fail(
445                                    location,
446                                    format!(
447                                        "encountered `Move` of a non-local, non-box place in `Call` terminator: {:?}",
448                                        terminator.kind,
449                                    ),
450                                );
451                            }
452                        }
453                    }
454                }
455
456                if let ty::FnDef(did, ..) = *func.ty(&self.body.local_decls, self.tcx).kind()
457                    && self.body.phase >= MirPhase::Runtime(RuntimePhase::Optimized)
458                    && matches!(self.tcx.codegen_fn_attrs(did).inline, InlineAttr::Force { .. })
459                {
460                    self.fail(location, "`#[rustc_force_inline]`-annotated function not inlined");
461                }
462            }
463            TerminatorKind::Assert { target, unwind, .. } => {
464                self.check_edge(location, *target, EdgeKind::Normal);
465                self.check_unwind_edge(location, *unwind);
466            }
467            TerminatorKind::Yield { resume, drop, .. } => {
468                if self.body.coroutine.is_none() {
469                    self.fail(location, "`Yield` cannot appear outside coroutine bodies");
470                }
471                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
472                    self.fail(location, "`Yield` should have been replaced by coroutine lowering");
473                }
474                self.check_edge(location, *resume, EdgeKind::Normal);
475                if let Some(drop) = drop {
476                    self.check_edge(location, *drop, EdgeKind::Normal);
477                }
478            }
479            TerminatorKind::FalseEdge { real_target, imaginary_target } => {
480                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
481                    self.fail(
482                        location,
483                        "`FalseEdge` should have been removed after drop elaboration",
484                    );
485                }
486                self.check_edge(location, *real_target, EdgeKind::Normal);
487                self.check_edge(location, *imaginary_target, EdgeKind::Normal);
488            }
489            TerminatorKind::FalseUnwind { real_target, unwind } => {
490                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
491                    self.fail(
492                        location,
493                        "`FalseUnwind` should have been removed after drop elaboration",
494                    );
495                }
496                self.check_edge(location, *real_target, EdgeKind::Normal);
497                self.check_unwind_edge(location, *unwind);
498            }
499            TerminatorKind::InlineAsm { targets, unwind, .. } => {
500                for &target in targets {
501                    self.check_edge(location, target, EdgeKind::Normal);
502                }
503                self.check_unwind_edge(location, *unwind);
504            }
505            TerminatorKind::CoroutineDrop => {
506                if self.body.coroutine.is_none() {
507                    self.fail(location, "`CoroutineDrop` cannot appear outside coroutine bodies");
508                }
509                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
510                    self.fail(
511                        location,
512                        "`CoroutineDrop` should have been replaced by coroutine lowering",
513                    );
514                }
515            }
516            TerminatorKind::UnwindResume => {
517                let bb = location.block;
518                if !self.body.basic_blocks[bb].is_cleanup {
519                    self.fail(location, "Cannot `UnwindResume` from non-cleanup basic block")
520                }
521                if !self.can_unwind {
522                    self.fail(location, "Cannot `UnwindResume` in a function that cannot unwind")
523                }
524            }
525            TerminatorKind::UnwindTerminate(_) => {
526                let bb = location.block;
527                if !self.body.basic_blocks[bb].is_cleanup {
528                    self.fail(location, "Cannot `UnwindTerminate` from non-cleanup basic block")
529                }
530            }
531            TerminatorKind::Return => {
532                let bb = location.block;
533                if self.body.basic_blocks[bb].is_cleanup {
534                    self.fail(location, "Cannot `Return` from cleanup basic block")
535                }
536            }
537            TerminatorKind::Unreachable => {}
538        }
539
540        self.super_terminator(terminator, location);
541    }
542
543    fn visit_source_scope(&mut self, scope: SourceScope) {
544        if self.body.source_scopes.get(scope).is_none() {
545            self.tcx.dcx().span_bug(
546                self.body.span,
547                format!(
548                    "broken MIR in {:?} ({}):\ninvalid source scope {:?}",
549                    self.body.source.instance, self.when, scope,
550                ),
551            );
552        }
553    }
554}
555
556/// A faster version of the validation pass that only checks those things which may break when
557/// instantiating any generic parameters.
558///
559/// `caller_body` is used to detect cycles in MIR inlining and MIR validation before
560/// `optimized_mir` is available.
561pub(super) fn validate_types<'tcx>(
562    tcx: TyCtxt<'tcx>,
563    typing_env: ty::TypingEnv<'tcx>,
564    body: &Body<'tcx>,
565    caller_body: &Body<'tcx>,
566) -> Vec<(Location, String)> {
567    let mut type_checker = TypeChecker { body, caller_body, tcx, typing_env, failures: Vec::new() };
568    // The type checker formats a bunch of strings with type names in it, but these strings
569    // are not always going to be encountered on the error path since the inliner also uses
570    // the validator, and there are certain kinds of inlining (even for valid code) that
571    // can cause validation errors (mostly around where clauses and rigid projections).
572    with_no_trimmed_paths!({
573        type_checker.visit_body(body);
574    });
575    type_checker.failures
576}
577
578struct TypeChecker<'a, 'tcx> {
579    body: &'a Body<'tcx>,
580    caller_body: &'a Body<'tcx>,
581    tcx: TyCtxt<'tcx>,
582    typing_env: ty::TypingEnv<'tcx>,
583    failures: Vec<(Location, String)>,
584}
585
586impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
587    fn fail(&mut self, location: Location, msg: impl Into<String>) {
588        self.failures.push((location, msg.into()));
589    }
590
591    /// Check if src can be assigned into dest.
592    /// This is not precise, it will accept some incorrect assignments.
593    fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
594        // Fast path before we normalize.
595        if src == dest {
596            // Equal types, all is good.
597            return true;
598        }
599
600        // We sometimes have to use `defining_opaque_types` for subtyping
601        // to succeed here and figuring out how exactly that should work
602        // is annoying. It is harmless enough to just not validate anything
603        // in that case. We still check this after analysis as all opaque
604        // types have been revealed at this point.
605        if (src, dest).has_opaque_types() {
606            return true;
607        }
608
609        // After borrowck subtyping should be fully explicit via
610        // `Subtype` projections.
611        let variance = if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
612            Variance::Invariant
613        } else {
614            Variance::Covariant
615        };
616
617        crate::util::relate_types(self.tcx, self.typing_env, variance, src, dest)
618    }
619
620    /// Check that the given predicate definitely holds in the param-env of this MIR body.
621    fn predicate_must_hold_modulo_regions(
622        &self,
623        pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
624    ) -> bool {
625        let pred: ty::Predicate<'tcx> = pred.upcast(self.tcx);
626
627        // We sometimes have to use `defining_opaque_types` for predicates
628        // to succeed here and figuring out how exactly that should work
629        // is annoying. It is harmless enough to just not validate anything
630        // in that case. We still check this after analysis as all opaque
631        // types have been revealed at this point.
632        if pred.has_opaque_types() {
633            return true;
634        }
635
636        let (infcx, param_env) = self.tcx.infer_ctxt().build_with_typing_env(self.typing_env);
637        let ocx = ObligationCtxt::new(&infcx);
638        ocx.register_obligation(Obligation::new(
639            self.tcx,
640            ObligationCause::dummy(),
641            param_env,
642            pred,
643        ));
644        ocx.evaluate_obligations_error_on_ambiguity().no_errors()
645    }
646}
647
648impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
649    fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
650        // This check is somewhat expensive, so only run it when -Zvalidate-mir is passed.
651        if self.tcx.sess.opts.unstable_opts.validate_mir
652            && self.body.phase < MirPhase::Runtime(RuntimePhase::Initial)
653        {
654            // `Operand::Copy` is only supposed to be used with `Copy` types.
655            if let Operand::Copy(place) = operand {
656                let ty = place.ty(&self.body.local_decls, self.tcx).ty;
657
658                if !self.tcx.type_is_copy_modulo_regions(self.typing_env, ty) {
659                    self.fail(location, format!("`Operand::Copy` with non-`Copy` type {ty}"));
660                }
661            }
662        }
663
664        self.super_operand(operand, location);
665    }
666
667    fn visit_projection_elem(
668        &mut self,
669        place_ref: PlaceRef<'tcx>,
670        elem: PlaceElem<'tcx>,
671        context: PlaceContext,
672        location: Location,
673    ) {
674        match elem {
675            ProjectionElem::Deref
676                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) =>
677            {
678                let base_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
679
680                if base_ty.is_box() {
681                    self.fail(location, format!("{base_ty} dereferenced after ElaborateBoxDerefs"))
682                }
683            }
684            ProjectionElem::Field(f, ty) => {
685                let parent_ty = place_ref.ty(&self.body.local_decls, self.tcx);
686                let fail_out_of_bounds = |this: &mut Self, location| {
687                    this.fail(location, format!("Out of bounds field {f:?} for {parent_ty:?}"));
688                };
689                let check_equal = |this: &mut Self, location, f_ty| {
690                    if !this.mir_assign_valid_types(ty, f_ty) {
691                        this.fail(
692                            location,
693                            format!(
694                                "Field projection `{place_ref:?}.{f:?}` specified type `{ty}`, but actual type is `{f_ty}`"
695                            )
696                        )
697                    }
698                };
699
700                let kind = match parent_ty.ty.kind() {
701                    &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
702                        self.tcx.type_of(def_id).instantiate(self.tcx, args).skip_norm_wip().kind()
703                    }
704                    kind => kind,
705                };
706
707                match kind {
708                    ty::Tuple(fields) => {
709                        let Some(f_ty) = fields.get(f.as_usize()) else {
710                            fail_out_of_bounds(self, location);
711                            return;
712                        };
713                        check_equal(self, location, *f_ty);
714                    }
715                    // Debug info is allowed to project into pattern types
716                    ty::Pat(base, _) => check_equal(self, location, *base),
717                    ty::Adt(adt_def, args) => {
718                        // see <https://github.com/rust-lang/rust/blob/7601adcc764d42c9f2984082b49948af652df986/compiler/rustc_middle/src/ty/layout.rs#L861-L864>
719                        if self.tcx.is_lang_item(adt_def.did(), LangItem::DynMetadata) {
720                            self.fail(
721                                location,
722                                format!(
723                                    "You can't project to field {f:?} of `DynMetadata` because \
724                                     layout is weird and thinks it doesn't have fields."
725                                ),
726                            );
727                        }
728
729                        if adt_def.repr().simd() || adt_def.repr().scalable() {
730                            self.fail(
731                                location,
732                                format!(
733                                    "Projecting into SIMD type {adt_def:?} is banned by MCP#838"
734                                ),
735                            );
736                        }
737
738                        let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT);
739                        let Some(field) = adt_def.variant(var).fields.get(f) else {
740                            fail_out_of_bounds(self, location);
741                            return;
742                        };
743                        check_equal(self, location, field.ty(self.tcx, args).skip_norm_wip());
744                    }
745                    ty::Closure(_, args) => {
746                        let args = args.as_closure();
747                        let Some(&f_ty) = args.upvar_tys().get(f.as_usize()) else {
748                            fail_out_of_bounds(self, location);
749                            return;
750                        };
751                        check_equal(self, location, f_ty);
752                    }
753                    ty::CoroutineClosure(_, args) => {
754                        let args = args.as_coroutine_closure();
755                        let Some(&f_ty) = args.upvar_tys().get(f.as_usize()) else {
756                            fail_out_of_bounds(self, location);
757                            return;
758                        };
759                        check_equal(self, location, f_ty);
760                    }
761                    &ty::Coroutine(def_id, args) => {
762                        let f_ty = if let Some(var) = parent_ty.variant_index {
763                            // If we're currently validating an inlined copy of this body,
764                            // then it will no longer be parameterized over the original
765                            // args of the coroutine. Otherwise, we prefer to use this body
766                            // since we may be in the process of computing this MIR in the
767                            // first place.
768                            let layout = if def_id == self.caller_body.source.def_id() {
769                                self.caller_body
770                                    .coroutine_layout_raw()
771                                    .or_else(|| self.tcx.coroutine_layout(def_id, args).ok())
772                            } else if self.tcx.needs_coroutine_by_move_body_def_id(def_id)
773                                && let ty::ClosureKind::FnOnce =
774                                    args.as_coroutine().kind_ty().to_opt_closure_kind().unwrap()
775                                && self.caller_body.source.def_id()
776                                    == self.tcx.coroutine_by_move_body_def_id(def_id)
777                            {
778                                // Same if this is the by-move body of a coroutine-closure.
779                                self.caller_body.coroutine_layout_raw()
780                            } else {
781                                self.tcx.coroutine_layout(def_id, args).ok()
782                            };
783
784                            let Some(layout) = layout else {
785                                self.fail(
786                                    location,
787                                    format!("No coroutine layout for {parent_ty:?}"),
788                                );
789                                return;
790                            };
791
792                            let Some(&local) = layout.variant_fields[var].get(f) else {
793                                fail_out_of_bounds(self, location);
794                                return;
795                            };
796
797                            let Some(f_ty) = layout.field_tys.get(local) else {
798                                self.fail(
799                                    location,
800                                    format!("Out of bounds local {local:?} for {parent_ty:?}"),
801                                );
802                                return;
803                            };
804
805                            ty::EarlyBinder::bind(self.tcx, f_ty.ty)
806                                .instantiate(self.tcx, args)
807                                .skip_norm_wip()
808                        } else if let Some(&f_ty) = args.as_coroutine().upvar_tys().get(f.index()) {
809                            f_ty
810                        } else {
811                            fail_out_of_bounds(self, location);
812                            return;
813                        };
814
815                        check_equal(self, location, f_ty);
816                    }
817                    _ => {
818                        self.fail(location, format!("{:?} does not have fields", parent_ty.ty));
819                    }
820                }
821            }
822            ProjectionElem::Index(index) => {
823                let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
824                match indexed_ty.kind() {
825                    ty::Array(_, _) | ty::Slice(_) => {}
826                    _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
827                }
828
829                let index_ty = self.body.local_decls[index].ty;
830                if index_ty != self.tcx.types.usize {
831                    self.fail(location, format!("bad index ({index_ty} != usize)"))
832                }
833            }
834            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
835                let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
836                match indexed_ty.kind() {
837                    ty::Array(_, _) => {
838                        if from_end {
839                            self.fail(location, "arrays should not be indexed from end");
840                        }
841                    }
842                    ty::Slice(_) => {}
843                    _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
844                }
845
846                if from_end {
847                    if offset > min_length {
848                        self.fail(
849                            location,
850                            format!(
851                                "constant index with offset -{offset} out of bounds of min length {min_length}"
852                            ),
853                        );
854                    }
855                } else {
856                    if offset >= min_length {
857                        self.fail(
858                            location,
859                            format!(
860                                "constant index with offset {offset} out of bounds of min length {min_length}"
861                            ),
862                        );
863                    }
864                }
865            }
866            ProjectionElem::Subslice { from, to, from_end } => {
867                let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
868                match indexed_ty.kind() {
869                    ty::Array(_, _) => {
870                        if from_end {
871                            self.fail(location, "arrays should not be subsliced from end");
872                        }
873                    }
874                    ty::Slice(_) => {
875                        if !from_end {
876                            self.fail(location, "slices should be subsliced from end");
877                        }
878                    }
879                    _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
880                }
881
882                if !from_end && from > to {
883                    self.fail(location, "backwards subslice {from}..{to}");
884                }
885            }
886            ProjectionElem::OpaqueCast(ty)
887                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) =>
888            {
889                self.fail(
890                    location,
891                    format!("explicit opaque type cast to `{ty}` after `PostAnalysisNormalize`"),
892                )
893            }
894            ProjectionElem::UnwrapUnsafeBinder(unwrapped_ty) => {
895                let binder_ty = place_ref.ty(&self.body.local_decls, self.tcx);
896                let ty::UnsafeBinder(binder_ty) = *binder_ty.ty.kind() else {
897                    self.fail(
898                        location,
899                        format!("WrapUnsafeBinder does not produce a ty::UnsafeBinder"),
900                    );
901                    return;
902                };
903                let binder_inner_ty = self.tcx.instantiate_bound_regions_with_erased(*binder_ty);
904                if !self.mir_assign_valid_types(unwrapped_ty, binder_inner_ty) {
905                    self.fail(
906                        location,
907                        format!(
908                            "Cannot unwrap unsafe binder {binder_ty:?} into type {unwrapped_ty}"
909                        ),
910                    );
911                }
912            }
913            _ => {}
914        }
915        self.super_projection_elem(place_ref, elem, context, location);
916    }
917
918    fn visit_var_debug_info(&mut self, debuginfo: &VarDebugInfo<'tcx>) {
919        if let Some(VarDebugInfoFragment { ty, ref projection }) = debuginfo.composite {
920            if ty.is_union() || ty.is_enum() {
921                self.fail(
922                    START_BLOCK.start_location(),
923                    format!("invalid type {ty} in debuginfo for {:?}", debuginfo.name),
924                );
925            }
926            if projection.is_empty() {
927                self.fail(
928                    START_BLOCK.start_location(),
929                    format!("invalid empty projection in debuginfo for {:?}", debuginfo.name),
930                );
931            }
932            if projection.iter().any(|p| !matches!(p, PlaceElem::Field(..))) {
933                self.fail(
934                    START_BLOCK.start_location(),
935                    format!(
936                        "illegal projection {:?} in debuginfo for {:?}",
937                        projection, debuginfo.name
938                    ),
939                );
940            }
941        }
942        match debuginfo.value {
943            VarDebugInfoContents::Const(_) => {}
944            VarDebugInfoContents::Place(place) => {
945                if place.projection.iter().any(|p| !p.can_use_in_debuginfo()) {
946                    self.fail(
947                        START_BLOCK.start_location(),
948                        format!("illegal place {:?} in debuginfo for {:?}", place, debuginfo.name),
949                    );
950                }
951            }
952        }
953        self.super_var_debug_info(debuginfo);
954    }
955
956    fn visit_place(&mut self, place: &Place<'tcx>, cntxt: PlaceContext, location: Location) {
957        // Set off any `bug!`s in the type computation code
958        let _ = place.ty(&self.body.local_decls, self.tcx);
959
960        if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial)
961            && place.projection.len() > 1
962            && cntxt != PlaceContext::NonUse(NonUseContext::VarDebugInfo)
963            && place.projection[1..].contains(&ProjectionElem::Deref)
964        {
965            self.fail(
966                location,
967                format!("place {place:?} has deref as a later projection (it is only permitted as the first projection)"),
968            );
969        }
970
971        // Ensure all downcast projections are followed by field projections.
972        let mut projections_iter = place.projection.iter();
973        while let Some(proj) = projections_iter.next() {
974            if matches!(proj, ProjectionElem::Downcast(..)) {
975                if !matches!(projections_iter.next(), Some(ProjectionElem::Field(..))) {
976                    self.fail(
977                        location,
978                        format!(
979                            "place {place:?} has `Downcast` projection not followed by `Field`"
980                        ),
981                    );
982                }
983            }
984        }
985
986        if let ClearCrossCrate::Set(LocalInfo::DerefTemp) =
987            self.body.local_decls[place.local].local_info
988            && !place.is_indirect_first_projection()
989        {
990            if cntxt != PlaceContext::MutatingUse(MutatingUseContext::Store)
991                || place.as_local().is_none()
992            {
993                self.fail(
994                    location,
995                    format!("`DerefTemp` locals must only be dereferenced or directly assigned to"),
996                );
997            }
998        }
999
1000        if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial)
1001            && let Some(i) = place
1002                .projection
1003                .iter()
1004                .position(|elem| matches!(elem, ProjectionElem::Subslice { .. }))
1005            && let Some(tail) = place.projection.get(i + 1..)
1006            && tail.iter().any(|elem| {
1007                matches!(
1008                    elem,
1009                    ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. }
1010                )
1011            })
1012        {
1013            self.fail(
1014                location,
1015                format!("place {place:?} has `ConstantIndex` or `Subslice` after `Subslice`"),
1016            );
1017        }
1018
1019        self.super_place(place, cntxt, location);
1020    }
1021
1022    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1023        macro_rules! check_kinds {
1024            ($t:expr, $text:literal, $typat:pat) => {
1025                if !matches!(($t).kind(), $typat) {
1026                    self.fail(location, format!($text, $t));
1027                }
1028            };
1029        }
1030        match rvalue {
1031            Rvalue::Use(_, _) => {}
1032            Rvalue::CopyForDeref(_) => {
1033                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1034                    self.fail(location, "`CopyForDeref` should have been removed in runtime MIR");
1035                }
1036            }
1037            Rvalue::Aggregate(kind, fields) => match **kind {
1038                AggregateKind::Tuple => {}
1039                AggregateKind::Array(dest) => {
1040                    for src in fields {
1041                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1042                            self.fail(location, "array field has the wrong type");
1043                        }
1044                    }
1045                }
1046                AggregateKind::Adt(def_id, idx, args, _, Some(field)) => {
1047                    let adt_def = self.tcx.adt_def(def_id);
1048                    assert!(adt_def.is_union());
1049                    assert_eq!(idx, FIRST_VARIANT);
1050                    let dest_ty = self.tcx.normalize_erasing_regions(
1051                        self.typing_env,
1052                        adt_def.non_enum_variant().fields[field].ty(self.tcx, args),
1053                    );
1054                    if let [field] = fields.raw.as_slice() {
1055                        let src_ty = field.ty(self.body, self.tcx);
1056                        if !self.mir_assign_valid_types(src_ty, dest_ty) {
1057                            self.fail(location, "union field has the wrong type");
1058                        }
1059                    } else {
1060                        self.fail(location, "unions should have one initialized field");
1061                    }
1062                }
1063                AggregateKind::Adt(def_id, idx, args, _, None) => {
1064                    let adt_def = self.tcx.adt_def(def_id);
1065                    assert!(!adt_def.is_union());
1066                    let variant = &adt_def.variants()[idx];
1067                    if variant.fields.len() != fields.len() {
1068                        self.fail(location, format!(
1069                            "adt {def_id:?} has the wrong number of initialized fields, expected {}, found {}",
1070                            fields.len(),
1071                            variant.fields.len(),
1072                        ));
1073                    }
1074                    for (src, dest) in std::iter::zip(fields, &variant.fields) {
1075                        let dest_ty = self
1076                            .tcx
1077                            .normalize_erasing_regions(self.typing_env, dest.ty(self.tcx, args));
1078                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest_ty) {
1079                            self.fail(location, "adt field has the wrong type");
1080                        }
1081                    }
1082                }
1083                AggregateKind::Closure(_, args) => {
1084                    let upvars = args.as_closure().upvar_tys();
1085                    if upvars.len() != fields.len() {
1086                        self.fail(location, "closure has the wrong number of initialized fields");
1087                    }
1088                    for (src, dest) in std::iter::zip(fields, upvars) {
1089                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1090                            self.fail(location, "closure field has the wrong type");
1091                        }
1092                    }
1093                }
1094                AggregateKind::Coroutine(_, args) => {
1095                    let upvars = args.as_coroutine().upvar_tys();
1096                    if upvars.len() != fields.len() {
1097                        self.fail(location, "coroutine has the wrong number of initialized fields");
1098                    }
1099                    for (src, dest) in std::iter::zip(fields, upvars) {
1100                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1101                            self.fail(location, "coroutine field has the wrong type");
1102                        }
1103                    }
1104                }
1105                AggregateKind::CoroutineClosure(_, args) => {
1106                    let upvars = args.as_coroutine_closure().upvar_tys();
1107                    if upvars.len() != fields.len() {
1108                        self.fail(
1109                            location,
1110                            "coroutine-closure has the wrong number of initialized fields",
1111                        );
1112                    }
1113                    for (src, dest) in std::iter::zip(fields, upvars) {
1114                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1115                            self.fail(location, "coroutine-closure field has the wrong type");
1116                        }
1117                    }
1118                }
1119                AggregateKind::RawPtr(pointee_ty, mutability) => {
1120                    if !matches!(self.body.phase, MirPhase::Runtime(_)) {
1121                        // It would probably be fine to support this in earlier phases, but at the
1122                        // time of writing it's only ever introduced from intrinsic lowering, so
1123                        // earlier things just `bug!` on it.
1124                        self.fail(location, "RawPtr should be in runtime MIR only");
1125                    }
1126
1127                    if let [data_ptr, metadata] = fields.raw.as_slice() {
1128                        let data_ptr_ty = data_ptr.ty(self.body, self.tcx);
1129                        let metadata_ty = metadata.ty(self.body, self.tcx);
1130                        if let ty::RawPtr(in_pointee, in_mut) = data_ptr_ty.kind() {
1131                            if *in_mut != mutability {
1132                                self.fail(location, "input and output mutability must match");
1133                            }
1134
1135                            // FIXME: check `Thin` instead of `Sized`
1136                            if !in_pointee.is_sized(self.tcx, self.typing_env) {
1137                                self.fail(location, "input pointer must be thin");
1138                            }
1139                        } else {
1140                            self.fail(
1141                                location,
1142                                "first operand to raw pointer aggregate must be a raw pointer",
1143                            );
1144                        }
1145
1146                        // FIXME: Check metadata more generally
1147                        if pointee_ty.is_slice() {
1148                            if !self.mir_assign_valid_types(metadata_ty, self.tcx.types.usize) {
1149                                self.fail(location, "slice metadata must be usize");
1150                            }
1151                        } else if pointee_ty.is_sized(self.tcx, self.typing_env) {
1152                            if metadata_ty != self.tcx.types.unit {
1153                                self.fail(location, "metadata for pointer-to-thin must be unit");
1154                            }
1155                        }
1156                    } else {
1157                        self.fail(location, "raw pointer aggregate must have 2 fields");
1158                    }
1159                }
1160            },
1161            Rvalue::Ref(_, BorrowKind::Fake(_), _) => {
1162                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1163                    self.fail(
1164                        location,
1165                        "`Assign` statement with a `Fake` borrow should have been removed in runtime MIR",
1166                    );
1167                }
1168            }
1169            Rvalue::Ref(..) | Rvalue::Reborrow(..) => {}
1170            Rvalue::BinaryOp(op, vals) => {
1171                use BinOp::*;
1172                let a = vals.0.ty(&self.body.local_decls, self.tcx);
1173                let b = vals.1.ty(&self.body.local_decls, self.tcx);
1174                if crate::util::binop_right_homogeneous(*op) {
1175                    if let Eq | Lt | Le | Ne | Ge | Gt = op {
1176                        // The function pointer types can have lifetimes
1177                        if !self.mir_assign_valid_types(a, b) {
1178                            self.fail(
1179                                location,
1180                                format!("Cannot {op:?} compare incompatible types {a} and {b}"),
1181                            );
1182                        }
1183                    } else if a != b {
1184                        self.fail(
1185                            location,
1186                            format!("Cannot perform binary op {op:?} on unequal types {a} and {b}"),
1187                        );
1188                    }
1189                }
1190
1191                match op {
1192                    Offset => {
1193                        check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..));
1194                        if b != self.tcx.types.isize && b != self.tcx.types.usize {
1195                            self.fail(location, format!("Cannot offset by non-isize type {b}"));
1196                        }
1197                    }
1198                    Eq | Lt | Le | Ne | Ge | Gt => {
1199                        for x in [a, b] {
1200                            check_kinds!(
1201                                x,
1202                                "Cannot {op:?} compare type {:?}",
1203                                ty::Bool
1204                                    | ty::Char
1205                                    | ty::Int(..)
1206                                    | ty::Uint(..)
1207                                    | ty::Float(..)
1208                                    | ty::RawPtr(..)
1209                                    | ty::FnPtr(..)
1210                            )
1211                        }
1212                    }
1213                    Cmp => {
1214                        for x in [a, b] {
1215                            check_kinds!(
1216                                x,
1217                                "Cannot three-way compare non-integer type {:?}",
1218                                ty::Char | ty::Uint(..) | ty::Int(..)
1219                            )
1220                        }
1221                    }
1222                    AddUnchecked | AddWithOverflow | SubUnchecked | SubWithOverflow
1223                    | MulUnchecked | MulWithOverflow | Shl | ShlUnchecked | Shr | ShrUnchecked => {
1224                        for x in [a, b] {
1225                            check_kinds!(
1226                                x,
1227                                "Cannot {op:?} non-integer type {:?}",
1228                                ty::Uint(..) | ty::Int(..)
1229                            )
1230                        }
1231                    }
1232                    BitAnd | BitOr | BitXor => {
1233                        for x in [a, b] {
1234                            check_kinds!(
1235                                x,
1236                                "Cannot perform bitwise op {op:?} on type {:?}",
1237                                ty::Uint(..) | ty::Int(..) | ty::Bool
1238                            )
1239                        }
1240                    }
1241                    Add | Sub | Mul | Div | Rem => {
1242                        for x in [a, b] {
1243                            check_kinds!(
1244                                x,
1245                                "Cannot perform arithmetic {op:?} on type {:?}",
1246                                ty::Uint(..) | ty::Int(..) | ty::Float(..)
1247                            )
1248                        }
1249                    }
1250                }
1251            }
1252            Rvalue::UnaryOp(op, operand) => {
1253                let a = operand.ty(&self.body.local_decls, self.tcx);
1254                match op {
1255                    UnOp::Neg => {
1256                        check_kinds!(a, "Cannot negate type {:?}", ty::Int(..) | ty::Float(..))
1257                    }
1258                    UnOp::Not => {
1259                        check_kinds!(
1260                            a,
1261                            "Cannot binary not type {:?}",
1262                            ty::Int(..) | ty::Uint(..) | ty::Bool
1263                        );
1264                    }
1265                    UnOp::PtrMetadata => {
1266                        check_kinds!(
1267                            a,
1268                            "Cannot PtrMetadata non-pointer non-reference type {:?}",
1269                            ty::RawPtr(..) | ty::Ref(..)
1270                        );
1271                    }
1272                }
1273            }
1274            Rvalue::Cast(kind, operand, target_type) => {
1275                let op_ty = operand.ty(self.body, self.tcx);
1276                match kind {
1277                    // FIXME: Add Checks for these
1278                    CastKind::PointerWithExposedProvenance | CastKind::PointerExposeProvenance => {}
1279                    CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
1280                        // FIXME: check signature compatibility.
1281                        check_kinds!(
1282                            op_ty,
1283                            "CastKind::{kind:?} input must be a fn item, not {:?}",
1284                            ty::FnDef(..)
1285                        );
1286                        check_kinds!(
1287                            target_type,
1288                            "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1289                            ty::FnPtr(..)
1290                        );
1291                    }
1292                    CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
1293                        // FIXME: check safety and signature compatibility.
1294                        check_kinds!(
1295                            op_ty,
1296                            "CastKind::{kind:?} input must be a fn pointer, not {:?}",
1297                            ty::FnPtr(..)
1298                        );
1299                        check_kinds!(
1300                            target_type,
1301                            "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1302                            ty::FnPtr(..)
1303                        );
1304                    }
1305                    CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(..), _) => {
1306                        // FIXME: check safety, captures, and signature compatibility.
1307                        check_kinds!(
1308                            op_ty,
1309                            "CastKind::{kind:?} input must be a closure, not {:?}",
1310                            ty::Closure(..)
1311                        );
1312                        check_kinds!(
1313                            target_type,
1314                            "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1315                            ty::FnPtr(..)
1316                        );
1317                    }
1318                    CastKind::PointerCoercion(PointerCoercion::MutToConstPointer, _) => {
1319                        // FIXME: check same pointee?
1320                        check_kinds!(
1321                            op_ty,
1322                            "CastKind::{kind:?} input must be a raw mut pointer, not {:?}",
1323                            ty::RawPtr(_, Mutability::Mut)
1324                        );
1325                        check_kinds!(
1326                            target_type,
1327                            "CastKind::{kind:?} output must be a raw const pointer, not {:?}",
1328                            ty::RawPtr(_, Mutability::Not)
1329                        );
1330                        if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup) {
1331                            self.fail(location, format!("After borrowck, MIR disallows {kind:?}"));
1332                        }
1333                    }
1334                    CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, _) => {
1335                        // FIXME: Check pointee types
1336                        check_kinds!(
1337                            op_ty,
1338                            "CastKind::{kind:?} input must be a raw pointer, not {:?}",
1339                            ty::RawPtr(..)
1340                        );
1341                        check_kinds!(
1342                            target_type,
1343                            "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1344                            ty::RawPtr(..)
1345                        );
1346                        if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup) {
1347                            self.fail(location, format!("After borrowck, MIR disallows {kind:?}"));
1348                        }
1349                    }
1350                    CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
1351                        // Pointers being unsize coerced should at least implement
1352                        // `CoerceUnsized`.
1353                        if !self.predicate_must_hold_modulo_regions(ty::TraitRef::new(
1354                            self.tcx,
1355                            self.tcx.require_lang_item(
1356                                LangItem::CoerceUnsized,
1357                                self.body.source_info(location).span,
1358                            ),
1359                            [op_ty, *target_type],
1360                        )) {
1361                            self.fail(location, format!("Unsize coercion, but `{op_ty}` isn't coercible to `{target_type}`"));
1362                        }
1363                    }
1364                    CastKind::IntToInt | CastKind::IntToFloat => {
1365                        let input_valid = op_ty.is_integral() || op_ty.is_char() || op_ty.is_bool();
1366                        let target_valid = target_type.is_numeric() || target_type.is_char();
1367                        if !input_valid || !target_valid {
1368                            self.fail(
1369                                location,
1370                                format!("Wrong cast kind {kind:?} for the type {op_ty}"),
1371                            );
1372                        }
1373                    }
1374                    CastKind::FnPtrToPtr => {
1375                        check_kinds!(
1376                            op_ty,
1377                            "CastKind::{kind:?} input must be a fn pointer, not {:?}",
1378                            ty::FnPtr(..)
1379                        );
1380                        check_kinds!(
1381                            target_type,
1382                            "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1383                            ty::RawPtr(..)
1384                        );
1385                    }
1386                    CastKind::PtrToPtr => {
1387                        check_kinds!(
1388                            op_ty,
1389                            "CastKind::{kind:?} input must be a raw pointer, not {:?}",
1390                            ty::RawPtr(..)
1391                        );
1392                        check_kinds!(
1393                            target_type,
1394                            "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1395                            ty::RawPtr(..)
1396                        );
1397                    }
1398                    CastKind::FloatToFloat | CastKind::FloatToInt => {
1399                        if !op_ty.is_floating_point() || !target_type.is_numeric() {
1400                            self.fail(
1401                                location,
1402                                format!(
1403                                    "Trying to cast non 'Float' as {kind:?} into {target_type:?}"
1404                                ),
1405                            );
1406                        }
1407                    }
1408                    CastKind::Transmute | CastKind::BoxDerefTransmute => {
1409                        // Unlike `mem::transmute`, a MIR `Transmute` is well-formed
1410                        // for any two `Sized` types, just potentially UB to run.
1411
1412                        if !self
1413                            .tcx
1414                            .normalize_erasing_regions(
1415                                self.typing_env,
1416                                Unnormalized::new_wip(op_ty),
1417                            )
1418                            .is_sized(self.tcx, self.typing_env)
1419                        {
1420                            self.fail(
1421                                location,
1422                                format!("Cannot transmute from non-`Sized` type {op_ty}"),
1423                            );
1424                        }
1425                        if !self
1426                            .tcx
1427                            .normalize_erasing_regions(
1428                                self.typing_env,
1429                                Unnormalized::new_wip(*target_type),
1430                            )
1431                            .is_sized(self.tcx, self.typing_env)
1432                        {
1433                            self.fail(
1434                                location,
1435                                format!("Cannot transmute to non-`Sized` type {target_type:?}"),
1436                            );
1437                        }
1438
1439                        if matches!(kind, CastKind::BoxDerefTransmute) {
1440                            if !target_type.is_raw_ptr() {
1441                                self.fail(
1442                                    location,
1443                                    format!(
1444                                        "Cannot BoxDerefTransmute to non-pointer type {target_type}"
1445                                    ),
1446                                );
1447                            }
1448                        }
1449                    }
1450                    CastKind::Subtype => {
1451                        if !util::sub_types(self.tcx, self.typing_env, op_ty, *target_type) {
1452                            self.fail(
1453                                location,
1454                                format!("Failed subtyping {op_ty} and {target_type}"),
1455                            )
1456                        }
1457                    }
1458                }
1459            }
1460            Rvalue::Repeat(_, _)
1461            | Rvalue::ThreadLocalRef(_)
1462            | Rvalue::RawPtr(_, _)
1463            | Rvalue::Discriminant(_) => {}
1464
1465            Rvalue::WrapUnsafeBinder(op, ty) => {
1466                let unwrapped_ty = op.ty(self.body, self.tcx);
1467                let ty::UnsafeBinder(binder_ty) = *ty.kind() else {
1468                    self.fail(
1469                        location,
1470                        format!("WrapUnsafeBinder does not produce a ty::UnsafeBinder"),
1471                    );
1472                    return;
1473                };
1474                let binder_inner_ty = self.tcx.instantiate_bound_regions_with_erased(*binder_ty);
1475                if !self.mir_assign_valid_types(unwrapped_ty, binder_inner_ty) {
1476                    self.fail(
1477                        location,
1478                        format!("Cannot wrap {unwrapped_ty} into unsafe binder {binder_ty:?}"),
1479                    );
1480                }
1481            }
1482        }
1483        self.super_rvalue(rvalue, location);
1484    }
1485
1486    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1487        match &statement.kind {
1488            StatementKind::Assign((dest, rvalue)) => {
1489                // LHS and RHS of the assignment must have the same type.
1490                let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
1491                let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
1492
1493                if !self.mir_assign_valid_types(right_ty, left_ty) {
1494                    self.fail(
1495                        location,
1496                        format!(
1497                            "encountered `{:?}` with incompatible types:\n\
1498                            left-hand side has type: {}\n\
1499                            right-hand side has type: {}",
1500                            statement.kind, left_ty, right_ty,
1501                        ),
1502                    );
1503                }
1504
1505                if let Some(local) = dest.as_local()
1506                    && let ClearCrossCrate::Set(LocalInfo::DerefTemp) =
1507                        self.body.local_decls[local].local_info
1508                    && !matches!(rvalue, Rvalue::CopyForDeref(_))
1509                {
1510                    self.fail(location, "assignment to a `DerefTemp` must use `CopyForDeref`")
1511                }
1512            }
1513            StatementKind::AscribeUserType(..) => {
1514                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1515                    self.fail(
1516                        location,
1517                        "`AscribeUserType` should have been removed after drop lowering phase",
1518                    );
1519                }
1520            }
1521            StatementKind::FakeRead(..) => {
1522                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1523                    self.fail(
1524                        location,
1525                        "`FakeRead` should have been removed after drop lowering phase",
1526                    );
1527                }
1528            }
1529            StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(op)) => {
1530                let ty = op.ty(&self.body.local_decls, self.tcx);
1531                if !ty.is_bool() {
1532                    self.fail(
1533                        location,
1534                        format!("`assume` argument must be `bool`, but got: `{ty}`"),
1535                    );
1536                }
1537            }
1538            StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(
1539                CopyNonOverlapping { src, dst, count },
1540            )) => {
1541                let src_ty = src.ty(&self.body.local_decls, self.tcx);
1542                let op_src_ty = if let Some(src_deref) = src_ty.builtin_deref(true) {
1543                    src_deref
1544                } else {
1545                    self.fail(
1546                        location,
1547                        format!("Expected src to be ptr in copy_nonoverlapping, got: {src_ty}"),
1548                    );
1549                    return;
1550                };
1551                let dst_ty = dst.ty(&self.body.local_decls, self.tcx);
1552                let op_dst_ty = if let Some(dst_deref) = dst_ty.builtin_deref(true) {
1553                    dst_deref
1554                } else {
1555                    self.fail(
1556                        location,
1557                        format!("Expected dst to be ptr in copy_nonoverlapping, got: {dst_ty}"),
1558                    );
1559                    return;
1560                };
1561                // since CopyNonOverlapping is parametrized by 1 type,
1562                // we only need to check that they are equal and not keep an extra parameter.
1563                if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) {
1564                    self.fail(location, format!("bad arg ({op_src_ty} != {op_dst_ty})"));
1565                }
1566
1567                let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx);
1568                if op_cnt_ty != self.tcx.types.usize {
1569                    self.fail(location, format!("bad arg ({op_cnt_ty} != usize)"))
1570                }
1571            }
1572            StatementKind::SetDiscriminant { place, .. } => {
1573                if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial) {
1574                    self.fail(location, "`SetDiscriminant`is not allowed until deaggregation");
1575                }
1576                let pty = place.ty(&self.body.local_decls, self.tcx).ty;
1577                if !matches!(
1578                    pty.kind(),
1579                    ty::Adt(..)
1580                        | ty::Coroutine(..)
1581                        | ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. })
1582                ) {
1583                    self.fail(
1584                        location,
1585                        format!(
1586                            "`SetDiscriminant` is only allowed on ADTs and coroutines, not {pty}"
1587                        ),
1588                    );
1589                }
1590            }
1591            StatementKind::StorageLive(_)
1592            | StatementKind::StorageDead(_)
1593            | StatementKind::Coverage(_)
1594            | StatementKind::ConstEvalCounter
1595            | StatementKind::PlaceMention(..)
1596            | StatementKind::BackwardIncompatibleDropHint { .. }
1597            | StatementKind::Nop => {}
1598        }
1599
1600        self.super_statement(statement, location);
1601    }
1602
1603    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1604        match &terminator.kind {
1605            TerminatorKind::SwitchInt { targets, discr } => {
1606                let switch_ty = discr.ty(&self.body.local_decls, self.tcx);
1607
1608                let target_width = self.tcx.sess.target.pointer_width;
1609
1610                let size = Size::from_bits(match switch_ty.kind() {
1611                    ty::Uint(uint) => uint.normalize(target_width).bit_width().unwrap(),
1612                    ty::Int(int) => int.normalize(target_width).bit_width().unwrap(),
1613                    ty::Char => 32,
1614                    ty::Bool => 1,
1615                    other => bug!("unhandled type: {:?}", other),
1616                });
1617
1618                for (value, _) in targets.iter() {
1619                    if ScalarInt::try_from_uint(value, size).is_none() {
1620                        self.fail(
1621                            location,
1622                            format!("the value {value:#x} is not a proper {switch_ty}"),
1623                        )
1624                    }
1625                }
1626            }
1627            TerminatorKind::Call { func, .. } | TerminatorKind::TailCall { func, .. } => {
1628                let func_ty = func.ty(&self.body.local_decls, self.tcx);
1629                match func_ty.kind() {
1630                    ty::FnPtr(..) | ty::FnDef(..) => {}
1631                    _ => self.fail(
1632                        location,
1633                        format!(
1634                            "encountered non-callable type {func_ty} in `{}` terminator",
1635                            terminator.kind.name()
1636                        ),
1637                    ),
1638                }
1639
1640                if let TerminatorKind::TailCall { .. } = terminator.kind {
1641                    // FIXME(explicit_tail_calls): implement tail-call specific checks here (such
1642                    // as signature matching, forbidding closures, etc)
1643                }
1644            }
1645            TerminatorKind::Assert { cond, .. } => {
1646                let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
1647                if cond_ty != self.tcx.types.bool {
1648                    self.fail(
1649                        location,
1650                        format!(
1651                            "encountered non-boolean condition of type {cond_ty} in `Assert` terminator"
1652                        ),
1653                    );
1654                }
1655            }
1656            TerminatorKind::Goto { .. }
1657            | TerminatorKind::Drop { .. }
1658            | TerminatorKind::Yield { .. }
1659            | TerminatorKind::FalseEdge { .. }
1660            | TerminatorKind::FalseUnwind { .. }
1661            | TerminatorKind::InlineAsm { .. }
1662            | TerminatorKind::CoroutineDrop
1663            | TerminatorKind::UnwindResume
1664            | TerminatorKind::UnwindTerminate(_)
1665            | TerminatorKind::Return
1666            | TerminatorKind::Unreachable => {}
1667        }
1668
1669        self.super_terminator(terminator, location);
1670    }
1671
1672    fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
1673        if let ClearCrossCrate::Set(LocalInfo::DerefTemp) = local_decl.local_info {
1674            if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1675                self.fail(
1676                    START_BLOCK.start_location(),
1677                    "`DerefTemp` should have been removed in runtime MIR",
1678                );
1679            } else if local_decl.ty.builtin_deref(true).is_none() {
1680                self.fail(
1681                    START_BLOCK.start_location(),
1682                    "`DerefTemp` should only be used for dereferenceable types",
1683                )
1684            }
1685        }
1686
1687        self.super_local_decl(local, local_decl);
1688    }
1689}
1690
1691pub(super) fn validate_debuginfos<'tcx>(body: &Body<'tcx>) -> Vec<(Location, String)> {
1692    let mut debuginfo_checker =
1693        DebuginfoChecker { debuginfo_locals: debuginfo_locals(body), failures: Vec::new() };
1694    debuginfo_checker.visit_body(body);
1695    debuginfo_checker.failures
1696}
1697
1698struct DebuginfoChecker {
1699    debuginfo_locals: DenseBitSet<Local>,
1700    failures: Vec<(Location, String)>,
1701}
1702
1703impl<'tcx> Visitor<'tcx> for DebuginfoChecker {
1704    fn visit_statement_debuginfo(
1705        &mut self,
1706        stmt_debuginfo: &StmtDebugInfo<'tcx>,
1707        location: Location,
1708    ) {
1709        let local = match stmt_debuginfo {
1710            StmtDebugInfo::AssignRef(local, _) | StmtDebugInfo::InvalidAssign(local) => *local,
1711        };
1712        if !self.debuginfo_locals.contains(local) {
1713            self.failures.push((location, format!("{local:?} is not in debuginfo")));
1714        }
1715    }
1716}