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 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
27 pub enum CheckOpResult {
33 pub type IndirectlyMutableResults<'mir, 'tcx> =
34 old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
36 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
37 cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
38 in_any_value_of_ty: BitSet<Local>,
41 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
44 item: &'a Item<'mir, 'tcx>,
45 dead_unwinds: &BitSet<BasicBlock>,
47 let analysis = FlowSensitiveAnalysis::new(q, item);
49 dataflow::Engine::new(item.tcx, item.body, item.def_id, dead_unwinds, analysis)
50 .iterate_to_fixpoint();
51 let cursor = dataflow::ResultsCursor::new(item.body, results);
53 let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
54 for (local, decl) in item.body.local_decls.iter_enumerated() {
55 if Q::in_any_value_of_ty(item, decl.ty) {
56 in_any_value_of_ty.insert(local);
67 pub struct Qualifs<'a, 'mir, 'tcx> {
68 has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
69 needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
70 indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
73 impl Qualifs<'a, 'mir, 'tcx> {
74 fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
75 self.indirectly_mutable.seek(location);
76 self.indirectly_mutable.get().contains(local)
79 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
81 /// Only updates the cursor if absolutely necessary
82 fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
83 if !self.needs_drop.in_any_value_of_ty.contains(local) {
87 self.needs_drop.cursor.seek_before(location);
88 self.needs_drop.cursor.get().contains(local)
89 || self.indirectly_mutable(local, location)
92 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
94 /// Only updates the cursor if absolutely necessary.
95 fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
96 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
100 self.has_mut_interior.cursor.seek_before(location);
101 self.has_mut_interior.cursor.get().contains(local)
102 || self.indirectly_mutable(local, location)
105 /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
106 /// `indirectly_mutable` cursors to be updated beforehand.
107 fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
108 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
112 self.has_mut_interior.cursor.get().contains(local)
113 || self.indirectly_mutable.get().contains(local)
116 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
117 // Find the `Return` terminator if one exists.
119 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
120 // qualifs for the return type.
121 let return_block = item.body
125 match block.terminator().kind {
126 TerminatorKind::Return => true,
132 let return_block = match return_block {
133 None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
137 let return_loc = item.body.terminator_loc(return_block);
140 needs_drop: self.needs_drop_lazy_seek(RETURN_PLACE, return_loc),
141 has_mut_interior: self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc),
146 pub struct Validator<'a, 'mir, 'tcx> {
147 item: &'a Item<'mir, 'tcx>,
148 qualifs: Qualifs<'a, 'mir, 'tcx>,
150 /// The span of the current statement.
153 /// True if the local was assigned the result of an illegal borrow (`ops::MutBorrow`).
155 /// This is used to hide errors from {re,}borrowing the newly-assigned local, instead pointing
156 /// the user to the place where the illegal borrow occurred. This set is only populated once an
157 /// error has been emitted, so it will never cause an erroneous `mir::Body` to pass validation.
159 /// FIXME(ecstaticmorse): assert at the end of checking that if `tcx.has_errors() == false`,
160 /// this set is empty. Note that if we start removing locals from
161 /// `derived_from_illegal_borrow`, just checking at the end won't be enough.
162 derived_from_illegal_borrow: BitSet<Local>,
165 impl Deref for Validator<'_, 'mir, 'tcx> {
166 type Target = Item<'mir, 'tcx>;
168 fn deref(&self) -> &Self::Target {
173 impl Validator<'a, 'mir, 'tcx> {
175 item: &'a Item<'mir, 'tcx>,
177 let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
179 let needs_drop = QualifCursor::new(
185 let has_mut_interior = QualifCursor::new(
191 let indirectly_mutable = old_dataflow::do_dataflow(
195 &item.tcx.get_attrs(item.def_id),
197 old_dataflow::IndirectlyMutableLocals::new(item.tcx, item.body, item.param_env),
198 |_, local| old_dataflow::DebugFormatted::new(&local),
201 let indirectly_mutable = old_dataflow::DataflowResultsCursor::new(
206 let qualifs = Qualifs {
213 span: item.body.span,
216 derived_from_illegal_borrow: BitSet::new_empty(item.body.local_decls.len()),
220 pub fn check_body(&mut self) {
221 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
223 let use_min_const_fn_checks =
224 tcx.is_min_const_fn(def_id)
225 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
227 if use_min_const_fn_checks {
228 // Enforce `min_const_fn` for stable `const fn`s.
229 use crate::transform::qualify_min_const_fn::is_min_const_fn;
230 if let Err((span, err)) = is_min_const_fn(tcx, def_id, body) {
231 error_min_const_fn_violation(tcx, span, err);
236 check_short_circuiting_in_const_local(self.item);
238 if body.is_cfg_cyclic() {
239 // We can't provide a good span for the error here, but this should be caught by the
240 // HIR const-checker anyways.
241 self.check_op_spanned(ops::Loop, body.span);
244 self.visit_body(body);
246 // Ensure that the end result is `Sync` in a non-thread local `static`.
247 let should_check_for_sync = const_kind == Some(ConstKind::Static)
248 && !tcx.has_attr(def_id, sym::thread_local);
250 if should_check_for_sync {
251 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
252 check_return_ty_is_sync(tcx, body, hir_id);
256 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
257 self.qualifs.in_return_place(self.item)
260 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
261 /// context. Returns `Forbidden` if an error was emitted.
262 pub fn check_op_spanned<O>(&mut self, op: O, span: Span) -> CheckOpResult
266 trace!("check_op: op={:?}", op);
268 if op.is_allowed_in_item(self) {
269 return CheckOpResult::Allowed;
272 // If an operation is supported in miri (and is not already controlled by a feature gate) it
273 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
274 let is_unleashable = O::IS_SUPPORTED_IN_MIRI
275 && O::feature_gate(self.tcx).is_none();
277 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
278 self.tcx.sess.span_warn(span, "skipping const checks");
279 return CheckOpResult::Unleashed;
282 op.emit_error(self, span);
283 CheckOpResult::Forbidden
286 /// Emits an error if an expression cannot be evaluated in the current context.
287 pub fn check_op(&mut self, op: impl NonConstOp) -> CheckOpResult {
288 let span = self.span;
289 self.check_op_spanned(op, span)
292 fn check_static(&mut self, def_id: DefId, span: Span) -> CheckOpResult {
293 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
295 self.check_op_spanned(ops::ThreadLocalAccess, span)
297 self.check_op_spanned(ops::StaticAccess, span)
302 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
303 fn visit_basic_block_data(
306 block: &BasicBlockData<'tcx>,
308 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
310 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
311 // These blocks often drop locals that would otherwise be returned from the function.
313 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
314 // error anyway, but maybe we should do more here?
315 if block.is_cleanup {
319 self.super_basic_block_data(bb, block);
322 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
323 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
325 // Check nested operands and places.
326 if let Rvalue::Ref(_, kind, ref place) = *rvalue {
327 // Special-case reborrows to be more like a copy of a reference.
328 let mut reborrow_place = None;
329 if let &[ref proj_base @ .., elem] = place.projection.as_ref() {
330 if elem == ProjectionElem::Deref {
331 let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
332 if let ty::Ref(..) = base_ty.kind {
333 reborrow_place = Some(proj_base);
338 if let Some(proj) = reborrow_place {
339 let ctx = match kind {
340 BorrowKind::Shared => PlaceContext::NonMutatingUse(
341 NonMutatingUseContext::SharedBorrow,
343 BorrowKind::Shallow => PlaceContext::NonMutatingUse(
344 NonMutatingUseContext::ShallowBorrow,
346 BorrowKind::Unique => PlaceContext::NonMutatingUse(
347 NonMutatingUseContext::UniqueBorrow,
349 BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
350 MutatingUseContext::Borrow,
353 self.visit_place_base(&place.base, ctx, location);
354 self.visit_projection(&place.base, proj, ctx, location);
356 self.super_rvalue(rvalue, location);
359 self.super_rvalue(rvalue, location);
365 Rvalue::UnaryOp(UnOp::Neg, _) |
366 Rvalue::UnaryOp(UnOp::Not, _) |
367 Rvalue::NullaryOp(NullOp::SizeOf, _) |
368 Rvalue::CheckedBinaryOp(..) |
369 Rvalue::Cast(CastKind::Pointer(_), ..) |
370 Rvalue::Discriminant(..) |
373 Rvalue::Aggregate(..) => {}
375 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
376 let operand_ty = operand.ty(self.body, self.tcx);
377 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
378 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
380 if let (CastTy::Ptr(_), CastTy::Int(_))
381 | (CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
382 self.check_op(ops::RawPtrToIntCast);
386 Rvalue::BinaryOp(op, ref lhs, _) => {
387 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
388 assert!(op == BinOp::Eq || op == BinOp::Ne ||
389 op == BinOp::Le || op == BinOp::Lt ||
390 op == BinOp::Ge || op == BinOp::Gt ||
391 op == BinOp::Offset);
394 self.check_op(ops::RawPtrComparison);
398 Rvalue::NullaryOp(NullOp::Box, _) => {
399 self.check_op(ops::HeapAllocation);
406 place_base: &PlaceBase<'tcx>,
407 context: PlaceContext,
411 "visit_place_base: place_base={:?} context={:?} location={:?}",
416 self.super_place_base(place_base, context, location);
419 PlaceBase::Local(_) => {}
420 PlaceBase::Static(_) => {
421 bug!("Promotion must be run after const validation");
431 self.super_operand(op, location);
432 if let Operand::Constant(c) = op {
433 if let Some(def_id) = c.check_static_ptr(self.tcx) {
434 self.check_static(def_id, self.span);
439 fn visit_assign(&mut self, dest: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
440 trace!("visit_assign: dest={:?} rvalue={:?} location={:?}", dest, rvalue, location);
442 // Error on mutable borrows or shared borrows of values with interior mutability.
444 // This replicates the logic at the start of `assign` in the old const checker. Note that
445 // it depends on `HasMutInterior` being set for mutable borrows as well as values with
446 // interior mutability.
447 if let Rvalue::Ref(_, kind, ref borrowed_place) = *rvalue {
448 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually seek
449 // the cursors beforehand.
450 self.qualifs.has_mut_interior.cursor.seek_before(location);
451 self.qualifs.indirectly_mutable.seek(location);
453 let rvalue_has_mut_interior = HasMutInterior::in_rvalue(
455 &|local| self.qualifs.has_mut_interior_eager_seek(local),
459 if rvalue_has_mut_interior {
460 let is_derived_from_illegal_borrow = match borrowed_place.as_local() {
461 // If an unprojected local was borrowed and its value was the result of an
462 // illegal borrow, suppress this error and mark the result of this borrow as
465 if self.derived_from_illegal_borrow.contains(borrowed_local) =>
470 // Otherwise proceed normally: check the legality of a mutable borrow in this
472 _ => self.check_op(ops::MutBorrow(kind)) == CheckOpResult::Forbidden,
475 // When the target of the assignment is a local with no projections, mark it as
476 // derived from an illegal borrow if necessary.
478 // FIXME: should we also clear `derived_from_illegal_borrow` when a local is
479 // assigned a new value?
480 if is_derived_from_illegal_borrow {
481 if let Some(dest) = dest.as_local() {
482 self.derived_from_illegal_borrow.insert(dest);
488 self.super_assign(dest, rvalue, location);
491 fn visit_projection_elem(
493 place_base: &PlaceBase<'tcx>,
494 proj_base: &[PlaceElem<'tcx>],
495 elem: &PlaceElem<'tcx>,
496 context: PlaceContext,
500 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
501 context={:?} location={:?}",
509 self.super_projection_elem(place_base, proj_base, elem, context, location);
512 ProjectionElem::Deref => {
513 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
514 if let ty::RawPtr(_) = base_ty.kind {
515 if proj_base.is_empty() {
516 if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
517 let decl = &self.body.local_decls[*local];
518 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
519 let span = decl.source_info.span;
520 self.check_static(def_id, span);
525 self.check_op(ops::RawPtrDeref);
528 if context.is_mutating_use() {
529 self.check_op(ops::MutDeref);
533 ProjectionElem::ConstantIndex {..} |
534 ProjectionElem::Subslice {..} |
535 ProjectionElem::Field(..) |
536 ProjectionElem::Index(_) => {
537 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
538 match base_ty.ty_adt_def() {
539 Some(def) if def.is_union() => {
540 self.check_op(ops::UnionAccess);
547 ProjectionElem::Downcast(..) => {
548 self.check_op(ops::Downcast);
554 fn visit_source_info(&mut self, source_info: &SourceInfo) {
555 trace!("visit_source_info: source_info={:?}", source_info);
556 self.span = source_info.span;
559 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
560 trace!("visit_statement: statement={:?} location={:?}", statement, location);
562 match statement.kind {
563 StatementKind::Assign(..) => {
564 self.super_statement(statement, location);
566 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
567 self.check_op(ops::IfOrMatch);
569 StatementKind::SetDiscriminant { .. } => {
570 self.super_statement(statement, location)
572 // FIXME(eddyb) should these really do nothing?
573 StatementKind::FakeRead(..) |
574 StatementKind::StorageLive(_) |
575 StatementKind::StorageDead(_) |
576 StatementKind::InlineAsm {..} |
577 StatementKind::Retag { .. } |
578 StatementKind::AscribeUserType(..) |
579 StatementKind::Nop => {}
583 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
584 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
585 self.super_terminator_kind(kind, location);
588 TerminatorKind::Call { func, .. } => {
589 let fn_ty = func.ty(self.body, self.tcx);
591 let def_id = match fn_ty.kind {
592 ty::FnDef(def_id, _) => def_id,
595 self.check_op(ops::FnCallIndirect);
599 self.check_op(ops::FnCallOther);
604 // At this point, we are calling a function whose `DefId` is known...
606 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = self.tcx.fn_sig(def_id).abi() {
607 assert!(!self.tcx.is_const_fn(def_id));
609 if self.tcx.item_name(def_id) == sym::transmute {
610 self.check_op(ops::Transmute);
614 // To preserve the current semantics, we return early, allowing all
615 // intrinsics (except `transmute`) to pass unchecked to miri.
617 // FIXME: We should keep a whitelist of allowed intrinsics (or at least a
618 // blacklist of unimplemented ones) and fail here instead.
622 if self.tcx.is_const_fn(def_id) {
626 if is_lang_panic_fn(self.tcx, def_id) {
627 self.check_op(ops::Panic);
628 } else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
629 // Exempt unstable const fns inside of macros with
630 // `#[allow_internal_unstable]`.
631 if !self.span.allows_unstable(feature) {
632 self.check_op(ops::FnCallUnstable(def_id, feature));
635 self.check_op(ops::FnCallNonConst(def_id));
640 // Forbid all `Drop` terminators unless the place being dropped is a local with no
641 // projections that cannot be `NeedsDrop`.
642 | TerminatorKind::Drop { location: dropped_place, .. }
643 | TerminatorKind::DropAndReplace { location: dropped_place, .. }
645 let mut err_span = self.span;
647 // Check to see if the type of this place can ever have a drop impl. If not, this
648 // `Drop` terminator is frivolous.
649 let ty_needs_drop = dropped_place
650 .ty(self.body, self.tcx)
652 .needs_drop(self.tcx, self.param_env);
658 let needs_drop = if let Some(local) = dropped_place.as_local() {
659 // Use the span where the local was declared as the span of the drop error.
660 err_span = self.body.local_decls[local].source_info.span;
661 self.qualifs.needs_drop_lazy_seek(local, location)
667 self.check_op_spanned(ops::LiveDrop, err_span);
676 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
677 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
678 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
679 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
683 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
684 let body = item.body;
686 if body.control_flow_destroyed.is_empty() {
690 let mut locals = body.vars_iter();
691 if let Some(local) = locals.next() {
692 let span = body.local_decls[local].source_info.span;
693 let mut error = item.tcx.sess.struct_span_err(
696 "new features like let bindings are not permitted in {}s \
697 which also use short circuiting operators",
701 for (span, kind) in body.control_flow_destroyed.iter() {
704 &format!("use of {} here does not actually short circuit due to \
705 the const evaluator presently not being able to do control flow. \
706 See https://github.com/rust-lang/rust/issues/49146 for more \
707 information.", kind),
710 for local in locals {
711 let span = body.local_decls[local].source_info.span;
712 error.span_note(span, "more locals defined here");
718 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
719 let ty = body.return_ty();
720 tcx.infer_ctxt().enter(|infcx| {
721 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
722 let mut fulfillment_cx = traits::FulfillmentContext::new();
723 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
724 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
725 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
726 infcx.report_fulfillment_errors(&err, None, false);