1 //! Validates the MIR to ensure that invariants are upheld.
3 use crate::dataflow::impls::MaybeStorageLive;
4 use crate::dataflow::{Analysis, ResultsCursor};
5 use crate::util::storage::AlwaysLiveLocals;
8 use rustc_middle::mir::visit::{PlaceContext, Visitor};
9 use rustc_middle::mir::{
10 AggregateKind, BasicBlock, Body, BorrowKind, Local, Location, MirPhase, Operand, Rvalue,
11 Statement, StatementKind, Terminator, TerminatorKind, VarDebugInfo,
13 use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation};
14 use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
16 #[derive(Copy, Clone, Debug)]
22 pub struct Validator {
23 /// Describes at which point in the pipeline this validation is happening.
25 /// The phase for which we are upholding the dialect. If the given phase forbids a specific
26 /// element, this validator will now emit errors if that specific element is encountered.
27 /// Note that phases that change the dialect cause all *following* phases to check the
28 /// invariants of the new dialect. A phase that changes dialects never checks the new invariants
30 pub mir_phase: MirPhase,
33 impl<'tcx> MirPass<'tcx> for Validator {
34 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
35 let def_id = body.source.def_id();
36 let param_env = tcx.param_env(def_id);
37 let mir_phase = self.mir_phase;
39 let always_live_locals = AlwaysLiveLocals::new(body);
40 let storage_liveness = MaybeStorageLive::new(always_live_locals)
41 .into_engine(tcx, body)
42 .iterate_to_fixpoint()
43 .into_results_cursor(body);
45 TypeChecker { when: &self.when, body, tcx, param_env, mir_phase, storage_liveness }
50 /// Returns whether the two types are equal up to lifetimes.
51 /// All lifetimes, including higher-ranked ones, get ignored for this comparison.
52 /// (This is unlike the `erasing_regions` methods, which keep higher-ranked lifetimes for soundness reasons.)
54 /// The point of this function is to approximate "equal up to subtyping". However,
55 /// the approximation is incorrect as variance is ignored.
56 pub fn equal_up_to_regions(
58 param_env: ParamEnv<'tcx>,
67 struct LifetimeIgnoreRelation<'tcx> {
69 param_env: ty::ParamEnv<'tcx>,
72 impl TypeRelation<'tcx> for LifetimeIgnoreRelation<'tcx> {
73 fn tcx(&self) -> TyCtxt<'tcx> {
77 fn param_env(&self) -> ty::ParamEnv<'tcx> {
81 fn tag(&self) -> &'static str {
82 "librustc_mir::transform::validate"
85 fn a_is_expected(&self) -> bool {
89 fn relate_with_variance<T: Relate<'tcx>>(
94 ) -> RelateResult<'tcx, T> {
95 // Ignore variance, require types to be exactly the same.
99 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
104 ty::relate::super_relate_tys(self, a, b)
110 _b: ty::Region<'tcx>,
111 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
118 a: &'tcx ty::Const<'tcx>,
119 b: &'tcx ty::Const<'tcx>,
120 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
121 ty::relate::super_relate_consts(self, a, b)
128 ) -> RelateResult<'tcx, ty::Binder<T>>
132 self.relate(a.skip_binder(), b.skip_binder())?;
137 // Instantiate and run relation.
138 let mut relator: LifetimeIgnoreRelation<'tcx> = LifetimeIgnoreRelation { tcx: tcx, param_env };
139 relator.relate(src, dest).is_ok()
142 struct TypeChecker<'a, 'tcx> {
144 body: &'a Body<'tcx>,
146 param_env: ParamEnv<'tcx>,
148 storage_liveness: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
151 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
152 fn fail(&self, location: Location, msg: impl AsRef<str>) {
153 let span = self.body.source_info(location).span;
154 // We use `delay_span_bug` as we might see broken MIR when other errors have already
156 self.tcx.sess.diagnostic().delay_span_bug(
159 "broken MIR in {:?} ({}) at {:?}:\n{}",
160 self.body.source.instance,
168 fn check_edge(&self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) {
169 if let Some(bb) = self.body.basic_blocks().get(bb) {
170 let src = self.body.basic_blocks().get(location.block).unwrap();
171 match (src.is_cleanup, bb.is_cleanup, edge_kind) {
172 // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges
173 (false, false, EdgeKind::Normal)
174 // Non-cleanup blocks can jump to cleanup blocks along unwind edges
175 | (false, true, EdgeKind::Unwind)
176 // Cleanup blocks can jump to cleanup blocks along non-unwind edges
177 | (true, true, EdgeKind::Normal) => {}
178 // All other jumps are invalid
183 "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})",
193 self.fail(location, format!("encountered jump to invalid basic block {:?}", bb))
197 /// Check if src can be assigned into dest.
198 /// This is not precise, it will accept some incorrect assignments.
199 fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
200 // Fast path before we normalize.
202 // Equal types, all is good.
205 // Normalize projections and things like that.
206 // FIXME: We need to reveal_all, as some optimizations change types in ways
207 // that require unfolding opaque types.
208 let param_env = self.param_env.with_reveal_all_normalized(self.tcx);
209 let src = self.tcx.normalize_erasing_regions(param_env, src);
210 let dest = self.tcx.normalize_erasing_regions(param_env, dest);
212 // Type-changing assignments can happen when subtyping is used. While
213 // all normal lifetimes are erased, higher-ranked types with their
214 // late-bound lifetimes are still around and can lead to type
215 // differences. So we compare ignoring lifetimes.
216 equal_up_to_regions(self.tcx, param_env, src, dest)
220 impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
221 fn visit_local(&mut self, local: &Local, context: PlaceContext, location: Location) {
222 if context.is_use() {
223 // Uses of locals must occur while the local's storage is allocated.
224 self.storage_liveness.seek_after_primary_effect(location);
225 let locals_with_storage = self.storage_liveness.get();
226 if !locals_with_storage.contains(*local) {
227 self.fail(location, format!("use of local {:?}, which has no storage here", local));
232 fn visit_var_debug_info(&mut self, _var_debug_info: &VarDebugInfo<'tcx>) {
233 // Debuginfo can contain field projections, which count as a use of the base local. Skip
234 // debuginfo so that we avoid the storage liveness assertion in that case.
237 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
238 // `Operand::Copy` is only supposed to be used with `Copy` types.
239 if let Operand::Copy(place) = operand {
240 let ty = place.ty(&self.body.local_decls, self.tcx).ty;
241 let span = self.body.source_info(location).span;
243 if !ty.is_copy_modulo_regions(self.tcx.at(span), self.param_env) {
244 self.fail(location, format!("`Operand::Copy` with non-`Copy` type {}", ty));
248 self.super_operand(operand, location);
251 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
252 match &statement.kind {
253 StatementKind::Assign(box (dest, rvalue)) => {
254 // LHS and RHS of the assignment must have the same type.
255 let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
256 let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
257 if !self.mir_assign_valid_types(right_ty, left_ty) {
261 "encountered `{:?}` with incompatible types:\n\
262 left-hand side has type: {}\n\
263 right-hand side has type: {}",
264 statement.kind, left_ty, right_ty,
269 // The sides of an assignment must not alias. Currently this just checks whether the places
271 Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) => {
275 "encountered `Assign` statement with overlapping memory",
279 // The deaggregator currently does not deaggreagate arrays.
280 // So for now, we ignore them here.
281 Rvalue::Aggregate(box AggregateKind::Array { .. }, _) => {}
282 // All other aggregates must be gone after some phases.
283 Rvalue::Aggregate(box kind, _) => {
284 if self.mir_phase > MirPhase::DropLowering
285 && !matches!(kind, AggregateKind::Generator(..))
287 // Generators persist until the state machine transformation, but all
288 // other aggregates must have been lowered.
291 format!("{:?} have been lowered to field assignments", rvalue),
293 } else if self.mir_phase > MirPhase::GeneratorLowering {
294 // No more aggregates after drop and generator lowering.
297 format!("{:?} have been lowered to field assignments", rvalue),
301 Rvalue::Ref(_, BorrowKind::Shallow, _) => {
302 if self.mir_phase > MirPhase::DropLowering {
305 "`Assign` statement with a `Shallow` borrow should have been removed after drop lowering phase",
312 StatementKind::AscribeUserType(..) => {
313 if self.mir_phase > MirPhase::DropLowering {
316 "`AscribeUserType` should have been removed after drop lowering phase",
320 StatementKind::FakeRead(..) => {
321 if self.mir_phase > MirPhase::DropLowering {
324 "`FakeRead` should have been removed after drop lowering phase",
332 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
333 match &terminator.kind {
334 TerminatorKind::Goto { target } => {
335 self.check_edge(location, *target, EdgeKind::Normal);
337 TerminatorKind::SwitchInt { targets, values, switch_ty, discr } => {
338 let ty = discr.ty(&self.body.local_decls, self.tcx);
339 if ty != *switch_ty {
343 "encountered `SwitchInt` terminator with type mismatch: {:?} != {:?}",
348 if targets.len() != values.len() + 1 {
352 "encountered `SwitchInt` terminator with {} values, but {} targets (should be values+1)",
358 for target in targets {
359 self.check_edge(location, *target, EdgeKind::Normal);
362 TerminatorKind::Drop { target, unwind, .. } => {
363 self.check_edge(location, *target, EdgeKind::Normal);
364 if let Some(unwind) = unwind {
365 self.check_edge(location, *unwind, EdgeKind::Unwind);
368 TerminatorKind::DropAndReplace { target, unwind, .. } => {
369 if self.mir_phase > MirPhase::DropLowering {
372 "`DropAndReplace` is not permitted to exist after drop elaboration",
375 self.check_edge(location, *target, EdgeKind::Normal);
376 if let Some(unwind) = unwind {
377 self.check_edge(location, *unwind, EdgeKind::Unwind);
380 TerminatorKind::Call { func, destination, cleanup, .. } => {
381 let func_ty = func.ty(&self.body.local_decls, self.tcx);
382 match func_ty.kind() {
383 ty::FnPtr(..) | ty::FnDef(..) => {}
386 format!("encountered non-callable type {} in `Call` terminator", func_ty),
389 if let Some((_, target)) = destination {
390 self.check_edge(location, *target, EdgeKind::Normal);
392 if let Some(cleanup) = cleanup {
393 self.check_edge(location, *cleanup, EdgeKind::Unwind);
396 TerminatorKind::Assert { cond, target, cleanup, .. } => {
397 let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
398 if cond_ty != self.tcx.types.bool {
402 "encountered non-boolean condition of type {} in `Assert` terminator",
407 self.check_edge(location, *target, EdgeKind::Normal);
408 if let Some(cleanup) = cleanup {
409 self.check_edge(location, *cleanup, EdgeKind::Unwind);
412 TerminatorKind::Yield { resume, drop, .. } => {
413 if self.mir_phase > MirPhase::GeneratorLowering {
414 self.fail(location, "`Yield` should have been replaced by generator lowering");
416 self.check_edge(location, *resume, EdgeKind::Normal);
417 if let Some(drop) = drop {
418 self.check_edge(location, *drop, EdgeKind::Normal);
421 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
422 self.check_edge(location, *real_target, EdgeKind::Normal);
423 self.check_edge(location, *imaginary_target, EdgeKind::Normal);
425 TerminatorKind::FalseUnwind { real_target, unwind } => {
426 self.check_edge(location, *real_target, EdgeKind::Normal);
427 if let Some(unwind) = unwind {
428 self.check_edge(location, *unwind, EdgeKind::Unwind);
431 TerminatorKind::InlineAsm { destination, .. } => {
432 if let Some(destination) = destination {
433 self.check_edge(location, *destination, EdgeKind::Normal);
436 // Nothing to validate for these.
437 TerminatorKind::Resume
438 | TerminatorKind::Abort
439 | TerminatorKind::Return
440 | TerminatorKind::Unreachable
441 | TerminatorKind::GeneratorDrop => {}