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> {
85 fn fail(&self, location: Location, msg: impl AsRef<str>) {
86 let span = self.body.source_info(location).span;
87 // We use `delay_span_bug` as we might see broken MIR when other errors have already
89 self.tcx.sess.diagnostic().delay_span_bug(
92 "broken MIR in {:?} ({}) at {:?}:\n{}",
93 self.body.source.instance,
101 fn check_edge(&self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) {
102 if bb == START_BLOCK {
103 self.fail(location, "start block must not have predecessors")
105 if let Some(bb) = self.body.basic_blocks.get(bb) {
106 let src = self.body.basic_blocks.get(location.block).unwrap();
107 match (src.is_cleanup, bb.is_cleanup, edge_kind) {
108 // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges
109 (false, false, EdgeKind::Normal)
110 // Non-cleanup blocks can jump to cleanup blocks along unwind edges
111 | (false, true, EdgeKind::Unwind)
112 // Cleanup blocks can jump to cleanup blocks along non-unwind edges
113 | (true, true, EdgeKind::Normal) => {}
114 // All other jumps are invalid
119 "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})",
129 self.fail(location, format!("encountered jump to invalid basic block {:?}", bb))
133 /// Check if src can be assigned into dest.
134 /// This is not precise, it will accept some incorrect assignments.
135 fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
136 // Fast path before we normalize.
138 // Equal types, all is good.
141 // Normalization reveals opaque types, but we may be validating MIR while computing
142 // said opaque types, causing cycles.
143 if (src, dest).has_opaque_types() {
147 crate::util::is_subtype(self.tcx, self.param_env, src, dest)
151 impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
152 fn visit_local(&mut self, local: Local, context: PlaceContext, location: Location) {
153 if self.body.local_decls.get(local).is_none() {
156 format!("local {:?} has no corresponding declaration in `body.local_decls`", local),
160 if self.reachable_blocks.contains(location.block) && context.is_use() {
161 // We check that the local is live whenever it is used. Technically, violating this
162 // restriction is only UB and not actually indicative of not well-formed MIR. This means
163 // that an optimization which turns MIR that already has UB into MIR that fails this
164 // check is not necessarily wrong. However, we have no such optimizations at the moment,
165 // and so we include this check anyway to help us catch bugs. If you happen to write an
166 // optimization that might cause this to incorrectly fire, feel free to remove this
168 self.storage_liveness.seek_after_primary_effect(location);
169 let locals_with_storage = self.storage_liveness.get();
170 if !locals_with_storage.contains(local) {
171 self.fail(location, format!("use of local {:?}, which has no storage here", local));
176 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
177 // This check is somewhat expensive, so only run it when -Zvalidate-mir is passed.
178 if self.tcx.sess.opts.unstable_opts.validate_mir
179 && self.mir_phase < MirPhase::Runtime(RuntimePhase::Initial)
181 // `Operand::Copy` is only supposed to be used with `Copy` types.
182 if let Operand::Copy(place) = operand {
183 let ty = place.ty(&self.body.local_decls, self.tcx).ty;
185 if !ty.is_copy_modulo_regions(self.tcx, self.param_env) {
186 self.fail(location, format!("`Operand::Copy` with non-`Copy` type {}", ty));
191 self.super_operand(operand, location);
194 fn visit_projection_elem(
197 proj_base: &[PlaceElem<'tcx>],
198 elem: PlaceElem<'tcx>,
199 context: PlaceContext,
203 ProjectionElem::Index(index) => {
204 let index_ty = self.body.local_decls[index].ty;
205 if index_ty != self.tcx.types.usize {
206 self.fail(location, format!("bad index ({:?} != usize)", index_ty))
209 ProjectionElem::Deref
210 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::PostCleanup) =>
212 let base_ty = Place::ty_from(local, proj_base, &self.body.local_decls, self.tcx).ty;
214 if base_ty.is_box() {
217 format!("{:?} dereferenced after ElaborateBoxDerefs", base_ty),
221 ProjectionElem::Field(f, ty) => {
222 let parent = Place { local, projection: self.tcx.intern_place_elems(proj_base) };
223 let parent_ty = parent.ty(&self.body.local_decls, self.tcx);
224 let fail_out_of_bounds = |this: &Self, location| {
225 this.fail(location, format!("Out of bounds field {:?} for {:?}", f, parent_ty));
227 let check_equal = |this: &Self, location, f_ty| {
228 if !this.mir_assign_valid_types(ty, f_ty) {
232 "Field projection `{:?}.{:?}` specified type `{:?}`, but actual type is `{:?}`",
239 let kind = match parent_ty.ty.kind() {
240 &ty::Opaque(def_id, substs) => {
241 self.tcx.bound_type_of(def_id).subst(self.tcx, substs).kind()
247 ty::Tuple(fields) => {
248 let Some(f_ty) = fields.get(f.as_usize()) else {
249 fail_out_of_bounds(self, location);
252 check_equal(self, location, *f_ty);
254 ty::Adt(adt_def, substs) => {
255 let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
256 let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
257 fail_out_of_bounds(self, location);
260 check_equal(self, location, field.ty(self.tcx, substs));
262 ty::Closure(_, substs) => {
263 let substs = substs.as_closure();
264 let Some(f_ty) = substs.upvar_tys().nth(f.as_usize()) else {
265 fail_out_of_bounds(self, location);
268 check_equal(self, location, f_ty);
270 &ty::Generator(def_id, substs, _) => {
271 let f_ty = if let Some(var) = parent_ty.variant_index {
272 let gen_body = if def_id == self.body.source.def_id() {
275 self.tcx.optimized_mir(def_id)
278 let Some(layout) = gen_body.generator_layout() else {
279 self.fail(location, format!("No generator layout for {:?}", parent_ty));
283 let Some(&local) = layout.variant_fields[var].get(f) else {
284 fail_out_of_bounds(self, location);
288 let Some(&f_ty) = layout.field_tys.get(local) else {
289 self.fail(location, format!("Out of bounds local {:?} for {:?}", local, parent_ty));
295 let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else {
296 fail_out_of_bounds(self, location);
303 check_equal(self, location, f_ty);
306 self.fail(location, format!("{:?} does not have fields", parent_ty.ty));
312 self.super_projection_elem(local, proj_base, elem, context, location);
315 fn visit_place(&mut self, place: &Place<'tcx>, cntxt: PlaceContext, location: Location) {
316 // Set off any `bug!`s in the type computation code
317 let _ = place.ty(&self.body.local_decls, self.tcx);
319 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial)
320 && place.projection.len() > 1
321 && cntxt != PlaceContext::NonUse(VarDebugInfo)
322 && place.projection[1..].contains(&ProjectionElem::Deref)
324 self.fail(location, format!("{:?}, has deref at the wrong place", place));
327 self.super_place(place, cntxt, location);
330 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
331 macro_rules! check_kinds {
332 ($t:expr, $text:literal, $($patterns:tt)*) => {
333 if !matches!(($t).kind(), $($patterns)*) {
334 self.fail(location, format!($text, $t));
339 Rvalue::Use(_) | Rvalue::CopyForDeref(_) => {}
340 Rvalue::Aggregate(agg_kind, _) => {
341 let disallowed = match **agg_kind {
342 AggregateKind::Array(..) => false,
343 _ => self.mir_phase >= MirPhase::Runtime(RuntimePhase::PostCleanup),
348 format!("{:?} have been lowered to field assignments", rvalue),
352 Rvalue::Ref(_, BorrowKind::Shallow, _) => {
353 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
356 "`Assign` statement with a `Shallow` borrow should have been removed in runtime MIR",
360 Rvalue::Ref(..) => {}
362 let pty = p.ty(&self.body.local_decls, self.tcx).ty;
365 "Cannot compute length of non-array type {:?}",
366 ty::Array(..) | ty::Slice(..)
369 Rvalue::BinaryOp(op, vals) => {
371 let a = vals.0.ty(&self.body.local_decls, self.tcx);
372 let b = vals.1.ty(&self.body.local_decls, self.tcx);
375 check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..));
376 if b != self.tcx.types.isize && b != self.tcx.types.usize {
377 self.fail(location, format!("Cannot offset by non-isize type {:?}", b));
380 Eq | Lt | Le | Ne | Ge | Gt => {
384 "Cannot compare type {:?}",
394 // The function pointer types can have lifetimes
395 if !self.mir_assign_valid_types(a, b) {
398 format!("Cannot compare unequal types {:?} and {:?}", a, b),
406 "Cannot shift non-integer type {:?}",
407 ty::Uint(..) | ty::Int(..)
411 BitAnd | BitOr | BitXor => {
415 "Cannot perform bitwise op on type {:?}",
416 ty::Uint(..) | ty::Int(..) | ty::Bool
423 "Cannot perform bitwise op on unequal types {:?} and {:?}",
429 Add | Sub | Mul | Div | Rem => {
433 "Cannot perform arithmetic on type {:?}",
434 ty::Uint(..) | ty::Int(..) | ty::Float(..)
441 "Cannot perform arithmetic on unequal types {:?} and {:?}",
449 Rvalue::CheckedBinaryOp(op, vals) => {
451 let a = vals.0.ty(&self.body.local_decls, self.tcx);
452 let b = vals.1.ty(&self.body.local_decls, self.tcx);
458 "Cannot perform checked arithmetic on type {:?}",
459 ty::Uint(..) | ty::Int(..)
466 "Cannot perform checked arithmetic on unequal types {:?} and {:?}",
476 "Cannot perform checked shift on non-integer type {:?}",
477 ty::Uint(..) | ty::Int(..)
481 _ => self.fail(location, format!("There is no checked version of {:?}", op)),
484 Rvalue::UnaryOp(op, operand) => {
485 let a = operand.ty(&self.body.local_decls, self.tcx);
488 check_kinds!(a, "Cannot negate type {:?}", ty::Int(..) | ty::Float(..))
493 "Cannot binary not type {:?}",
494 ty::Int(..) | ty::Uint(..) | ty::Bool
499 Rvalue::ShallowInitBox(operand, _) => {
500 let a = operand.ty(&self.body.local_decls, self.tcx);
501 check_kinds!(a, "Cannot shallow init type {:?}", ty::RawPtr(..));
503 Rvalue::Cast(kind, operand, target_type) => {
504 let op_ty = operand.ty(self.body, self.tcx);
506 CastKind::DynStar => {
507 // FIXME(dyn-star): make sure nothing needs to be done here.
509 // FIXME: Add Checks for these
510 CastKind::PointerFromExposedAddress
511 | CastKind::PointerExposeAddress
512 | CastKind::Pointer(_) => {}
513 CastKind::IntToInt | CastKind::IntToFloat => {
514 let input_valid = op_ty.is_integral() || op_ty.is_char() || op_ty.is_bool();
515 let target_valid = target_type.is_numeric() || target_type.is_char();
516 if !input_valid || !target_valid {
519 format!("Wrong cast kind {kind:?} for the type {op_ty}",),
523 CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
524 if !(op_ty.is_any_ptr() && target_type.is_unsafe_ptr()) {
525 self.fail(location, "Can't cast {op_ty} into 'Ptr'");
528 CastKind::FloatToFloat | CastKind::FloatToInt => {
529 if !op_ty.is_floating_point() || !target_type.is_numeric() {
533 "Trying to cast non 'Float' as {kind:?} into {target_type:?}"
541 | Rvalue::ThreadLocalRef(_)
542 | Rvalue::AddressOf(_, _)
543 | Rvalue::NullaryOp(_, _)
544 | Rvalue::Discriminant(_) => {}
546 self.super_rvalue(rvalue, location);
549 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
550 match &statement.kind {
551 StatementKind::Assign(box (dest, rvalue)) => {
552 // LHS and RHS of the assignment must have the same type.
553 let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
554 let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
555 if !self.mir_assign_valid_types(right_ty, left_ty) {
559 "encountered `{:?}` with incompatible types:\n\
560 left-hand side has type: {}\n\
561 right-hand side has type: {}",
562 statement.kind, left_ty, right_ty,
566 if let Rvalue::CopyForDeref(place) = rvalue {
567 if !place.ty(&self.body.local_decls, self.tcx).ty.builtin_deref(true).is_some()
571 "`CopyForDeref` should only be used for dereferenceable types",
575 // FIXME(JakobDegen): Check this for all rvalues, not just this one.
576 if let Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) = rvalue {
577 // The sides of an assignment must not alias. Currently this just checks whether
578 // the places are identical.
582 "encountered `Assign` statement with overlapping memory",
587 StatementKind::AscribeUserType(..) => {
588 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
591 "`AscribeUserType` should have been removed after drop lowering phase",
595 StatementKind::FakeRead(..) => {
596 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
599 "`FakeRead` should have been removed after drop lowering phase",
603 StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => {
604 let ty = op.ty(&self.body.local_decls, self.tcx);
608 format!("`assume` argument must be `bool`, but got: `{}`", ty),
612 StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(
613 CopyNonOverlapping { src, dst, count },
615 let src_ty = src.ty(&self.body.local_decls, self.tcx);
616 let op_src_ty = if let Some(src_deref) = src_ty.builtin_deref(true) {
621 format!("Expected src to be ptr in copy_nonoverlapping, got: {}", src_ty),
625 let dst_ty = dst.ty(&self.body.local_decls, self.tcx);
626 let op_dst_ty = if let Some(dst_deref) = dst_ty.builtin_deref(true) {
631 format!("Expected dst to be ptr in copy_nonoverlapping, got: {}", dst_ty),
635 // since CopyNonOverlapping is parametrized by 1 type,
636 // we only need to check that they are equal and not keep an extra parameter.
637 if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) {
638 self.fail(location, format!("bad arg ({:?} != {:?})", op_src_ty, op_dst_ty));
641 let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx);
642 if op_cnt_ty != self.tcx.types.usize {
643 self.fail(location, format!("bad arg ({:?} != usize)", op_cnt_ty))
646 StatementKind::SetDiscriminant { place, .. } => {
647 if self.mir_phase < MirPhase::Runtime(RuntimePhase::Initial) {
648 self.fail(location, "`SetDiscriminant`is not allowed until deaggregation");
650 let pty = place.ty(&self.body.local_decls, self.tcx).ty.kind();
651 if !matches!(pty, ty::Adt(..) | ty::Generator(..) | ty::Opaque(..)) {
655 "`SetDiscriminant` is only allowed on ADTs and generators, not {:?}",
661 StatementKind::Deinit(..) => {
662 if self.mir_phase < MirPhase::Runtime(RuntimePhase::Initial) {
663 self.fail(location, "`Deinit`is not allowed until deaggregation");
666 StatementKind::Retag(_, _) => {
667 // FIXME(JakobDegen) The validator should check that `self.mir_phase <
668 // DropsLowered`. However, this causes ICEs with generation of drop shims, which
669 // seem to fail to set their `MirPhase` correctly.
671 StatementKind::StorageLive(..)
672 | StatementKind::StorageDead(..)
673 | StatementKind::Coverage(_)
674 | StatementKind::Nop => {}
677 self.super_statement(statement, location);
680 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
681 match &terminator.kind {
682 TerminatorKind::Goto { target } => {
683 self.check_edge(location, *target, EdgeKind::Normal);
685 TerminatorKind::SwitchInt { targets, switch_ty, discr } => {
686 let ty = discr.ty(&self.body.local_decls, self.tcx);
687 if ty != *switch_ty {
691 "encountered `SwitchInt` terminator with type mismatch: {:?} != {:?}",
697 let target_width = self.tcx.sess.target.pointer_width;
699 let size = Size::from_bits(match switch_ty.kind() {
700 ty::Uint(uint) => uint.normalize(target_width).bit_width().unwrap(),
701 ty::Int(int) => int.normalize(target_width).bit_width().unwrap(),
704 other => bug!("unhandled type: {:?}", other),
707 for (value, target) in targets.iter() {
708 if Scalar::<()>::try_from_uint(value, size).is_none() {
711 format!("the value {:#x} is not a proper {:?}", value, switch_ty),
715 self.check_edge(location, target, EdgeKind::Normal);
717 self.check_edge(location, targets.otherwise(), EdgeKind::Normal);
719 self.value_cache.clear();
720 self.value_cache.extend(targets.iter().map(|(value, _)| value));
721 let all_len = self.value_cache.len();
722 self.value_cache.sort_unstable();
723 self.value_cache.dedup();
724 let has_duplicates = all_len != self.value_cache.len();
729 "duplicated values in `SwitchInt` terminator: {:?}",
735 TerminatorKind::Drop { target, unwind, .. } => {
736 self.check_edge(location, *target, EdgeKind::Normal);
737 if let Some(unwind) = unwind {
738 self.check_edge(location, *unwind, EdgeKind::Unwind);
741 TerminatorKind::DropAndReplace { target, unwind, .. } => {
742 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
745 "`DropAndReplace` should have been removed during drop elaboration",
748 self.check_edge(location, *target, EdgeKind::Normal);
749 if let Some(unwind) = unwind {
750 self.check_edge(location, *unwind, EdgeKind::Unwind);
753 TerminatorKind::Call { func, args, destination, target, cleanup, .. } => {
754 let func_ty = func.ty(&self.body.local_decls, self.tcx);
755 match func_ty.kind() {
756 ty::FnPtr(..) | ty::FnDef(..) => {}
759 format!("encountered non-callable type {} in `Call` terminator", func_ty),
762 if let Some(target) = target {
763 self.check_edge(location, *target, EdgeKind::Normal);
765 if let Some(cleanup) = cleanup {
766 self.check_edge(location, *cleanup, EdgeKind::Unwind);
769 // The call destination place and Operand::Move place used as an argument might be
770 // passed by a reference to the callee. Consequently they must be non-overlapping.
771 // Currently this simply checks for duplicate places.
772 self.place_cache.clear();
773 self.place_cache.push(destination.as_ref());
775 if let Operand::Move(place) = arg {
776 self.place_cache.push(place.as_ref());
779 let all_len = self.place_cache.len();
780 let mut dedup = FxHashSet::default();
781 self.place_cache.retain(|p| dedup.insert(*p));
782 let has_duplicates = all_len != self.place_cache.len();
787 "encountered overlapping memory in `Call` terminator: {:?}",
793 TerminatorKind::Assert { cond, target, cleanup, .. } => {
794 let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
795 if cond_ty != self.tcx.types.bool {
799 "encountered non-boolean condition of type {} in `Assert` terminator",
804 self.check_edge(location, *target, EdgeKind::Normal);
805 if let Some(cleanup) = cleanup {
806 self.check_edge(location, *cleanup, EdgeKind::Unwind);
809 TerminatorKind::Yield { resume, drop, .. } => {
810 if self.body.generator.is_none() {
811 self.fail(location, "`Yield` cannot appear outside generator bodies");
813 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
814 self.fail(location, "`Yield` should have been replaced by generator lowering");
816 self.check_edge(location, *resume, EdgeKind::Normal);
817 if let Some(drop) = drop {
818 self.check_edge(location, *drop, EdgeKind::Normal);
821 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
822 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
825 "`FalseEdge` should have been removed after drop elaboration",
828 self.check_edge(location, *real_target, EdgeKind::Normal);
829 self.check_edge(location, *imaginary_target, EdgeKind::Normal);
831 TerminatorKind::FalseUnwind { real_target, unwind } => {
832 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
835 "`FalseUnwind` should have been removed after drop elaboration",
838 self.check_edge(location, *real_target, EdgeKind::Normal);
839 if let Some(unwind) = unwind {
840 self.check_edge(location, *unwind, EdgeKind::Unwind);
843 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
844 if let Some(destination) = destination {
845 self.check_edge(location, *destination, EdgeKind::Normal);
847 if let Some(cleanup) = cleanup {
848 self.check_edge(location, *cleanup, EdgeKind::Unwind);
851 TerminatorKind::GeneratorDrop => {
852 if self.body.generator.is_none() {
853 self.fail(location, "`GeneratorDrop` cannot appear outside generator bodies");
855 if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) {
858 "`GeneratorDrop` should have been replaced by generator lowering",
862 TerminatorKind::Resume | TerminatorKind::Abort => {
863 let bb = location.block;
864 if !self.body.basic_blocks[bb].is_cleanup {
865 self.fail(location, "Cannot `Resume` or `Abort` from non-cleanup basic block")
868 TerminatorKind::Return => {
869 let bb = location.block;
870 if self.body.basic_blocks[bb].is_cleanup {
871 self.fail(location, "Cannot `Return` from cleanup basic block")
874 TerminatorKind::Unreachable => {}
877 self.super_terminator(terminator, location);
880 fn visit_source_scope(&mut self, scope: SourceScope) {
881 if self.body.source_scopes.get(scope).is_none() {
882 self.tcx.sess.diagnostic().delay_span_bug(
885 "broken MIR in {:?} ({}):\ninvalid source scope {:?}",
886 self.body.source.instance, self.when, scope,