1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
3 use rustc::hir::{HirId, def_id::DefId};
4 use rustc::middle::lang_items;
5 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
7 use rustc::traits::{self, TraitEngine};
8 use rustc::ty::cast::CastTy;
9 use rustc::ty::{self, TyCtxt};
10 use rustc_index::bit_set::BitSet;
11 use rustc_target::spec::abi::Abi;
12 use rustc_error_codes::*;
13 use syntax::symbol::sym;
19 use crate::dataflow::{self as old_dataflow, generic as dataflow};
20 use self::old_dataflow::IndirectlyMutableLocals;
21 use super::ops::{self, NonConstOp};
22 use super::qualifs::{self, HasMutInterior, NeedsDrop};
23 use super::resolver::FlowSensitiveAnalysis;
24 use super::{ConstKind, Item, Qualif, is_lang_panic_fn};
26 pub type IndirectlyMutableResults<'mir, 'tcx> =
27 old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
29 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
30 cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
31 in_any_value_of_ty: BitSet<Local>,
34 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
37 item: &'a Item<'mir, 'tcx>,
38 dead_unwinds: &BitSet<BasicBlock>,
40 let analysis = FlowSensitiveAnalysis::new(q, item);
42 dataflow::Engine::new(item.tcx, item.body, item.def_id, dead_unwinds, analysis)
43 .iterate_to_fixpoint();
44 let cursor = dataflow::ResultsCursor::new(item.body, results);
46 let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
47 for (local, decl) in item.body.local_decls.iter_enumerated() {
48 if Q::in_any_value_of_ty(item, decl.ty) {
49 in_any_value_of_ty.insert(local);
60 pub struct Qualifs<'a, 'mir, 'tcx> {
61 has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
62 needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
63 indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
66 impl Qualifs<'a, 'mir, 'tcx> {
67 fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
68 self.indirectly_mutable.seek(location);
69 self.indirectly_mutable.get().contains(local)
72 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
74 /// Only updates the cursor if absolutely necessary
75 fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
76 if !self.needs_drop.in_any_value_of_ty.contains(local) {
80 self.needs_drop.cursor.seek_before(location);
81 self.needs_drop.cursor.get().contains(local)
82 || self.indirectly_mutable(local, location)
85 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
87 /// Only updates the cursor if absolutely necessary.
88 fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
89 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
93 self.has_mut_interior.cursor.seek_before(location);
94 self.has_mut_interior.cursor.get().contains(local)
95 || self.indirectly_mutable(local, location)
98 /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
99 /// `indirectly_mutable` cursors to be updated beforehand.
100 fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
101 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
105 self.has_mut_interior.cursor.get().contains(local)
106 || self.indirectly_mutable.get().contains(local)
109 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
110 // Find the `Return` terminator if one exists.
112 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
113 // qualifs for the return type.
114 let return_block = item.body
118 match block.terminator().kind {
119 TerminatorKind::Return => true,
125 let return_block = match return_block {
126 None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
130 let return_loc = item.body.terminator_loc(return_block);
133 needs_drop: self.needs_drop_lazy_seek(RETURN_PLACE, return_loc),
134 has_mut_interior: self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc),
139 pub struct Validator<'a, 'mir, 'tcx> {
140 item: &'a Item<'mir, 'tcx>,
141 qualifs: Qualifs<'a, 'mir, 'tcx>,
143 /// The span of the current statement.
147 impl Deref for Validator<'_, 'mir, 'tcx> {
148 type Target = Item<'mir, 'tcx>;
150 fn deref(&self) -> &Self::Target {
155 impl Validator<'a, 'mir, 'tcx> {
157 item: &'a Item<'mir, 'tcx>,
159 let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
161 let needs_drop = QualifCursor::new(
167 let has_mut_interior = QualifCursor::new(
173 let indirectly_mutable = old_dataflow::do_dataflow(
177 &item.tcx.get_attrs(item.def_id),
179 old_dataflow::IndirectlyMutableLocals::new(item.tcx, item.body, item.param_env),
180 |_, local| old_dataflow::DebugFormatted::new(&local),
183 let indirectly_mutable = old_dataflow::DataflowResultsCursor::new(
188 let qualifs = Qualifs {
195 span: item.body.span,
201 pub fn check_body(&mut self) {
202 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
204 let use_min_const_fn_checks =
205 tcx.is_min_const_fn(def_id)
206 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
208 if use_min_const_fn_checks {
209 // Enforce `min_const_fn` for stable `const fn`s.
210 use crate::transform::qualify_min_const_fn::is_min_const_fn;
211 if let Err((span, err)) = is_min_const_fn(tcx, def_id, body) {
212 error_min_const_fn_violation(tcx, span, err);
217 check_short_circuiting_in_const_local(self.item);
219 if body.is_cfg_cyclic() {
220 // We can't provide a good span for the error here, but this should be caught by the
221 // HIR const-checker anyways.
222 self.check_op_spanned(ops::Loop, body.span);
225 self.visit_body(body);
227 // Ensure that the end result is `Sync` in a non-thread local `static`.
228 let should_check_for_sync = const_kind == Some(ConstKind::Static)
229 && !tcx.has_attr(def_id, sym::thread_local);
231 if should_check_for_sync {
232 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
233 check_return_ty_is_sync(tcx, body, hir_id);
237 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
238 self.qualifs.in_return_place(self.item)
241 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
243 pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
247 trace!("check_op: op={:?}", op);
249 if op.is_allowed_in_item(self) {
253 // If an operation is supported in miri (and is not already controlled by a feature gate) it
254 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
255 let is_unleashable = O::IS_SUPPORTED_IN_MIRI
256 && O::feature_gate(self.tcx).is_none();
258 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
259 self.tcx.sess.span_warn(span, "skipping const checks");
263 op.emit_error(self, span);
266 /// Emits an error if an expression cannot be evaluated in the current context.
267 pub fn check_op(&mut self, op: impl NonConstOp) {
268 let span = self.span;
269 self.check_op_spanned(op, span)
272 fn check_static(&mut self, def_id: DefId, span: Span) {
273 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
275 self.check_op_spanned(ops::ThreadLocalAccess, span)
277 self.check_op_spanned(ops::StaticAccess, span)
282 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
283 fn visit_basic_block_data(
286 block: &BasicBlockData<'tcx>,
288 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
290 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
291 // These blocks often drop locals that would otherwise be returned from the function.
293 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
294 // error anyway, but maybe we should do more here?
295 if block.is_cleanup {
299 self.super_basic_block_data(bb, block);
302 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
303 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
305 // Special-case reborrows to be more like a copy of a reference.
306 if let Rvalue::Ref(_, kind, ref place) = *rvalue {
307 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
308 let ctx = match kind {
309 BorrowKind::Shared => PlaceContext::NonMutatingUse(
310 NonMutatingUseContext::SharedBorrow,
312 BorrowKind::Shallow => PlaceContext::NonMutatingUse(
313 NonMutatingUseContext::ShallowBorrow,
315 BorrowKind::Unique => PlaceContext::NonMutatingUse(
316 NonMutatingUseContext::UniqueBorrow,
318 BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
319 MutatingUseContext::Borrow,
322 self.visit_place_base(&place.base, ctx, location);
323 self.visit_projection(&place.base, reborrowed_proj, ctx, location);
328 self.super_rvalue(rvalue, location);
333 Rvalue::UnaryOp(UnOp::Neg, _) |
334 Rvalue::UnaryOp(UnOp::Not, _) |
335 Rvalue::NullaryOp(NullOp::SizeOf, _) |
336 Rvalue::CheckedBinaryOp(..) |
337 Rvalue::Cast(CastKind::Pointer(_), ..) |
338 Rvalue::Discriminant(..) |
340 Rvalue::Aggregate(..) => {}
342 | Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
343 | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place)
345 let ty = place.ty(self.body, self.tcx).ty;
346 let is_allowed = match ty.kind {
347 // Inside a `static mut`, `&mut [...]` is allowed.
348 ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut
351 // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
352 // that this is merely a ZST and it is already eligible for promotion.
353 // This may require an RFC?
355 ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
363 self.check_op(ops::MutBorrow(kind));
367 // Taking a shared borrow of a `static` is always legal, even if that `static` has
368 // interior mutability.
369 | Rvalue::Ref(_, BorrowKind::Shared, ref place)
370 | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
371 if matches!(place.base, PlaceBase::Static(_))
374 | Rvalue::Ref(_, kind @ BorrowKind::Shared, ref place)
375 | Rvalue::Ref(_, kind @ BorrowKind::Shallow, ref place)
377 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
378 // seek the cursors beforehand.
379 self.qualifs.has_mut_interior.cursor.seek_before(location);
380 self.qualifs.indirectly_mutable.seek(location);
382 let borrowed_place_has_mut_interior = HasMutInterior::in_place(
384 &|local| self.qualifs.has_mut_interior_eager_seek(local),
388 if borrowed_place_has_mut_interior {
389 self.check_op(ops::MutBorrow(kind));
393 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
394 let operand_ty = operand.ty(self.body, self.tcx);
395 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
396 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
398 if let (CastTy::Ptr(_), CastTy::Int(_))
399 | (CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
400 self.check_op(ops::RawPtrToIntCast);
404 Rvalue::BinaryOp(op, ref lhs, _) => {
405 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
406 assert!(op == BinOp::Eq || op == BinOp::Ne ||
407 op == BinOp::Le || op == BinOp::Lt ||
408 op == BinOp::Ge || op == BinOp::Gt ||
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");
449 self.super_operand(op, location);
450 if let Operand::Constant(c) = op {
451 if let Some(def_id) = c.check_static_ptr(self.tcx) {
452 self.check_static(def_id, self.span);
457 fn visit_projection_elem(
459 place_base: &PlaceBase<'tcx>,
460 proj_base: &[PlaceElem<'tcx>],
461 elem: &PlaceElem<'tcx>,
462 context: PlaceContext,
466 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
467 context={:?} location={:?}",
475 self.super_projection_elem(place_base, proj_base, elem, context, location);
478 ProjectionElem::Deref => {
479 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
480 if let ty::RawPtr(_) = base_ty.kind {
481 if proj_base.is_empty() {
482 if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
483 let decl = &self.body.local_decls[*local];
484 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
485 let span = decl.source_info.span;
486 self.check_static(def_id, span);
491 self.check_op(ops::RawPtrDeref);
494 if context.is_mutating_use() {
495 self.check_op(ops::MutDeref);
499 ProjectionElem::ConstantIndex {..} |
500 ProjectionElem::Subslice {..} |
501 ProjectionElem::Field(..) |
502 ProjectionElem::Index(_) => {
503 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
504 match base_ty.ty_adt_def() {
505 Some(def) if def.is_union() => {
506 self.check_op(ops::UnionAccess);
513 ProjectionElem::Downcast(..) => {
514 self.check_op(ops::Downcast);
520 fn visit_source_info(&mut self, source_info: &SourceInfo) {
521 trace!("visit_source_info: source_info={:?}", source_info);
522 self.span = source_info.span;
525 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
526 trace!("visit_statement: statement={:?} location={:?}", statement, location);
528 match statement.kind {
529 StatementKind::Assign(..) => {
530 self.super_statement(statement, location);
532 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
533 self.check_op(ops::IfOrMatch);
535 // FIXME(eddyb) should these really do nothing?
536 StatementKind::FakeRead(..) |
537 StatementKind::SetDiscriminant { .. } |
538 StatementKind::StorageLive(_) |
539 StatementKind::StorageDead(_) |
540 StatementKind::InlineAsm {..} |
541 StatementKind::Retag { .. } |
542 StatementKind::AscribeUserType(..) |
543 StatementKind::Nop => {}
547 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
548 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
549 self.super_terminator_kind(kind, location);
552 TerminatorKind::Call { func, .. } => {
553 let fn_ty = func.ty(self.body, self.tcx);
555 let def_id = match fn_ty.kind {
556 ty::FnDef(def_id, _) => def_id,
559 self.check_op(ops::FnCallIndirect);
563 self.check_op(ops::FnCallOther);
568 // At this point, we are calling a function whose `DefId` is known...
570 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = self.tcx.fn_sig(def_id).abi() {
571 assert!(!self.tcx.is_const_fn(def_id));
573 if self.tcx.item_name(def_id) == sym::transmute {
574 self.check_op(ops::Transmute);
578 // To preserve the current semantics, we return early, allowing all
579 // intrinsics (except `transmute`) to pass unchecked to miri.
581 // FIXME: We should keep a whitelist of allowed intrinsics (or at least a
582 // blacklist of unimplemented ones) and fail here instead.
586 if self.tcx.is_const_fn(def_id) {
590 if is_lang_panic_fn(self.tcx, def_id) {
591 self.check_op(ops::Panic);
592 } else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
593 // Exempt unstable const fns inside of macros with
594 // `#[allow_internal_unstable]`.
595 if !self.span.allows_unstable(feature) {
596 self.check_op(ops::FnCallUnstable(def_id, feature));
599 self.check_op(ops::FnCallNonConst(def_id));
604 // Forbid all `Drop` terminators unless the place being dropped is a local with no
605 // projections that cannot be `NeedsDrop`.
606 | TerminatorKind::Drop { location: dropped_place, .. }
607 | TerminatorKind::DropAndReplace { location: dropped_place, .. }
609 let mut err_span = self.span;
611 // Check to see if the type of this place can ever have a drop impl. If not, this
612 // `Drop` terminator is frivolous.
613 let ty_needs_drop = dropped_place
614 .ty(self.body, self.tcx)
616 .needs_drop(self.tcx, self.param_env);
622 let needs_drop = if let Some(local) = dropped_place.as_local() {
623 // Use the span where the local was declared as the span of the drop error.
624 err_span = self.body.local_decls[local].source_info.span;
625 self.qualifs.needs_drop_lazy_seek(local, location)
631 self.check_op_spanned(ops::LiveDrop, err_span);
640 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
641 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
642 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
643 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
647 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
648 let body = item.body;
650 if body.control_flow_destroyed.is_empty() {
654 let mut locals = body.vars_iter();
655 if let Some(local) = locals.next() {
656 let span = body.local_decls[local].source_info.span;
657 let mut error = item.tcx.sess.struct_span_err(
660 "new features like let bindings are not permitted in {}s \
661 which also use short circuiting operators",
665 for (span, kind) in body.control_flow_destroyed.iter() {
668 &format!("use of {} here does not actually short circuit due to \
669 the const evaluator presently not being able to do control flow. \
670 See https://github.com/rust-lang/rust/issues/49146 for more \
671 information.", kind),
674 for local in locals {
675 let span = body.local_decls[local].source_info.span;
676 error.span_note(span, "more locals defined here");
682 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
683 let ty = body.return_ty();
684 tcx.infer_ctxt().enter(|infcx| {
685 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
686 let mut fulfillment_cx = traits::FulfillmentContext::new();
687 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
688 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
689 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
690 infcx.report_fulfillment_errors(&err, None, false);
695 fn place_as_reborrow(
698 place: &'a Place<'tcx>,
699 ) -> Option<&'a [PlaceElem<'tcx>]> {
703 .and_then(|(outermost, inner)| {
704 if outermost != &ProjectionElem::Deref {
708 let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
709 match inner_ty.kind {
710 ty::Ref(..) => Some(inner),