1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
3 use rustc::middle::lang_items;
4 use rustc::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
6 use rustc::traits::{self, TraitEngine};
7 use rustc::ty::cast::CastTy;
8 use rustc::ty::{self, TyCtxt};
9 use rustc_errors::struct_span_err;
10 use rustc_hir::{def_id::DefId, HirId};
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::const_eval::{is_const_fn, is_unstable_const_fn};
24 use crate::dataflow::{self as old_dataflow, generic as dataflow};
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> {
35 pub fn new(q: Q, item: &'a Item<'mir, 'tcx>) -> Self {
36 let analysis = FlowSensitiveAnalysis::new(q, item);
37 let results = dataflow::Engine::new_generic(item.tcx, &item.body, item.def_id, 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(&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(&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 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
90 // Find the `Return` terminator if one exists.
92 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
93 // qualifs for the return type.
94 let return_block = item
98 .find(|(_, block)| match block.terminator().kind {
99 TerminatorKind::Return => true,
104 let return_block = match return_block {
105 None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
109 let return_loc = item.body.terminator_loc(return_block);
112 needs_drop: self.needs_drop(RETURN_PLACE, return_loc),
113 has_mut_interior: self.has_mut_interior(RETURN_PLACE, return_loc),
118 pub struct Validator<'a, 'mir, 'tcx> {
119 item: &'a Item<'mir, 'tcx>,
120 qualifs: Qualifs<'a, 'mir, 'tcx>,
122 /// The span of the current statement.
126 impl Deref for Validator<'_, 'mir, 'tcx> {
127 type Target = Item<'mir, 'tcx>;
129 fn deref(&self) -> &Self::Target {
134 impl Validator<'a, 'mir, 'tcx> {
135 pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
136 let needs_drop = QualifCursor::new(NeedsDrop, item);
137 let has_mut_interior = QualifCursor::new(HasMutInterior, item);
139 let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
140 let indirectly_mutable = old_dataflow::do_dataflow(
144 &item.tcx.get_attrs(item.def_id),
146 old_dataflow::IndirectlyMutableLocals::new(item.tcx, *item.body, item.param_env),
147 |_, local| old_dataflow::DebugFormatted::new(&local),
150 let indirectly_mutable =
151 old_dataflow::DataflowResultsCursor::new(indirectly_mutable, *item.body);
153 let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable };
155 Validator { span: item.body.span, item, qualifs }
158 pub fn check_body(&mut self) {
159 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
161 let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
162 && crate::const_eval::is_min_const_fn(tcx, def_id))
163 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
165 if use_min_const_fn_checks {
166 // Enforce `min_const_fn` for stable `const fn`s.
167 use crate::transform::qualify_min_const_fn::is_min_const_fn;
168 if let Err((span, err)) = is_min_const_fn(tcx, def_id, &body) {
169 error_min_const_fn_violation(tcx, span, err);
174 check_short_circuiting_in_const_local(self.item);
176 if body.is_cfg_cyclic() {
177 // We can't provide a good span for the error here, but this should be caught by the
178 // HIR const-checker anyways.
179 self.check_op_spanned(ops::Loop, body.span);
182 self.visit_body(body);
184 // Ensure that the end result is `Sync` in a non-thread local `static`.
185 let should_check_for_sync =
186 const_kind == Some(ConstKind::Static) && !tcx.has_attr(def_id, sym::thread_local);
188 if should_check_for_sync {
189 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
190 check_return_ty_is_sync(tcx, &body, hir_id);
194 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
195 self.qualifs.in_return_place(self.item)
198 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
200 pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
204 trace!("check_op: op={:?}", op);
206 if op.is_allowed_in_item(self) {
210 // If an operation is supported in miri (and is not already controlled by a feature gate) it
211 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
212 let is_unleashable = O::IS_SUPPORTED_IN_MIRI && O::feature_gate(self.tcx).is_none();
214 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
215 self.tcx.sess.span_warn(span, "skipping const checks");
219 op.emit_error(self, span);
222 /// Emits an error if an expression cannot be evaluated in the current context.
223 pub fn check_op(&mut self, op: impl NonConstOp) {
224 let span = self.span;
225 self.check_op_spanned(op, span)
228 fn check_static(&mut self, def_id: DefId, span: Span) {
229 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
231 self.check_op_spanned(ops::ThreadLocalAccess, span)
233 self.check_op_spanned(ops::StaticAccess, span)
237 fn check_immutable_borrow_like(&mut self, location: Location, place: &Place<'tcx>) {
238 let borrowed_place_has_mut_interior = HasMutInterior::in_place(
240 &mut |local| self.qualifs.has_mut_interior(local, location),
244 if borrowed_place_has_mut_interior {
245 self.check_op(ops::CellBorrow);
250 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
251 fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
252 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
254 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
255 // These blocks often drop locals that would otherwise be returned from the function.
257 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
258 // error anyway, but maybe we should do more here?
259 if block.is_cleanup {
263 self.super_basic_block_data(bb, block);
266 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
267 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
269 // Special-case reborrows to be more like a copy of a reference.
271 Rvalue::Ref(_, kind, ref place) => {
272 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
273 let ctx = match kind {
274 BorrowKind::Shared => {
275 PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
277 BorrowKind::Shallow => {
278 PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
280 BorrowKind::Unique => {
281 PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
283 BorrowKind::Mut { .. } => {
284 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
287 self.visit_place_base(&place.local, ctx, location);
288 self.visit_projection(&place.local, reborrowed_proj, ctx, location);
292 Rvalue::AddressOf(mutbl, ref place) => {
293 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
294 let ctx = match mutbl {
296 PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf)
298 Mutability::Mut => PlaceContext::MutatingUse(MutatingUseContext::AddressOf),
300 self.visit_place_base(&place.local, ctx, location);
301 self.visit_projection(&place.local, reborrowed_proj, ctx, location);
308 self.super_rvalue(rvalue, location);
313 | Rvalue::UnaryOp(UnOp::Neg, _)
314 | Rvalue::UnaryOp(UnOp::Not, _)
315 | Rvalue::NullaryOp(NullOp::SizeOf, _)
316 | Rvalue::CheckedBinaryOp(..)
317 | Rvalue::Cast(CastKind::Pointer(_), ..)
318 | Rvalue::Discriminant(..)
320 | Rvalue::Aggregate(..) => {}
322 Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
323 | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place) => {
324 let ty = place.ty(*self.body, self.tcx).ty;
325 let is_allowed = match ty.kind {
326 // Inside a `static mut`, `&mut [...]` is allowed.
327 ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut => {
331 // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
332 // that this is merely a ZST and it is already eligible for promotion.
333 // This may require an RFC?
335 ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
342 if let BorrowKind::Mut { .. } = kind {
343 self.check_op(ops::MutBorrow);
345 self.check_op(ops::CellBorrow);
350 Rvalue::AddressOf(Mutability::Mut, _) => self.check_op(ops::MutAddressOf),
352 Rvalue::Ref(_, BorrowKind::Shared, ref place)
353 | Rvalue::Ref(_, BorrowKind::Shallow, ref place) => {
354 self.check_immutable_borrow_like(location, place)
357 Rvalue::AddressOf(Mutability::Not, ref place) => {
358 self.check_immutable_borrow_like(location, place)
361 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
362 let operand_ty = operand.ty(*self.body, self.tcx);
363 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
364 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
366 if let (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) =
369 self.check_op(ops::RawPtrToIntCast);
373 Rvalue::BinaryOp(op, ref lhs, _) => {
374 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
382 || op == BinOp::Offset
385 self.check_op(ops::RawPtrComparison);
389 Rvalue::NullaryOp(NullOp::Box, _) => {
390 self.check_op(ops::HeapAllocation);
395 fn visit_place_base(&mut self, place_local: &Local, context: PlaceContext, location: Location) {
397 "visit_place_base: place_local={:?} context={:?} location={:?}",
402 self.super_place_base(place_local, context, location);
405 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
406 self.super_operand(op, location);
407 if let Operand::Constant(c) = op {
408 if let Some(def_id) = c.check_static_ptr(self.tcx) {
409 self.check_static(def_id, self.span);
413 fn visit_projection_elem(
416 proj_base: &[PlaceElem<'tcx>],
417 elem: &PlaceElem<'tcx>,
418 context: PlaceContext,
422 "visit_projection_elem: place_local={:?} proj_base={:?} elem={:?} \
423 context={:?} location={:?}",
431 self.super_projection_elem(place_local, proj_base, elem, context, location);
434 ProjectionElem::Deref => {
435 let base_ty = Place::ty_from(*place_local, proj_base, *self.body, self.tcx).ty;
436 if let ty::RawPtr(_) = base_ty.kind {
437 if proj_base.is_empty() {
438 if let (local, []) = (place_local, proj_base) {
439 let decl = &self.body.local_decls[*local];
440 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
441 let span = decl.source_info.span;
442 self.check_static(def_id, span);
447 self.check_op(ops::RawPtrDeref);
450 if context.is_mutating_use() {
451 self.check_op(ops::MutDeref);
455 ProjectionElem::ConstantIndex { .. }
456 | ProjectionElem::Subslice { .. }
457 | ProjectionElem::Field(..)
458 | ProjectionElem::Index(_) => {
459 let base_ty = Place::ty_from(*place_local, proj_base, *self.body, self.tcx).ty;
460 match base_ty.ty_adt_def() {
461 Some(def) if def.is_union() => {
462 self.check_op(ops::UnionAccess);
469 ProjectionElem::Downcast(..) => {
470 self.check_op(ops::Downcast);
475 fn visit_source_info(&mut self, source_info: &SourceInfo) {
476 trace!("visit_source_info: source_info={:?}", source_info);
477 self.span = source_info.span;
480 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
481 trace!("visit_statement: statement={:?} location={:?}", statement, location);
483 match statement.kind {
484 StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
485 self.super_statement(statement, location);
487 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
488 self.check_op(ops::IfOrMatch);
490 // FIXME(eddyb) should these really do nothing?
491 StatementKind::FakeRead(..)
492 | StatementKind::StorageLive(_)
493 | StatementKind::StorageDead(_)
494 | StatementKind::InlineAsm { .. }
495 | StatementKind::Retag { .. }
496 | StatementKind::AscribeUserType(..)
497 | StatementKind::Nop => {}
501 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
502 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
503 self.super_terminator_kind(kind, location);
506 TerminatorKind::Call { func, .. } => {
507 let fn_ty = func.ty(*self.body, self.tcx);
509 let def_id = match fn_ty.kind {
510 ty::FnDef(def_id, _) => def_id,
513 self.check_op(ops::FnCallIndirect);
517 self.check_op(ops::FnCallOther);
522 // At this point, we are calling a function whose `DefId` is known...
523 if is_const_fn(self.tcx, def_id) {
527 if is_lang_panic_fn(self.tcx, def_id) {
528 self.check_op(ops::Panic);
529 } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) {
530 // Exempt unstable const fns inside of macros with
531 // `#[allow_internal_unstable]`.
532 if !self.span.allows_unstable(feature) {
533 self.check_op(ops::FnCallUnstable(def_id, feature));
536 self.check_op(ops::FnCallNonConst(def_id));
540 // Forbid all `Drop` terminators unless the place being dropped is a local with no
541 // projections that cannot be `NeedsDrop`.
542 TerminatorKind::Drop { location: dropped_place, .. }
543 | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
544 let mut err_span = self.span;
546 // Check to see if the type of this place can ever have a drop impl. If not, this
547 // `Drop` terminator is frivolous.
549 dropped_place.ty(*self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
555 let needs_drop = if let Some(local) = dropped_place.as_local() {
556 // Use the span where the local was declared as the span of the drop error.
557 err_span = self.body.local_decls[local].source_info.span;
558 self.qualifs.needs_drop(local, location)
564 self.check_op_spanned(ops::LiveDrop, err_span);
573 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
574 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
575 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
576 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
580 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
581 let body = item.body;
583 if body.control_flow_destroyed.is_empty() {
587 let mut locals = body.vars_iter();
588 if let Some(local) = locals.next() {
589 let span = body.local_decls[local].source_info.span;
590 let mut error = item.tcx.sess.struct_span_err(
593 "new features like let bindings are not permitted in {}s \
594 which also use short circuiting operators",
598 for (span, kind) in body.control_flow_destroyed.iter() {
602 "use of {} here does not actually short circuit due to \
603 the const evaluator presently not being able to do control flow. \
604 See https://github.com/rust-lang/rust/issues/49146 for more \
610 for local in locals {
611 let span = body.local_decls[local].source_info.span;
612 error.span_note(span, "more locals defined here");
618 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
619 let ty = body.return_ty();
620 tcx.infer_ctxt().enter(|infcx| {
621 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
622 let mut fulfillment_cx = traits::FulfillmentContext::new();
623 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
624 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
625 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
626 infcx.report_fulfillment_errors(&err, None, false);
631 fn place_as_reborrow(
634 place: &'a Place<'tcx>,
635 ) -> Option<&'a [PlaceElem<'tcx>]> {
636 place.projection.split_last().and_then(|(outermost, inner)| {
637 if outermost != &ProjectionElem::Deref {
641 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
642 // that points to the allocation for the static. Don't treat these as reborrows.
643 if body.local_decls[place.local].is_ref_to_static() {
647 // Ensure the type being derefed is a reference and not a raw pointer.
649 // This is sufficient to prevent an access to a `static mut` from being marked as a
650 // reborrow, even if the check above were to disappear.
651 let inner_ty = Place::ty_from(place.local, inner, body, tcx).ty;
652 match inner_ty.kind {
653 ty::Ref(..) => Some(inner),