1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
3 use rustc::hir::{def_id::DefId, HirId};
4 use rustc::middle::lang_items;
5 use rustc::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
7 use rustc::traits::{self, TraitEngine};
8 use rustc::ty::cast::CastTy;
9 use rustc::ty::{self, TyCtxt};
10 use rustc_error_codes::*;
11 use rustc_index::bit_set::BitSet;
12 use rustc_span::symbol::sym;
18 use self::old_dataflow::IndirectlyMutableLocals;
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, ConstKind, Item, Qualif};
23 use crate::dataflow::{self as old_dataflow, generic as dataflow};
25 pub type IndirectlyMutableResults<'mir, 'tcx> =
26 old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
28 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
29 cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
30 in_any_value_of_ty: BitSet<Local>,
33 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
34 pub fn new(q: Q, item: &'a Item<'mir, 'tcx>, dead_unwinds: &BitSet<BasicBlock>) -> Self {
35 let analysis = FlowSensitiveAnalysis::new(q, item);
37 dataflow::Engine::new(item.tcx, &item.body, item.def_id, dead_unwinds, analysis)
38 .iterate_to_fixpoint();
39 let cursor = dataflow::ResultsCursor::new(*item.body, results);
41 let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
42 for (local, decl) in item.body.local_decls.iter_enumerated() {
43 if Q::in_any_value_of_ty(item, decl.ty) {
44 in_any_value_of_ty.insert(local);
48 QualifCursor { cursor, in_any_value_of_ty }
52 pub struct Qualifs<'a, 'mir, 'tcx> {
53 has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
54 needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
55 indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
58 impl Qualifs<'a, 'mir, 'tcx> {
59 fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
60 self.indirectly_mutable.seek(location);
61 self.indirectly_mutable.get().contains(local)
64 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
66 /// Only updates the cursor if absolutely necessary
67 fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
68 if !self.needs_drop.in_any_value_of_ty.contains(local) {
72 self.needs_drop.cursor.seek_before(location);
73 self.needs_drop.cursor.get().contains(local) || self.indirectly_mutable(local, location)
76 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
78 /// Only updates the cursor if absolutely necessary.
79 fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
80 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
84 self.has_mut_interior.cursor.seek_before(location);
85 self.has_mut_interior.cursor.get().contains(local)
86 || self.indirectly_mutable(local, location)
89 /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
90 /// `indirectly_mutable` cursors to be updated beforehand.
91 fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
92 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
96 self.has_mut_interior.cursor.get().contains(local)
97 || self.indirectly_mutable.get().contains(local)
100 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
101 // Find the `Return` terminator if one exists.
103 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
104 // qualifs for the return type.
105 let return_block = item
109 .find(|(_, block)| match block.terminator().kind {
110 TerminatorKind::Return => true,
115 let return_block = match return_block {
116 None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
120 let return_loc = item.body.terminator_loc(return_block);
123 needs_drop: self.needs_drop_lazy_seek(RETURN_PLACE, return_loc),
124 has_mut_interior: self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc),
129 pub struct Validator<'a, 'mir, 'tcx> {
130 item: &'a Item<'mir, 'tcx>,
131 qualifs: Qualifs<'a, 'mir, 'tcx>,
133 /// The span of the current statement.
137 impl Deref for Validator<'_, 'mir, 'tcx> {
138 type Target = Item<'mir, 'tcx>;
140 fn deref(&self) -> &Self::Target {
145 impl Validator<'a, 'mir, 'tcx> {
146 pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
147 let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
149 let needs_drop = QualifCursor::new(NeedsDrop, item, &dead_unwinds);
151 let has_mut_interior = QualifCursor::new(HasMutInterior, item, &dead_unwinds);
153 let indirectly_mutable = old_dataflow::do_dataflow(
157 &item.tcx.get_attrs(item.def_id),
159 old_dataflow::IndirectlyMutableLocals::new(item.tcx, *item.body, item.param_env),
160 |_, local| old_dataflow::DebugFormatted::new(&local),
163 let indirectly_mutable =
164 old_dataflow::DataflowResultsCursor::new(indirectly_mutable, *item.body);
166 let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable };
168 Validator { span: item.body.span, item, qualifs }
171 pub fn check_body(&mut self) {
172 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
174 let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
175 && tcx.is_min_const_fn(def_id))
176 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
178 if use_min_const_fn_checks {
179 // Enforce `min_const_fn` for stable `const fn`s.
180 use crate::transform::qualify_min_const_fn::is_min_const_fn;
181 if let Err((span, err)) = is_min_const_fn(tcx, def_id, &body) {
182 error_min_const_fn_violation(tcx, span, err);
187 check_short_circuiting_in_const_local(self.item);
189 if body.is_cfg_cyclic() {
190 // We can't provide a good span for the error here, but this should be caught by the
191 // HIR const-checker anyways.
192 self.check_op_spanned(ops::Loop, body.span);
195 self.visit_body(body);
197 // Ensure that the end result is `Sync` in a non-thread local `static`.
198 let should_check_for_sync =
199 const_kind == Some(ConstKind::Static) && !tcx.has_attr(def_id, sym::thread_local);
201 if should_check_for_sync {
202 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
203 check_return_ty_is_sync(tcx, &body, hir_id);
207 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
208 self.qualifs.in_return_place(self.item)
211 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
213 pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
217 trace!("check_op: op={:?}", op);
219 if op.is_allowed_in_item(self) {
223 // If an operation is supported in miri (and is not already controlled by a feature gate) it
224 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
225 let is_unleashable = O::IS_SUPPORTED_IN_MIRI && O::feature_gate(self.tcx).is_none();
227 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
228 self.tcx.sess.span_warn(span, "skipping const checks");
232 op.emit_error(self, span);
235 /// Emits an error if an expression cannot be evaluated in the current context.
236 pub fn check_op(&mut self, op: impl NonConstOp) {
237 let span = self.span;
238 self.check_op_spanned(op, span)
241 fn check_static(&mut self, def_id: DefId, span: Span) {
242 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
244 self.check_op_spanned(ops::ThreadLocalAccess, span)
246 self.check_op_spanned(ops::StaticAccess, span)
250 fn check_immutable_borrow_like(&mut self, location: Location, place: &Place<'tcx>) {
251 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
252 // seek the cursors beforehand.
253 self.qualifs.has_mut_interior.cursor.seek_before(location);
254 self.qualifs.indirectly_mutable.seek(location);
256 let borrowed_place_has_mut_interior = HasMutInterior::in_place(
258 &|local| self.qualifs.has_mut_interior_eager_seek(local),
262 if borrowed_place_has_mut_interior {
263 self.check_op(ops::CellBorrow);
268 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
269 fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
270 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
272 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
273 // These blocks often drop locals that would otherwise be returned from the function.
275 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
276 // error anyway, but maybe we should do more here?
277 if block.is_cleanup {
281 self.super_basic_block_data(bb, block);
284 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
285 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
287 // Special-case reborrows to be more like a copy of a reference.
289 Rvalue::Ref(_, kind, ref place) => {
290 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
291 let ctx = match kind {
292 BorrowKind::Shared => {
293 PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
295 BorrowKind::Shallow => {
296 PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
298 BorrowKind::Unique => {
299 PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
301 BorrowKind::Mut { .. } => {
302 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
305 self.visit_place_base(&place.base, ctx, location);
306 self.visit_projection(&place.base, reborrowed_proj, ctx, location);
310 Rvalue::AddressOf(mutbl, ref place) => {
311 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
312 let ctx = match mutbl {
314 PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf)
316 Mutability::Mut => PlaceContext::MutatingUse(MutatingUseContext::AddressOf),
318 self.visit_place_base(&place.base, ctx, location);
319 self.visit_projection(&place.base, reborrowed_proj, ctx, location);
326 self.super_rvalue(rvalue, location);
331 | Rvalue::UnaryOp(UnOp::Neg, _)
332 | Rvalue::UnaryOp(UnOp::Not, _)
333 | Rvalue::NullaryOp(NullOp::SizeOf, _)
334 | Rvalue::CheckedBinaryOp(..)
335 | Rvalue::Cast(CastKind::Pointer(_), ..)
336 | Rvalue::Discriminant(..)
338 | Rvalue::Aggregate(..) => {}
340 Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
341 | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place) => {
342 let ty = place.ty(*self.body, self.tcx).ty;
343 let is_allowed = match ty.kind {
344 // Inside a `static mut`, `&mut [...]` is allowed.
345 ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut => {
349 // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
350 // that this is merely a ZST and it is already eligible for promotion.
351 // This may require an RFC?
353 ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
360 if let BorrowKind::Mut { .. } = kind {
361 self.check_op(ops::MutBorrow);
363 self.check_op(ops::CellBorrow);
368 Rvalue::AddressOf(Mutability::Mut, _) => self.check_op(ops::MutAddressOf),
370 // At the moment, `PlaceBase::Static` is only used for promoted MIR.
371 Rvalue::Ref(_, BorrowKind::Shared, ref place)
372 | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
373 | Rvalue::AddressOf(Mutability::Not, ref place)
374 if matches!(place.base, PlaceBase::Static(_)) =>
376 bug!("Saw a promoted during const-checking, which must run before promotion")
379 Rvalue::Ref(_, BorrowKind::Shared, ref place)
380 | Rvalue::Ref(_, BorrowKind::Shallow, ref place) => {
381 self.check_immutable_borrow_like(location, place)
384 Rvalue::AddressOf(Mutability::Not, ref place) => {
385 self.check_immutable_borrow_like(location, place)
388 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
389 let operand_ty = operand.ty(*self.body, self.tcx);
390 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
391 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
393 if let (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) =
396 self.check_op(ops::RawPtrToIntCast);
400 Rvalue::BinaryOp(op, ref lhs, _) => {
401 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
409 || op == BinOp::Offset
412 self.check_op(ops::RawPtrComparison);
416 Rvalue::NullaryOp(NullOp::Box, _) => {
417 self.check_op(ops::HeapAllocation);
424 place_base: &PlaceBase<'tcx>,
425 context: PlaceContext,
429 "visit_place_base: place_base={:?} context={:?} location={:?}",
434 self.super_place_base(place_base, context, location);
437 PlaceBase::Local(_) => {}
438 PlaceBase::Static(_) => {
439 bug!("Promotion must be run after const validation");
444 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
445 self.super_operand(op, location);
446 if let Operand::Constant(c) = op {
447 if let Some(def_id) = c.check_static_ptr(self.tcx) {
448 self.check_static(def_id, self.span);
452 fn visit_projection_elem(
454 place_base: &PlaceBase<'tcx>,
455 proj_base: &[PlaceElem<'tcx>],
456 elem: &PlaceElem<'tcx>,
457 context: PlaceContext,
461 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
462 context={:?} location={:?}",
470 self.super_projection_elem(place_base, proj_base, elem, context, location);
473 ProjectionElem::Deref => {
474 let base_ty = Place::ty_from(place_base, proj_base, *self.body, self.tcx).ty;
475 if let ty::RawPtr(_) = base_ty.kind {
476 if proj_base.is_empty() {
477 if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
478 let decl = &self.body.local_decls[*local];
479 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
480 let span = decl.source_info.span;
481 self.check_static(def_id, span);
486 self.check_op(ops::RawPtrDeref);
489 if context.is_mutating_use() {
490 self.check_op(ops::MutDeref);
494 ProjectionElem::ConstantIndex { .. }
495 | ProjectionElem::Subslice { .. }
496 | ProjectionElem::Field(..)
497 | ProjectionElem::Index(_) => {
498 let base_ty = Place::ty_from(place_base, proj_base, *self.body, self.tcx).ty;
499 match base_ty.ty_adt_def() {
500 Some(def) if def.is_union() => {
501 self.check_op(ops::UnionAccess);
508 ProjectionElem::Downcast(..) => {
509 self.check_op(ops::Downcast);
514 fn visit_source_info(&mut self, source_info: &SourceInfo) {
515 trace!("visit_source_info: source_info={:?}", source_info);
516 self.span = source_info.span;
519 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
520 trace!("visit_statement: statement={:?} location={:?}", statement, location);
522 match statement.kind {
523 StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
524 self.super_statement(statement, location);
526 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
527 self.check_op(ops::IfOrMatch);
529 // FIXME(eddyb) should these really do nothing?
530 StatementKind::FakeRead(..)
531 | StatementKind::StorageLive(_)
532 | StatementKind::StorageDead(_)
533 | StatementKind::InlineAsm { .. }
534 | StatementKind::Retag { .. }
535 | StatementKind::AscribeUserType(..)
536 | StatementKind::Nop => {}
540 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
541 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
542 self.super_terminator_kind(kind, location);
545 TerminatorKind::Call { func, .. } => {
546 let fn_ty = func.ty(*self.body, self.tcx);
548 let def_id = match fn_ty.kind {
549 ty::FnDef(def_id, _) => def_id,
552 self.check_op(ops::FnCallIndirect);
556 self.check_op(ops::FnCallOther);
561 // At this point, we are calling a function whose `DefId` is known...
562 if self.tcx.is_const_fn(def_id) {
566 if is_lang_panic_fn(self.tcx, def_id) {
567 self.check_op(ops::Panic);
568 } else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
569 // Exempt unstable const fns inside of macros with
570 // `#[allow_internal_unstable]`.
571 if !self.span.allows_unstable(feature) {
572 self.check_op(ops::FnCallUnstable(def_id, feature));
575 self.check_op(ops::FnCallNonConst(def_id));
579 // Forbid all `Drop` terminators unless the place being dropped is a local with no
580 // projections that cannot be `NeedsDrop`.
581 TerminatorKind::Drop { location: dropped_place, .. }
582 | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
583 let mut err_span = self.span;
585 // Check to see if the type of this place can ever have a drop impl. If not, this
586 // `Drop` terminator is frivolous.
588 dropped_place.ty(*self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
594 let needs_drop = if let Some(local) = dropped_place.as_local() {
595 // Use the span where the local was declared as the span of the drop error.
596 err_span = self.body.local_decls[local].source_info.span;
597 self.qualifs.needs_drop_lazy_seek(local, location)
603 self.check_op_spanned(ops::LiveDrop, err_span);
612 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
613 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
614 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
615 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
619 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
620 let body = item.body;
622 if body.control_flow_destroyed.is_empty() {
626 let mut locals = body.vars_iter();
627 if let Some(local) = locals.next() {
628 let span = body.local_decls[local].source_info.span;
629 let mut error = item.tcx.sess.struct_span_err(
632 "new features like let bindings are not permitted in {}s \
633 which also use short circuiting operators",
637 for (span, kind) in body.control_flow_destroyed.iter() {
641 "use of {} here does not actually short circuit due to \
642 the const evaluator presently not being able to do control flow. \
643 See https://github.com/rust-lang/rust/issues/49146 for more \
649 for local in locals {
650 let span = body.local_decls[local].source_info.span;
651 error.span_note(span, "more locals defined here");
657 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
658 let ty = body.return_ty();
659 tcx.infer_ctxt().enter(|infcx| {
660 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
661 let mut fulfillment_cx = traits::FulfillmentContext::new();
662 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
663 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
664 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
665 infcx.report_fulfillment_errors(&err, None, false);
670 fn place_as_reborrow(
673 place: &'a Place<'tcx>,
674 ) -> Option<&'a [PlaceElem<'tcx>]> {
675 place.projection.split_last().and_then(|(outermost, inner)| {
676 if outermost != &ProjectionElem::Deref {
680 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
681 // that points to the allocation for the static. Don't treat these as reborrows.
682 if let PlaceBase::Local(local) = place.base {
683 if body.local_decls[local].is_ref_to_static() {
688 // Ensure the type being derefed is a reference and not a raw pointer.
690 // This is sufficient to prevent an access to a `static mut` from being marked as a
691 // reborrow, even if the check above were to disappear.
692 let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
693 match inner_ty.kind {
694 ty::Ref(..) => Some(inner),