1 //! Validates the MIR to ensure that invariants are upheld.
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_index::bit_set::BitSet;
5 use rustc_middle::mir::interpret::Scalar;
6 use rustc_middle::mir::visit::NonUseContext::VarDebugInfo;
7 use rustc_middle::mir::visit::{PlaceContext, Visitor};
8 use rustc_middle::mir::{
9 traversal, AggregateKind, BasicBlock, BinOp, Body, BorrowKind, CastKind, CopyNonOverlapping,
10 Local, Location, MirPass, MirPhase, NonDivergingIntrinsic, Operand, Place, PlaceElem, PlaceRef,
11 ProjectionElem, RuntimePhase, Rvalue, SourceScope, Statement, StatementKind, Terminator,
12 TerminatorKind, UnOp, START_BLOCK,
14 use rustc_middle::ty::{self, InstanceDef, ParamEnv, Ty, TyCtxt, TypeVisitable};
15 use rustc_mir_dataflow::impls::MaybeStorageLive;
16 use rustc_mir_dataflow::storage::always_storage_live_locals;
17 use rustc_mir_dataflow::{Analysis, ResultsCursor};
18 use rustc_target::abi::{Size, VariantIdx};
20 #[derive(Copy, Clone, Debug)]
26 pub struct Validator {
27 /// Describes at which point in the pipeline this validation is happening.
29 /// The phase for which we are upholding the dialect. If the given phase forbids a specific
30 /// element, this validator will now emit errors if that specific element is encountered.
31 /// Note that phases that change the dialect cause all *following* phases to check the
32 /// invariants of the new dialect. A phase that changes dialects never checks the new invariants
34 pub mir_phase: MirPhase,
37 impl<'tcx> MirPass<'tcx> for Validator {
38 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
39 // FIXME(JakobDegen): These bodies never instantiated in codegend anyway, so it's not
40 // terribly important that they pass the validator. However, I think other passes might
41 // still see them, in which case they might be surprised. It would probably be better if we
42 // didn't put this through the MIR pipeline at all.
43 if matches!(body.source.instance, InstanceDef::Intrinsic(..) | InstanceDef::Virtual(..)) {
46 let def_id = body.source.def_id();
47 let param_env = tcx.param_env(def_id);
48 let mir_phase = self.mir_phase;
50 let always_live_locals = always_storage_live_locals(body);
51 let storage_liveness = MaybeStorageLive::new(always_live_locals)
52 .into_engine(tcx, body)
53 .iterate_to_fixpoint()
54 .into_results_cursor(body);
62 reachable_blocks: traversal::reachable_as_bitset(body),
64 place_cache: Vec::new(),
65 value_cache: Vec::new(),
71 struct TypeChecker<'a, 'tcx> {
75 param_env: ParamEnv<'tcx>,
77 reachable_blocks: BitSet<BasicBlock>,
78 storage_liveness: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
79 place_cache: Vec<PlaceRef<'tcx>>,
80 value_cache: Vec<u128>,
83 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
84 fn fail(&self, location: Location, msg: impl AsRef<str>) {
85 let span = self.body.source_info(location).span;
86 // We use `delay_span_bug` as we might see broken MIR when other errors have already
88 self.tcx.sess.diagnostic().delay_span_bug(
91 "broken MIR in {:?} ({}) at {:?}:\n{}",
92 self.body.source.instance,
100 fn check_edge(&self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) {
101 if bb == START_BLOCK {
102 self.fail(location, "start block must not have predecessors")
104 if let Some(bb) = self.body.basic_blocks.get(bb) {
105 let src = self.body.basic_blocks.get(location.block).unwrap();
106 match (src.is_cleanup, bb.is_cleanup, edge_kind) {
107 // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges
108 (false, false, EdgeKind::Normal)
109 // Non-cleanup blocks can jump to cleanup blocks along unwind edges
110 | (false, true, EdgeKind::Unwind)
111 // Cleanup blocks can jump to cleanup blocks along non-unwind edges
112 | (true, true, EdgeKind::Normal) => {}
113 // All other jumps are invalid
118 "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})",
128 self.fail(location, format!("encountered jump to invalid basic block {:?}", bb))
132 /// Check if src can be assigned into dest.
133 /// This is not precise, it will accept some incorrect assignments.
134 fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
135 // Fast path before we normalize.
137 // Equal types, all is good.
140 // Normalization reveals opaque types, but we may be validating MIR while computing
141 // said opaque types, causing cycles.
142 if (src, dest).has_opaque_types() {
146 crate::util::is_subtype(self.tcx, self.param_env, src, dest)
150 impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
151 fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
152 if self.body.local_decls.get(local).is_none() {
155 format!("local {:?} has no corresponding declaration in `body.local_decls`", local),
159 if self.reachable_blocks.contains(location.block) && context.is_use() {
160 // We check that the local is live whenever it is used. Technically, violating this
161 // restriction is only UB and not actually indicative of not well-formed MIR. This means
162 // that an optimization which turns MIR that already has UB into MIR that fails this
163 // check is not necessarily wrong. However, we have no such optimizations at the moment,
164 // and so we include this check anyway to help us catch bugs. If you happen to write an
165 // optimization that might cause this to incorrectly fire, feel free to remove this
167 self.storage_liveness.seek_after_primary_effect(location);
168 let locals_with_storage = self.storage_liveness.get();
169 if !locals_with_storage.contains(local) {
170 self.fail(location, format!("use of local {:?}, which has no storage here", local));
175 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
176 // This check is somewhat expensive, so only run it when -Zvalidate-mir is passed.
177 if self.tcx.sess.opts.unstable_opts.validate_mir
178 && self.mir_phase < MirPhase::Runtime(RuntimePhase::Initial)
180 // `Operand::Copy` is only supposed to be used with `Copy` types.
181 if let Operand::Copy(place) = operand {
182 let ty = place.ty(&self.body.local_decls, self.tcx).ty;
184 if !ty.is_copy_modulo_regions(self.tcx, self.param_env) {
185 self.fail(location, format!("`Operand::Copy` with non-`Copy` type {}", ty));
190 self.super_operand(operand, location);
193 fn visit_projection_elem(
196 proj_base: &[PlaceElem<'tcx>],
197 elem: PlaceElem<'tcx>,
198 context: PlaceContext,
202 ProjectionElem::Index(index) => {
203 let index_ty = self.body.local_decls[index].ty;
204 if index_ty != self.tcx.types.usize {
205 self.fail(location, format!("bad index ({:?} != usize)", index_ty))
208 ProjectionElem::Deref
209 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::PostCleanup) =>
211 let base_ty = Place::ty_from(local, proj_base, &self.body.local_decls, self.tcx).ty;
213 if base_ty.is_box() {
216 format!("{:?} dereferenced after ElaborateBoxDerefs", base_ty),
220 ProjectionElem::Field(f, ty) => {
221 let parent = Place { local, projection: self.tcx.intern_place_elems(proj_base) };
222 let parent_ty = parent.ty(&self.body.local_decls, self.tcx);
223 let fail_out_of_bounds = |this: &Self, location| {
224 this.fail(location, format!("Out of bounds field {:?} for {:?}", f, parent_ty));
226 let check_equal = |this: &Self, location, f_ty| {
227 if !this.mir_assign_valid_types(ty, f_ty) {
231 "Field projection `{:?}.{:?}` specified type `{:?}`, but actual type is `{:?}`",
238 let kind = match parent_ty.ty.kind() {
239 &ty::Opaque(def_id, substs) => {
240 self.tcx.bound_type_of(def_id).subst(self.tcx, substs).kind()
246 ty::Tuple(fields) => {
247 let Some(f_ty) = fields.get(f.as_usize()) else {
248 fail_out_of_bounds(self, location);
251 check_equal(self, location, *f_ty);
253 ty::Adt(adt_def, substs) => {
254 let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
255 let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
256 fail_out_of_bounds(self, location);
259 check_equal(self, location, field.ty(self.tcx, substs));
261 ty::Closure(_, substs) => {
262 let substs = substs.as_closure();
263 let Some(f_ty) = substs.upvar_tys().nth(f.as_usize()) else {
264 fail_out_of_bounds(self, location);
267 check_equal(self, location, f_ty);
269 &ty::Generator(def_id, substs, _) => {
270 let f_ty = if let Some(var) = parent_ty.variant_index {
271 let gen_body = if def_id == self.body.source.def_id() {
274 self.tcx.optimized_mir(def_id)
277 let Some(layout) = gen_body.generator_layout() else {
278 self.fail(location, format!("No generator layout for {:?}", parent_ty));
282 let Some(&local) = layout.variant_fields[var].get(f) else {
283 fail_out_of_bounds(self, location);
287 let Some(&f_ty) = layout.field_tys.get(local) else {
288 self.fail(location, format!("Out of bounds local {:?} for {:?}", local, parent_ty));
294 let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else {
295 fail_out_of_bounds(self, location);
302 check_equal(self, location, f_ty);
305 self.fail(location, format!("{:?} does not have fields", parent_ty.ty));
311 self.super_projection_elem(local, proj_base, elem, context, location);
314 fn visit_place(&mut self, place: &Place<'tcx>, cntxt: PlaceContext, location: Location) {
315 // Set off any `bug!`s in the type computation code
316 let _ = place.ty(&self.body.local_decls, self.tcx);
318 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial)
319 && place.projection.len() > 1
320 && cntxt != PlaceContext::NonUse(VarDebugInfo)
321 && place.projection[1..].contains(&ProjectionElem::Deref)
323 self.fail(location, format!("{:?}, has deref at the wrong place", place));
326 self.super_place(place, cntxt, location);
329 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
330 macro_rules! check_kinds {
331 ($t:expr, $text:literal, $($patterns:tt)*) => {
332 if !matches!(($t).kind(), $($patterns)*) {
333 self.fail(location, format!($text, $t));
338 Rvalue::Use(_) | Rvalue::CopyForDeref(_) => {}
339 Rvalue::Aggregate(agg_kind, _) => {
340 let disallowed = match **agg_kind {
341 AggregateKind::Array(..) => false,
342 _ => self.mir_phase >= MirPhase::Runtime(RuntimePhase::PostCleanup),
347 format!("{:?} have been lowered to field assignments", rvalue),
351 Rvalue::Ref(_, BorrowKind::Shallow, _) => {
352 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
355 "`Assign` statement with a `Shallow` borrow should have been removed in runtime MIR",
359 Rvalue::Ref(..) => {}
361 let pty = p.ty(&self.body.local_decls, self.tcx).ty;
364 "Cannot compute length of non-array type {:?}",
365 ty::Array(..) | ty::Slice(..)
368 Rvalue::BinaryOp(op, vals) => {
370 let a = vals.0.ty(&self.body.local_decls, self.tcx);
371 let b = vals.1.ty(&self.body.local_decls, self.tcx);
374 check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..));
375 if b != self.tcx.types.isize && b != self.tcx.types.usize {
376 self.fail(location, format!("Cannot offset by non-isize type {:?}", b));
379 Eq | Lt | Le | Ne | Ge | Gt => {
383 "Cannot compare type {:?}",
393 // The function pointer types can have lifetimes
394 if !self.mir_assign_valid_types(a, b) {
397 format!("Cannot compare unequal types {:?} and {:?}", a, b),
405 "Cannot shift non-integer type {:?}",
406 ty::Uint(..) | ty::Int(..)
410 BitAnd | BitOr | BitXor => {
414 "Cannot perform bitwise op on type {:?}",
415 ty::Uint(..) | ty::Int(..) | ty::Bool
422 "Cannot perform bitwise op on unequal types {:?} and {:?}",
428 Add | Sub | Mul | Div | Rem => {
432 "Cannot perform arithmetic on type {:?}",
433 ty::Uint(..) | ty::Int(..) | ty::Float(..)
440 "Cannot perform arithmetic on unequal types {:?} and {:?}",
448 Rvalue::CheckedBinaryOp(op, vals) => {
450 let a = vals.0.ty(&self.body.local_decls, self.tcx);
451 let b = vals.1.ty(&self.body.local_decls, self.tcx);
457 "Cannot perform checked arithmetic on type {:?}",
458 ty::Uint(..) | ty::Int(..)
465 "Cannot perform checked arithmetic on unequal types {:?} and {:?}",
475 "Cannot perform checked shift on non-integer type {:?}",
476 ty::Uint(..) | ty::Int(..)
480 _ => self.fail(location, format!("There is no checked version of {:?}", op)),
483 Rvalue::UnaryOp(op, operand) => {
484 let a = operand.ty(&self.body.local_decls, self.tcx);
487 check_kinds!(a, "Cannot negate type {:?}", ty::Int(..) | ty::Float(..))
492 "Cannot binary not type {:?}",
493 ty::Int(..) | ty::Uint(..) | ty::Bool
498 Rvalue::ShallowInitBox(operand, _) => {
499 let a = operand.ty(&self.body.local_decls, self.tcx);
500 check_kinds!(a, "Cannot shallow init type {:?}", ty::RawPtr(..));
502 Rvalue::Cast(kind, operand, target_type) => {
503 let op_ty = operand.ty(self.body, self.tcx);
505 CastKind::DynStar => {
506 // FIXME(dyn-star): make sure nothing needs to be done here.
508 // FIXME: Add Checks for these
509 CastKind::PointerFromExposedAddress
510 | CastKind::PointerExposeAddress
511 | CastKind::Pointer(_) => {}
512 CastKind::IntToInt | CastKind::IntToFloat => {
513 let input_valid = op_ty.is_integral() || op_ty.is_char() || op_ty.is_bool();
514 let target_valid = target_type.is_numeric() || target_type.is_char();
515 if !input_valid || !target_valid {
518 format!("Wrong cast kind {kind:?} for the type {op_ty}",),
522 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
523 if !(op_ty.is_any_ptr() && target_type.is_unsafe_ptr()) {
524 self.fail(location, "Can't cast {op_ty} into 'Ptr'");
527 CastKind::FloatToFloat | CastKind::FloatToInt => {
528 if !op_ty.is_floating_point() || !target_type.is_numeric() {
532 "Trying to cast non 'Float' as {kind:?} into {target_type:?}"
540 | Rvalue::ThreadLocalRef(_)
541 | Rvalue::AddressOf(_, _)
542 | Rvalue::NullaryOp(_, _)
543 | Rvalue::Discriminant(_) => {}
545 self.super_rvalue(rvalue, location);
548 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
549 match &statement.kind {
550 StatementKind::Assign(box (dest, rvalue)) => {
551 // LHS and RHS of the assignment must have the same type.
552 let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
553 let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
554 if !self.mir_assign_valid_types(right_ty, left_ty) {
558 "encountered `{:?}` with incompatible types:\n\
559 left-hand side has type: {}\n\
560 right-hand side has type: {}",
561 statement.kind, left_ty, right_ty,
565 if let Rvalue::CopyForDeref(place) = rvalue {
566 if !place.ty(&self.body.local_decls, self.tcx).ty.builtin_deref(true).is_some()
570 "`CopyForDeref` should only be used for dereferenceable types",
574 // FIXME(JakobDegen): Check this for all rvalues, not just this one.
575 if let Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) = rvalue {
576 // The sides of an assignment must not alias. Currently this just checks whether
577 // the places are identical.
581 "encountered `Assign` statement with overlapping memory",
586 StatementKind::AscribeUserType(..) => {
587 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
590 "`AscribeUserType` should have been removed after drop lowering phase",
594 StatementKind::FakeRead(..) => {
595 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
598 "`FakeRead` should have been removed after drop lowering phase",
602 StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => {
603 let ty = op.ty(&self.body.local_decls, self.tcx);
607 format!("`assume` argument must be `bool`, but got: `{}`", ty),
611 StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(
612 CopyNonOverlapping { src, dst, count },
614 let src_ty = src.ty(&self.body.local_decls, self.tcx);
615 let op_src_ty = if let Some(src_deref) = src_ty.builtin_deref(true) {
620 format!("Expected src to be ptr in copy_nonoverlapping, got: {}", src_ty),
624 let dst_ty = dst.ty(&self.body.local_decls, self.tcx);
625 let op_dst_ty = if let Some(dst_deref) = dst_ty.builtin_deref(true) {
630 format!("Expected dst to be ptr in copy_nonoverlapping, got: {}", dst_ty),
634 // since CopyNonOverlapping is parametrized by 1 type,
635 // we only need to check that they are equal and not keep an extra parameter.
636 if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) {
637 self.fail(location, format!("bad arg ({:?} != {:?})", op_src_ty, op_dst_ty));
640 let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx);
641 if op_cnt_ty != self.tcx.types.usize {
642 self.fail(location, format!("bad arg ({:?} != usize)", op_cnt_ty))
645 StatementKind::SetDiscriminant { place, .. } => {
646 if self.mir_phase < MirPhase::Runtime(RuntimePhase::Initial) {
647 self.fail(location, "`SetDiscriminant`is not allowed until deaggregation");
649 let pty = place.ty(&self.body.local_decls, self.tcx).ty.kind();
650 if !matches!(pty, ty::Adt(..) | ty::Generator(..) | ty::Opaque(..)) {
654 "`SetDiscriminant` is only allowed on ADTs and generators, not {:?}",
660 StatementKind::Deinit(..) => {
661 if self.mir_phase < MirPhase::Runtime(RuntimePhase::Initial) {
662 self.fail(location, "`Deinit`is not allowed until deaggregation");
665 StatementKind::Retag(_, _) => {
666 // FIXME(JakobDegen) The validator should check that `self.mir_phase <
667 // DropsLowered`. However, this causes ICEs with generation of drop shims, which
668 // seem to fail to set their `MirPhase` correctly.
670 StatementKind::StorageLive(..)
671 | StatementKind::StorageDead(..)
672 | StatementKind::Coverage(_)
673 | StatementKind::Nop => {}
676 self.super_statement(statement, location);
679 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
680 match &terminator.kind {
681 TerminatorKind::Goto { target } => {
682 self.check_edge(location, *target, EdgeKind::Normal);
684 TerminatorKind::SwitchInt { targets, switch_ty, discr } => {
685 let ty = discr.ty(&self.body.local_decls, self.tcx);
686 if ty != *switch_ty {
690 "encountered `SwitchInt` terminator with type mismatch: {:?} != {:?}",
696 let target_width = self.tcx.sess.target.pointer_width;
698 let size = Size::from_bits(match switch_ty.kind() {
699 ty::Uint(uint) => uint.normalize(target_width).bit_width().unwrap(),
700 ty::Int(int) => int.normalize(target_width).bit_width().unwrap(),
703 other => bug!("unhandled type: {:?}", other),
706 for (value, target) in targets.iter() {
707 if Scalar::<()>::try_from_uint(value, size).is_none() {
710 format!("the value {:#x} is not a proper {:?}", value, switch_ty),
714 self.check_edge(location, target, EdgeKind::Normal);
716 self.check_edge(location, targets.otherwise(), EdgeKind::Normal);
718 self.value_cache.clear();
719 self.value_cache.extend(targets.iter().map(|(value, _)| value));
720 let all_len = self.value_cache.len();
721 self.value_cache.sort_unstable();
722 self.value_cache.dedup();
723 let has_duplicates = all_len != self.value_cache.len();
728 "duplicated values in `SwitchInt` terminator: {:?}",
734 TerminatorKind::Drop { target, unwind, .. } => {
735 self.check_edge(location, *target, EdgeKind::Normal);
736 if let Some(unwind) = unwind {
737 self.check_edge(location, *unwind, EdgeKind::Unwind);
740 TerminatorKind::DropAndReplace { target, unwind, .. } => {
741 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
744 "`DropAndReplace` should have been removed during drop elaboration",
747 self.check_edge(location, *target, EdgeKind::Normal);
748 if let Some(unwind) = unwind {
749 self.check_edge(location, *unwind, EdgeKind::Unwind);
752 TerminatorKind::Call { func, args, destination, target, cleanup, .. } => {
753 let func_ty = func.ty(&self.body.local_decls, self.tcx);
754 match func_ty.kind() {
755 ty::FnPtr(..) | ty::FnDef(..) => {}
758 format!("encountered non-callable type {} in `Call` terminator", func_ty),
761 if let Some(target) = target {
762 self.check_edge(location, *target, EdgeKind::Normal);
764 if let Some(cleanup) = cleanup {
765 self.check_edge(location, *cleanup, EdgeKind::Unwind);
768 // The call destination place and Operand::Move place used as an argument might be
769 // passed by a reference to the callee. Consequently they must be non-overlapping.
770 // Currently this simply checks for duplicate places.
771 self.place_cache.clear();
772 self.place_cache.push(destination.as_ref());
774 if let Operand::Move(place) = arg {
775 self.place_cache.push(place.as_ref());
778 let all_len = self.place_cache.len();
779 let mut dedup = FxHashSet::default();
780 self.place_cache.retain(|p| dedup.insert(*p));
781 let has_duplicates = all_len != self.place_cache.len();
786 "encountered overlapping memory in `Call` terminator: {:?}",
792 TerminatorKind::Assert { cond, target, cleanup, .. } => {
793 let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
794 if cond_ty != self.tcx.types.bool {
798 "encountered non-boolean condition of type {} in `Assert` terminator",
803 self.check_edge(location, *target, EdgeKind::Normal);
804 if let Some(cleanup) = cleanup {
805 self.check_edge(location, *cleanup, EdgeKind::Unwind);
808 TerminatorKind::Yield { resume, drop, .. } => {
809 if self.body.generator.is_none() {
810 self.fail(location, "`Yield` cannot appear outside generator bodies");
812 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
813 self.fail(location, "`Yield` should have been replaced by generator lowering");
815 self.check_edge(location, *resume, EdgeKind::Normal);
816 if let Some(drop) = drop {
817 self.check_edge(location, *drop, EdgeKind::Normal);
820 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
821 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
824 "`FalseEdge` should have been removed after drop elaboration",
827 self.check_edge(location, *real_target, EdgeKind::Normal);
828 self.check_edge(location, *imaginary_target, EdgeKind::Normal);
830 TerminatorKind::FalseUnwind { real_target, unwind } => {
831 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
834 "`FalseUnwind` should have been removed after drop elaboration",
837 self.check_edge(location, *real_target, EdgeKind::Normal);
838 if let Some(unwind) = unwind {
839 self.check_edge(location, *unwind, EdgeKind::Unwind);
842 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
843 if let Some(destination) = destination {
844 self.check_edge(location, *destination, EdgeKind::Normal);
846 if let Some(cleanup) = cleanup {
847 self.check_edge(location, *cleanup, EdgeKind::Unwind);
850 TerminatorKind::GeneratorDrop => {
851 if self.body.generator.is_none() {
852 self.fail(location, "`GeneratorDrop` cannot appear outside generator bodies");
854 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
857 "`GeneratorDrop` should have been replaced by generator lowering",
861 TerminatorKind::Resume | TerminatorKind::Abort => {
862 let bb = location.block;
863 if !self.body.basic_blocks[bb].is_cleanup {
864 self.fail(location, "Cannot `Resume` or `Abort` from non-cleanup basic block")
867 TerminatorKind::Return => {
868 let bb = location.block;
869 if self.body.basic_blocks[bb].is_cleanup {
870 self.fail(location, "Cannot `Return` from cleanup basic block")
873 TerminatorKind::Unreachable => {}
876 self.super_terminator(terminator, location);
879 fn visit_source_scope(&mut self, scope: SourceScope) {
880 if self.body.source_scopes.get(scope).is_none() {
881 self.tcx.sess.diagnostic().delay_span_bug(
884 "broken MIR in {:?} ({}):\ninvalid source scope {:?}",
885 self.body.source.instance, self.when, scope,