1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
3 use rustc_errors::struct_span_err;
4 use rustc_hir::lang_items;
5 use rustc_hir::{def_id::DefId, HirId};
6 use rustc_infer::infer::TyCtxtInferExt;
7 use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
8 use rustc_middle::mir::*;
9 use rustc_middle::ty::cast::CastTy;
10 use rustc_middle::ty::{self, Instance, InstanceDef, TyCtxt};
11 use rustc_span::symbol::sym;
13 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
14 use rustc_trait_selection::traits::{self, TraitEngine};
19 use super::ops::{self, NonConstOp};
20 use super::qualifs::{self, HasMutInterior, NeedsDrop};
21 use super::resolver::FlowSensitiveAnalysis;
22 use super::{is_lang_panic_fn, ConstCx, ConstKind, Qualif};
23 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
24 use crate::dataflow::MaybeMutBorrowedLocals;
25 use crate::dataflow::{self, Analysis};
27 // We are using `MaybeMutBorrowedLocals` as a proxy for whether an item may have been mutated
28 // through a pointer prior to the given point. This is okay even though `MaybeMutBorrowedLocals`
29 // kills locals upon `StorageDead` because a local will never be used after a `StorageDead`.
30 type IndirectlyMutableResults<'mir, 'tcx> =
31 dataflow::ResultsCursor<'mir, 'tcx, MaybeMutBorrowedLocals<'mir, 'tcx>>;
33 type QualifResults<'mir, 'tcx, Q> =
34 dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'mir, 'tcx, Q>>;
37 pub struct Qualifs<'mir, 'tcx> {
38 has_mut_interior: Option<QualifResults<'mir, 'tcx, HasMutInterior>>,
39 needs_drop: Option<QualifResults<'mir, 'tcx, NeedsDrop>>,
40 indirectly_mutable: Option<IndirectlyMutableResults<'mir, 'tcx>>,
43 impl Qualifs<'mir, 'tcx> {
44 fn indirectly_mutable(
46 ccx: &'mir ConstCx<'mir, 'tcx>,
50 let indirectly_mutable = self.indirectly_mutable.get_or_insert_with(|| {
51 let ConstCx { tcx, body, def_id, param_env, .. } = *ccx;
53 // We can use `unsound_ignore_borrow_on_drop` here because custom drop impls are not
54 // allowed in a const.
56 // FIXME(ecstaticmorse): Someday we want to allow custom drop impls. How do we do this
57 // without breaking stable code?
58 MaybeMutBorrowedLocals::mut_borrows_only(tcx, &body, param_env)
59 .unsound_ignore_borrow_on_drop()
60 .into_engine(tcx, &body, def_id)
61 .iterate_to_fixpoint()
62 .into_results_cursor(&body)
65 indirectly_mutable.seek_before(location);
66 indirectly_mutable.get().contains(local)
69 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
71 /// Only updates the cursor if absolutely necessary
74 ccx: &'mir ConstCx<'mir, 'tcx>,
78 let ty = ccx.body.local_decls[local].ty;
79 if !NeedsDrop::in_any_value_of_ty(ccx, ty) {
83 let needs_drop = self.needs_drop.get_or_insert_with(|| {
84 let ConstCx { tcx, body, def_id, .. } = *ccx;
86 FlowSensitiveAnalysis::new(NeedsDrop, ccx)
87 .into_engine(tcx, &body, def_id)
88 .iterate_to_fixpoint()
89 .into_results_cursor(&body)
92 needs_drop.seek_before(location);
93 needs_drop.get().contains(local) || self.indirectly_mutable(ccx, local, location)
96 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
98 /// Only updates the cursor if absolutely necessary.
101 ccx: &'mir ConstCx<'mir, 'tcx>,
105 let ty = ccx.body.local_decls[local].ty;
106 if !HasMutInterior::in_any_value_of_ty(ccx, ty) {
110 let has_mut_interior = self.has_mut_interior.get_or_insert_with(|| {
111 let ConstCx { tcx, body, def_id, .. } = *ccx;
113 FlowSensitiveAnalysis::new(HasMutInterior, ccx)
114 .into_engine(tcx, &body, def_id)
115 .iterate_to_fixpoint()
116 .into_results_cursor(&body)
119 has_mut_interior.seek_before(location);
120 has_mut_interior.get().contains(local) || self.indirectly_mutable(ccx, local, location)
123 fn in_return_place(&mut self, ccx: &'mir ConstCx<'mir, 'tcx>) -> ConstQualifs {
124 // Find the `Return` terminator if one exists.
126 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
127 // qualifs for the return type.
128 let return_block = ccx
132 .find(|(_, block)| match block.terminator().kind {
133 TerminatorKind::Return => true,
138 let return_block = match return_block {
139 None => return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty()),
143 let return_loc = ccx.body.terminator_loc(return_block);
146 needs_drop: self.needs_drop(ccx, RETURN_PLACE, return_loc),
147 has_mut_interior: self.has_mut_interior(ccx, RETURN_PLACE, return_loc),
152 pub struct Validator<'mir, 'tcx> {
153 ccx: &'mir ConstCx<'mir, 'tcx>,
154 qualifs: Qualifs<'mir, 'tcx>,
156 /// The span of the current statement.
160 impl Deref for Validator<'mir, 'tcx> {
161 type Target = ConstCx<'mir, 'tcx>;
163 fn deref(&self) -> &Self::Target {
168 impl Validator<'mir, 'tcx> {
169 pub fn new(ccx: &'mir ConstCx<'mir, 'tcx>) -> Self {
170 Validator { span: ccx.body.span, ccx, qualifs: Default::default() }
173 pub fn check_body(&mut self) {
174 let ConstCx { tcx, body, def_id, const_kind, .. } = *self.ccx;
176 let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
177 && crate::const_eval::is_min_const_fn(tcx, def_id))
178 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
180 if use_min_const_fn_checks {
181 // Enforce `min_const_fn` for stable `const fn`s.
182 use crate::transform::qualify_min_const_fn::is_min_const_fn;
183 if let Err((span, err)) = is_min_const_fn(tcx, def_id, &body) {
184 error_min_const_fn_violation(tcx, span, err);
189 check_short_circuiting_in_const_local(self.ccx);
191 if body.is_cfg_cyclic() {
192 // We can't provide a good span for the error here, but this should be caught by the
193 // HIR const-checker anyways.
194 self.check_op_spanned(ops::Loop, body.span);
197 self.visit_body(&body);
199 // Ensure that the end result is `Sync` in a non-thread local `static`.
200 let should_check_for_sync =
201 const_kind == Some(ConstKind::Static) && !tcx.has_attr(def_id, sym::thread_local);
203 if should_check_for_sync {
204 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
205 check_return_ty_is_sync(tcx, &body, hir_id);
209 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
210 self.qualifs.in_return_place(self.ccx)
213 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
215 pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
219 debug!("check_op: op={:?}", op);
221 if op.is_allowed_in_item(self) {
225 // If an operation is supported in miri (and is not already controlled by a feature gate) it
226 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
227 let is_unleashable = O::IS_SUPPORTED_IN_MIRI && O::feature_gate().is_none();
229 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
230 self.tcx.sess.span_warn(span, "skipping const checks");
234 op.emit_error(self, span);
237 /// Emits an error if an expression cannot be evaluated in the current context.
238 pub fn check_op(&mut self, op: impl NonConstOp) {
239 let span = self.span;
240 self.check_op_spanned(op, span)
243 fn check_static(&mut self, def_id: DefId, span: Span) {
244 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
246 self.check_op_spanned(ops::ThreadLocalAccess, span)
248 self.check_op_spanned(ops::StaticAccess, span)
253 impl Visitor<'tcx> for Validator<'mir, 'tcx> {
254 fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
255 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
257 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
258 // These blocks often drop locals that would otherwise be returned from the function.
260 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
261 // error anyway, but maybe we should do more here?
262 if block.is_cleanup {
266 self.super_basic_block_data(bb, block);
269 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
270 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
272 // Special-case reborrows to be more like a copy of a reference.
274 Rvalue::Ref(_, kind, place) => {
275 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
276 let ctx = match kind {
277 BorrowKind::Shared => {
278 PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
280 BorrowKind::Shallow => {
281 PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
283 BorrowKind::Unique => {
284 PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
286 BorrowKind::Mut { .. } => {
287 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
290 self.visit_local(&place.local, ctx, location);
291 self.visit_projection(place.local, reborrowed_proj, ctx, location);
295 Rvalue::AddressOf(mutbl, place) => {
296 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
297 let ctx = match mutbl {
299 PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf)
301 Mutability::Mut => PlaceContext::MutatingUse(MutatingUseContext::AddressOf),
303 self.visit_local(&place.local, ctx, location);
304 self.visit_projection(place.local, reborrowed_proj, ctx, location);
311 self.super_rvalue(rvalue, location);
316 | Rvalue::UnaryOp(UnOp::Neg, _)
317 | Rvalue::UnaryOp(UnOp::Not, _)
318 | Rvalue::NullaryOp(NullOp::SizeOf, _)
319 | Rvalue::CheckedBinaryOp(..)
320 | Rvalue::Cast(CastKind::Pointer(_), ..)
321 | Rvalue::Discriminant(..)
323 | Rvalue::Aggregate(..) => {}
325 Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
326 | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place) => {
327 let ty = place.ty(self.body, self.tcx).ty;
328 let is_allowed = match ty.kind {
329 // Inside a `static mut`, `&mut [...]` is allowed.
330 ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut => {
334 // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
335 // that this is merely a ZST and it is already eligible for promotion.
336 // This may require an RFC?
338 ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
345 if let BorrowKind::Mut { .. } = kind {
346 self.check_op(ops::MutBorrow);
348 self.check_op(ops::CellBorrow);
353 Rvalue::AddressOf(Mutability::Mut, _) => self.check_op(ops::MutAddressOf),
355 Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Shallow, ref place)
356 | Rvalue::AddressOf(Mutability::Not, ref place) => {
357 let borrowed_place_has_mut_interior = qualifs::in_place::<HasMutInterior, _>(
359 &mut |local| self.qualifs.has_mut_interior(self.ccx, local, location),
363 if borrowed_place_has_mut_interior {
364 self.check_op(ops::CellBorrow);
368 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
369 let operand_ty = operand.ty(self.body, self.tcx);
370 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
371 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
373 if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
374 self.check_op(ops::RawPtrToIntCast);
378 Rvalue::BinaryOp(op, ref lhs, _) => {
379 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
387 || op == BinOp::Offset
390 self.check_op(ops::RawPtrComparison);
394 Rvalue::NullaryOp(NullOp::Box, _) => {
395 self.check_op(ops::HeapAllocation);
400 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
401 self.super_operand(op, location);
402 if let Operand::Constant(c) = op {
403 if let Some(def_id) = c.check_static_ptr(self.tcx) {
404 self.check_static(def_id, self.span);
408 fn visit_projection_elem(
411 proj_base: &[PlaceElem<'tcx>],
412 elem: &PlaceElem<'tcx>,
413 context: PlaceContext,
417 "visit_projection_elem: place_local={:?} proj_base={:?} elem={:?} \
418 context={:?} location={:?}",
426 self.super_projection_elem(place_local, proj_base, elem, context, location);
429 ProjectionElem::Deref => {
430 let base_ty = Place::ty_from(place_local, proj_base, self.body, self.tcx).ty;
431 if let ty::RawPtr(_) = base_ty.kind {
432 if proj_base.is_empty() {
433 if let (local, []) = (place_local, proj_base) {
434 let decl = &self.body.local_decls[local];
435 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
436 let span = decl.source_info.span;
437 self.check_static(def_id, span);
442 self.check_op(ops::RawPtrDeref);
445 if context.is_mutating_use() {
446 self.check_op(ops::MutDeref);
450 ProjectionElem::ConstantIndex { .. }
451 | ProjectionElem::Subslice { .. }
452 | ProjectionElem::Field(..)
453 | ProjectionElem::Index(_) => {
454 let base_ty = Place::ty_from(place_local, proj_base, self.body, self.tcx).ty;
455 match base_ty.ty_adt_def() {
456 Some(def) if def.is_union() => {
457 self.check_op(ops::UnionAccess);
464 ProjectionElem::Downcast(..) => {
465 self.check_op(ops::Downcast);
470 fn visit_source_info(&mut self, source_info: &SourceInfo) {
471 trace!("visit_source_info: source_info={:?}", source_info);
472 self.span = source_info.span;
475 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
476 trace!("visit_statement: statement={:?} location={:?}", statement, location);
478 match statement.kind {
479 StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
480 self.super_statement(statement, location);
483 StatementKind::FakeRead(
484 FakeReadCause::ForMatchedPlace
485 | FakeReadCause::ForMatchGuard
486 | FakeReadCause::ForGuardBinding,
489 self.super_statement(statement, location);
490 self.check_op(ops::IfOrMatch);
492 StatementKind::LlvmInlineAsm { .. } => {
493 self.super_statement(statement, location);
494 self.check_op(ops::InlineAsm);
497 StatementKind::FakeRead(FakeReadCause::ForLet | FakeReadCause::ForIndex, _)
498 | StatementKind::StorageLive(_)
499 | StatementKind::StorageDead(_)
500 | StatementKind::Retag { .. }
501 | StatementKind::AscribeUserType(..)
502 | StatementKind::Nop => {}
506 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
507 trace!("visit_terminator: terminator={:?} location={:?}", terminator, location);
508 self.super_terminator(terminator, location);
510 match &terminator.kind {
511 TerminatorKind::Call { func, .. } => {
512 let fn_ty = func.ty(self.body, self.tcx);
514 let (def_id, substs) = match fn_ty.kind {
515 ty::FnDef(def_id, substs) => (def_id, substs),
518 self.check_op(ops::FnCallIndirect);
522 span_bug!(terminator.source_info.span, "invalid callee of type {:?}", fn_ty)
526 // At this point, we are calling a function whose `DefId` is known...
527 if is_const_fn(self.tcx, def_id) {
531 // See if this is a trait method for a concrete type whose impl of that trait is
533 if self.tcx.features().const_trait_impl {
534 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs);
535 debug!("Resolving ({:?}) -> {:?}", def_id, instance);
536 if let Ok(Some(func)) = instance {
537 if let InstanceDef::Item(def_id) = func.def {
538 if is_const_fn(self.tcx, def_id) {
545 if is_lang_panic_fn(self.tcx, def_id) {
546 self.check_op(ops::Panic);
547 } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) {
548 // Exempt unstable const fns inside of macros with
549 // `#[allow_internal_unstable]`.
550 if !self.span.allows_unstable(feature) {
551 self.check_op(ops::FnCallUnstable(def_id, feature));
554 self.check_op(ops::FnCallNonConst(def_id));
558 // Forbid all `Drop` terminators unless the place being dropped is a local with no
559 // projections that cannot be `NeedsDrop`.
560 TerminatorKind::Drop { location: dropped_place, .. }
561 | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
562 let mut err_span = self.span;
564 // Check to see if the type of this place can ever have a drop impl. If not, this
565 // `Drop` terminator is frivolous.
567 dropped_place.ty(self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
573 let needs_drop = if let Some(local) = dropped_place.as_local() {
574 // Use the span where the local was declared as the span of the drop error.
575 err_span = self.body.local_decls[local].source_info.span;
576 self.qualifs.needs_drop(self.ccx, local, location)
582 self.check_op_spanned(ops::LiveDrop, err_span);
586 // FIXME: Some of these are only caught by `min_const_fn`, but should error here
588 TerminatorKind::Abort
589 | TerminatorKind::Assert { .. }
590 | TerminatorKind::FalseEdges { .. }
591 | TerminatorKind::FalseUnwind { .. }
592 | TerminatorKind::GeneratorDrop
593 | TerminatorKind::Goto { .. }
594 | TerminatorKind::Resume
595 | TerminatorKind::Return
596 | TerminatorKind::SwitchInt { .. }
597 | TerminatorKind::Unreachable
598 | TerminatorKind::Yield { .. } => {}
603 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
604 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
606 "see issue #57563 <https://github.com/rust-lang/rust/issues/57563> \
607 for more information",
609 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
613 fn check_short_circuiting_in_const_local(ccx: &ConstCx<'_, 'tcx>) {
616 if body.control_flow_destroyed.is_empty() {
620 let mut locals = body.vars_iter();
621 if let Some(local) = locals.next() {
622 let span = body.local_decls[local].source_info.span;
623 let mut error = ccx.tcx.sess.struct_span_err(
626 "new features like let bindings are not permitted in {}s \
627 which also use short circuiting operators",
631 for (span, kind) in body.control_flow_destroyed.iter() {
635 "use of {} here does not actually short circuit due to \
636 the const evaluator presently not being able to do control flow. \
637 See issue #49146 <https://github.com/rust-lang/rust/issues/49146> \
638 for more information.",
643 for local in locals {
644 let span = body.local_decls[local].source_info.span;
645 error.span_note(span, "more locals are defined here");
651 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
652 let ty = body.return_ty();
653 tcx.infer_ctxt().enter(|infcx| {
654 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
655 let mut fulfillment_cx = traits::FulfillmentContext::new();
656 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
657 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
658 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
659 infcx.report_fulfillment_errors(&err, None, false);
664 fn place_as_reborrow(
668 ) -> Option<&'a [PlaceElem<'tcx>]> {
669 place.projection.split_last().and_then(|(outermost, inner)| {
670 if outermost != &ProjectionElem::Deref {
674 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
675 // that points to the allocation for the static. Don't treat these as reborrows.
676 if body.local_decls[place.local].is_ref_to_static() {
680 // Ensure the type being derefed is a reference and not a raw pointer.
682 // This is sufficient to prevent an access to a `static mut` from being marked as a
683 // reborrow, even if the check above were to disappear.
684 let inner_ty = Place::ty_from(place.local, inner, body, tcx).ty;
685 match inner_ty.kind {
686 ty::Ref(..) => Some(inner),