diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs index 4dc4fb6d8e936..7de44a656d652 100644 --- a/src/librustc_mir/borrow_check/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/type_check/mod.rs @@ -42,7 +42,10 @@ use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations} use crate::dataflow::move_paths::MoveData; use crate::dataflow::MaybeInitializedPlaces; use crate::dataflow::ResultsCursor; -use crate::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute; +use crate::transform::{ + check_consts::ConstCx, + promote_consts::should_suggest_const_in_array_repeat_expressions_attribute, +}; use crate::borrow_check::{ borrow_set::BorrowSet, @@ -1998,14 +2001,17 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let span = body.source_info(location).span; let ty = operand.ty(*body, tcx); if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) { + let ccx = ConstCx::new_with_param_env( + tcx, + self.mir_def_id, + body, + self.param_env, + ); // To determine if `const_in_array_repeat_expressions` feature gate should // be mentioned, need to check if the rvalue is promotable. let should_suggest = should_suggest_const_in_array_repeat_expressions_attribute( - tcx, - self.mir_def_id, - body, - operand, + &ccx, operand, ); debug!("check_rvalue: should_suggest={:?}", should_suggest); diff --git a/src/librustc_mir/transform/check_consts/mod.rs b/src/librustc_mir/transform/check_consts/mod.rs index bce3a506b1dd9..115523b1f7e05 100644 --- a/src/librustc_mir/transform/check_consts/mod.rs +++ b/src/librustc_mir/transform/check_consts/mod.rs @@ -20,7 +20,7 @@ pub mod validation; /// Information about the item currently being const-checked, as well as a reference to the global /// context. -pub struct Item<'mir, 'tcx> { +pub struct ConstCx<'mir, 'tcx> { pub body: mir::ReadOnlyBodyAndCache<'mir, 'tcx>, pub tcx: TyCtxt<'tcx>, pub def_id: DefId, @@ -28,16 +28,25 @@ pub struct Item<'mir, 'tcx> { pub const_kind: Option, } -impl Item<'mir, 'tcx> { +impl ConstCx<'mir, 'tcx> { pub fn new( tcx: TyCtxt<'tcx>, def_id: DefId, body: mir::ReadOnlyBodyAndCache<'mir, 'tcx>, ) -> Self { let param_env = tcx.param_env(def_id); + Self::new_with_param_env(tcx, def_id, body, param_env) + } + + pub fn new_with_param_env( + tcx: TyCtxt<'tcx>, + def_id: DefId, + body: mir::ReadOnlyBodyAndCache<'mir, 'tcx>, + param_env: ty::ParamEnv<'tcx>, + ) -> Self { let const_kind = ConstKind::for_item(tcx, def_id); - Item { body, tcx, def_id, param_env, const_kind } + ConstCx { body, tcx, def_id, param_env, const_kind } } /// Returns the kind of const context this `Item` represents (`const`, `static`, etc.). diff --git a/src/librustc_mir/transform/check_consts/ops.rs b/src/librustc_mir/transform/check_consts/ops.rs index b3264a7a0321a..180ca2da928db 100644 --- a/src/librustc_mir/transform/check_consts/ops.rs +++ b/src/librustc_mir/transform/check_consts/ops.rs @@ -7,7 +7,7 @@ use rustc_session::parse::feature_err; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; -use super::{ConstKind, Item}; +use super::{ConstCx, ConstKind}; /// An operation that is not *always* allowed in a const context. pub trait NonConstOp: std::fmt::Debug { @@ -27,19 +27,19 @@ pub trait NonConstOp: std::fmt::Debug { /// /// By default, it returns `true` if and only if this operation has a corresponding feature /// gate and that gate is enabled. - fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool { - Self::feature_gate().map_or(false, |gate| item.tcx.features().enabled(gate)) + fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool { + Self::feature_gate().map_or(false, |gate| ccx.tcx.features().enabled(gate)) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0019, "{} contains unimplemented expression type", - item.const_kind() + ccx.const_kind() ); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "A function call isn't allowed in the const's initialization expression \ because the expression's value must be known at compile-time.", @@ -66,9 +66,9 @@ impl NonConstOp for Downcast { #[derive(Debug)] pub struct FnCallIndirect; impl NonConstOp for FnCallIndirect { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = - item.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn"); + ccx.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn"); err.emit(); } } @@ -77,14 +77,14 @@ impl NonConstOp for FnCallIndirect { #[derive(Debug)] pub struct FnCallNonConst(pub DefId); impl NonConstOp for FnCallNonConst { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0015, "calls in {}s are limited to constant functions, \ tuple structs and tuple variants", - item.const_kind(), + ccx.const_kind(), ); err.emit(); } @@ -96,12 +96,12 @@ impl NonConstOp for FnCallNonConst { #[derive(Debug)] pub struct FnCallUnstable(pub DefId, pub Symbol); impl NonConstOp for FnCallUnstable { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let FnCallUnstable(def_id, feature) = *self; - let mut err = item.tcx.sess.struct_span_err( + let mut err = ccx.tcx.sess.struct_span_err( span, - &format!("`{}` is not yet stable as a const fn", item.tcx.def_path_str(def_id)), + &format!("`{}` is not yet stable as a const fn", ccx.tcx.def_path_str(def_id)), ); if nightly_options::is_nightly_build() { err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature)); @@ -115,16 +115,16 @@ pub struct HeapAllocation; impl NonConstOp for HeapAllocation { const IS_SUPPORTED_IN_MIRI: bool = false; - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0010, "allocations are not allowed in {}s", - item.const_kind() + ccx.const_kind() ); - err.span_label(span, format!("allocation not allowed in {}s", item.const_kind())); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + err.span_label(span, format!("allocation not allowed in {}s", ccx.const_kind())); + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "The value of statics and constants must be known at compile time, \ and they live for the entire lifetime of a program. Creating a boxed \ @@ -143,23 +143,23 @@ impl NonConstOp for IfOrMatch { Some(sym::const_if_match) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { // This should be caught by the HIR const-checker. - item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); + ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); } } #[derive(Debug)] pub struct LiveDrop; impl NonConstOp for LiveDrop { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0493, "destructors cannot be evaluated at compile-time" ) - .span_label(span, format!("{}s cannot evaluate destructors", item.const_kind())) + .span_label(span, format!("{}s cannot evaluate destructors", ccx.const_kind())) .emit(); } } @@ -171,18 +171,18 @@ impl NonConstOp for Loop { Some(sym::const_loop) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { // This should be caught by the HIR const-checker. - item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); + ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); } } #[derive(Debug)] pub struct CellBorrow; impl NonConstOp for CellBorrow { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0492, "cannot borrow a constant which may contain \ @@ -199,19 +199,19 @@ impl NonConstOp for MutBorrow { Some(sym::const_mut_refs) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_mut_refs, span, &format!( "references in {}s may only refer \ to immutable values", - item.const_kind() + ccx.const_kind() ), ); - err.span_label(span, format!("{}s require immutable values", item.const_kind())); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + err.span_label(span, format!("{}s require immutable values", ccx.const_kind())); + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "References in statics and constants may only refer \ to immutable values.\n\n\ @@ -234,12 +234,12 @@ impl NonConstOp for MutAddressOf { Some(sym::const_mut_refs) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_mut_refs, span, - &format!("`&raw mut` is not allowed in {}s", item.const_kind()), + &format!("`&raw mut` is not allowed in {}s", ccx.const_kind()), ) .emit(); } @@ -260,12 +260,12 @@ impl NonConstOp for Panic { Some(sym::const_panic) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_panic, span, - &format!("panicking in {}s is unstable", item.const_kind()), + &format!("panicking in {}s is unstable", ccx.const_kind()), ) .emit(); } @@ -278,12 +278,12 @@ impl NonConstOp for RawPtrComparison { Some(sym::const_compare_raw_pointers) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_compare_raw_pointers, span, - &format!("comparing raw pointers inside {}", item.const_kind()), + &format!("comparing raw pointers inside {}", ccx.const_kind()), ) .emit(); } @@ -296,12 +296,12 @@ impl NonConstOp for RawPtrDeref { Some(sym::const_raw_ptr_deref) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_raw_ptr_deref, span, - &format!("dereferencing raw pointers in {}s is unstable", item.const_kind(),), + &format!("dereferencing raw pointers in {}s is unstable", ccx.const_kind(),), ) .emit(); } @@ -314,12 +314,12 @@ impl NonConstOp for RawPtrToIntCast { Some(sym::const_raw_ptr_to_usize_cast) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast, span, - &format!("casting pointers to integers in {}s is unstable", item.const_kind(),), + &format!("casting pointers to integers in {}s is unstable", ccx.const_kind(),), ) .emit(); } @@ -329,22 +329,22 @@ impl NonConstOp for RawPtrToIntCast { #[derive(Debug)] pub struct StaticAccess; impl NonConstOp for StaticAccess { - fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool { - item.const_kind().is_static() + fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool { + ccx.const_kind().is_static() } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0013, "{}s cannot refer to statics", - item.const_kind() + ccx.const_kind() ); err.help( "consider extracting the value of the `static` to a `const`, and referring to that", ); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "`static` and `const` variables can refer to other `const` variables. \ A `const` variable, however, cannot refer to a `static` variable.", @@ -361,9 +361,9 @@ pub struct ThreadLocalAccess; impl NonConstOp for ThreadLocalAccess { const IS_SUPPORTED_IN_MIRI: bool = false; - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0625, "thread-local statics cannot be \ @@ -376,19 +376,19 @@ impl NonConstOp for ThreadLocalAccess { #[derive(Debug)] pub struct UnionAccess; impl NonConstOp for UnionAccess { - fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool { + fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool { // Union accesses are stable in all contexts except `const fn`. - item.const_kind() != ConstKind::ConstFn - || item.tcx.features().enabled(Self::feature_gate().unwrap()) + ccx.const_kind() != ConstKind::ConstFn + || ccx.tcx.features().enabled(Self::feature_gate().unwrap()) } fn feature_gate() -> Option { Some(sym::const_fn_union) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_fn_union, span, "unions in const fn are unstable", diff --git a/src/librustc_mir/transform/check_consts/qualifs.rs b/src/librustc_mir/transform/check_consts/qualifs.rs index f38b9d8ef8586..d960c402aeaea 100644 --- a/src/librustc_mir/transform/check_consts/qualifs.rs +++ b/src/librustc_mir/transform/check_consts/qualifs.rs @@ -6,7 +6,7 @@ use rustc_middle::mir::*; use rustc_middle::ty::{self, AdtDef, Ty}; use rustc_span::DUMMY_SP; -use super::Item as ConstCx; +use super::ConstCx; pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs { ConstQualifs { diff --git a/src/librustc_mir/transform/check_consts/resolver.rs b/src/librustc_mir/transform/check_consts/resolver.rs index b95a3939389ba..40abd84793645 100644 --- a/src/librustc_mir/transform/check_consts/resolver.rs +++ b/src/librustc_mir/transform/check_consts/resolver.rs @@ -8,7 +8,7 @@ use rustc_middle::mir::{self, BasicBlock, Local, Location}; use std::marker::PhantomData; -use super::{qualifs, Item, Qualif}; +use super::{qualifs, ConstCx, Qualif}; use crate::dataflow; /// A `Visitor` that propagates qualifs between locals. This defines the transfer function of @@ -18,7 +18,7 @@ use crate::dataflow; /// the `MaybeMutBorrowedLocals` dataflow pass to see if a `Local` may have become qualified via /// an indirect assignment or function call. struct TransferFunction<'a, 'mir, 'tcx, Q> { - item: &'a Item<'mir, 'tcx>, + ccx: &'a ConstCx<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet, _qualif: PhantomData, @@ -28,16 +28,16 @@ impl TransferFunction<'a, 'mir, 'tcx, Q> where Q: Qualif, { - fn new(item: &'a Item<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet) -> Self { - TransferFunction { item, qualifs_per_local, _qualif: PhantomData } + fn new(ccx: &'a ConstCx<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet) -> Self { + TransferFunction { ccx, qualifs_per_local, _qualif: PhantomData } } fn initialize_state(&mut self) { self.qualifs_per_local.clear(); - for arg in self.item.body.args_iter() { - let arg_ty = self.item.body.local_decls[arg].ty; - if Q::in_any_value_of_ty(self.item, arg_ty) { + for arg in self.ccx.body.args_iter() { + let arg_ty = self.ccx.body.local_decls[arg].ty; + if Q::in_any_value_of_ty(self.ccx, arg_ty) { self.qualifs_per_local.insert(arg); } } @@ -72,8 +72,8 @@ where ) { // We cannot reason about another function's internals, so use conservative type-based // qualification for the result of a function call. - let return_ty = return_place.ty(*self.item.body, self.item.tcx).ty; - let qualif = Q::in_any_value_of_ty(self.item, return_ty); + let return_ty = return_place.ty(*self.ccx.body, self.ccx.tcx).ty; + let qualif = Q::in_any_value_of_ty(self.ccx, return_ty); if !return_place.is_indirect() { self.assign_qualif_direct(&return_place, qualif); @@ -108,7 +108,7 @@ where location: Location, ) { let qualif = qualifs::in_rvalue::( - self.item, + self.ccx, &mut |l| self.qualifs_per_local.contains(l), rvalue, ); @@ -127,7 +127,7 @@ where if let mir::TerminatorKind::DropAndReplace { value, location: dest, .. } = kind { let qualif = qualifs::in_operand::( - self.item, + self.ccx, &mut |l| self.qualifs_per_local.contains(l), value, ); @@ -145,7 +145,7 @@ where /// The dataflow analysis used to propagate qualifs on arbitrary CFGs. pub(super) struct FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> { - item: &'a Item<'mir, 'tcx>, + ccx: &'a ConstCx<'mir, 'tcx>, _qualif: PhantomData, } @@ -153,15 +153,15 @@ impl<'a, 'mir, 'tcx, Q> FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> where Q: Qualif, { - pub(super) fn new(_: Q, item: &'a Item<'mir, 'tcx>) -> Self { - FlowSensitiveAnalysis { item, _qualif: PhantomData } + pub(super) fn new(_: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self { + FlowSensitiveAnalysis { ccx, _qualif: PhantomData } } fn transfer_function( &self, state: &'a mut BitSet, ) -> TransferFunction<'a, 'mir, 'tcx, Q> { - TransferFunction::::new(self.item, state) + TransferFunction::::new(self.ccx, state) } } diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index 4cc42c0408f69..6985ef94c66a1 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -20,7 +20,7 @@ use std::ops::Deref; use super::ops::{self, NonConstOp}; use super::qualifs::{self, HasMutInterior, NeedsDrop}; use super::resolver::FlowSensitiveAnalysis; -use super::{is_lang_panic_fn, ConstKind, Item, Qualif}; +use super::{is_lang_panic_fn, ConstCx, ConstKind, Qualif}; use crate::const_eval::{is_const_fn, is_unstable_const_fn}; use crate::dataflow::MaybeMutBorrowedLocals; use crate::dataflow::{self, Analysis}; @@ -37,15 +37,15 @@ struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> { } impl QualifCursor<'a, 'mir, 'tcx, Q> { - pub fn new(q: Q, item: &'a Item<'mir, 'tcx>) -> Self { - let cursor = FlowSensitiveAnalysis::new(q, item) - .into_engine(item.tcx, &item.body, item.def_id) + pub fn new(q: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self { + let cursor = FlowSensitiveAnalysis::new(q, ccx) + .into_engine(ccx.tcx, &ccx.body, ccx.def_id) .iterate_to_fixpoint() - .into_results_cursor(*item.body); + .into_results_cursor(*ccx.body); - let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len()); - for (local, decl) in item.body.local_decls.iter_enumerated() { - if Q::in_any_value_of_ty(item, decl.ty) { + let mut in_any_value_of_ty = BitSet::new_empty(ccx.body.local_decls.len()); + for (local, decl) in ccx.body.local_decls.iter_enumerated() { + if Q::in_any_value_of_ty(ccx, decl.ty) { in_any_value_of_ty.insert(local); } } @@ -91,12 +91,12 @@ impl Qualifs<'a, 'mir, 'tcx> { || self.indirectly_mutable(local, location) } - fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs { + fn in_return_place(&mut self, ccx: &ConstCx<'_, 'tcx>) -> ConstQualifs { // Find the `Return` terminator if one exists. // // If no `Return` terminator exists, this MIR is divergent. Just return the conservative // qualifs for the return type. - let return_block = item + let return_block = ccx .body .basic_blocks() .iter_enumerated() @@ -107,11 +107,11 @@ impl Qualifs<'a, 'mir, 'tcx> { .map(|(bb, _)| bb); let return_block = match return_block { - None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()), + None => return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty()), Some(bb) => bb, }; - let return_loc = item.body.terminator_loc(return_block); + let return_loc = ccx.body.terminator_loc(return_block); ConstQualifs { needs_drop: self.needs_drop(RETURN_PLACE, return_loc), @@ -121,7 +121,7 @@ impl Qualifs<'a, 'mir, 'tcx> { } pub struct Validator<'a, 'mir, 'tcx> { - item: &'a Item<'mir, 'tcx>, + ccx: &'a ConstCx<'mir, 'tcx>, qualifs: Qualifs<'a, 'mir, 'tcx>, /// The span of the current statement. @@ -129,19 +129,19 @@ pub struct Validator<'a, 'mir, 'tcx> { } impl Deref for Validator<'_, 'mir, 'tcx> { - type Target = Item<'mir, 'tcx>; + type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { - &self.item + &self.ccx } } impl Validator<'a, 'mir, 'tcx> { - pub fn new(item: &'a Item<'mir, 'tcx>) -> Self { - let Item { tcx, body, def_id, param_env, .. } = *item; + pub fn new(ccx: &'a ConstCx<'mir, 'tcx>) -> Self { + let ConstCx { tcx, body, def_id, param_env, .. } = *ccx; - let needs_drop = QualifCursor::new(NeedsDrop, item); - let has_mut_interior = QualifCursor::new(HasMutInterior, item); + let needs_drop = QualifCursor::new(NeedsDrop, ccx); + let has_mut_interior = QualifCursor::new(HasMutInterior, ccx); // We can use `unsound_ignore_borrow_on_drop` here because custom drop impls are not // allowed in a const. @@ -156,11 +156,11 @@ impl Validator<'a, 'mir, 'tcx> { let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable }; - Validator { span: item.body.span, item, qualifs } + Validator { span: ccx.body.span, ccx, qualifs } } pub fn check_body(&mut self) { - let Item { tcx, body, def_id, const_kind, .. } = *self.item; + let ConstCx { tcx, body, def_id, const_kind, .. } = *self.ccx; let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn) && crate::const_eval::is_min_const_fn(tcx, def_id)) @@ -175,7 +175,7 @@ impl Validator<'a, 'mir, 'tcx> { } } - check_short_circuiting_in_const_local(self.item); + check_short_circuiting_in_const_local(self.ccx); if body.is_cfg_cyclic() { // We can't provide a good span for the error here, but this should be caught by the @@ -196,7 +196,7 @@ impl Validator<'a, 'mir, 'tcx> { } pub fn qualifs_in_return_place(&mut self) -> ConstQualifs { - self.qualifs.in_return_place(self.item) + self.qualifs.in_return_place(self.ccx) } /// Emits an error at the given `span` if an expression cannot be evaluated in the current @@ -345,7 +345,7 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> { | Rvalue::Ref(_, BorrowKind::Shallow, ref place) | Rvalue::AddressOf(Mutability::Not, ref place) => { let borrowed_place_has_mut_interior = qualifs::in_place::( - &self.item, + &self.ccx, &mut |local| self.qualifs.has_mut_interior(local, location), place.as_ref(), ); @@ -590,8 +590,8 @@ fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) .emit(); } -fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) { - let body = item.body; +fn check_short_circuiting_in_const_local(ccx: &ConstCx<'_, 'tcx>) { + let body = ccx.body; if body.control_flow_destroyed.is_empty() { return; @@ -600,12 +600,12 @@ fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) { let mut locals = body.vars_iter(); if let Some(local) = locals.next() { let span = body.local_decls[local].source_info.span; - let mut error = item.tcx.sess.struct_span_err( + let mut error = ccx.tcx.sess.struct_span_err( span, &format!( "new features like let bindings are not permitted in {}s \ which also use short circuiting operators", - item.const_kind(), + ccx.const_kind(), ), ); for (span, kind) in body.control_flow_destroyed.iter() { diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index 8db0b39a497a9..9419121e4464c 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -194,7 +194,7 @@ fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs { return Default::default(); } - let item = check_consts::Item { + let ccx = check_consts::ConstCx { body: body.unwrap_read_only(), tcx, def_id, @@ -202,7 +202,7 @@ fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs { param_env: tcx.param_env(def_id), }; - let mut validator = check_consts::validation::Validator::new(&item); + let mut validator = check_consts::validation::Validator::new(&ccx); validator.check_body(); // We return the qualifs in the return place for every MIR body, even though it is only used diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index 71c2e3bf06095..eda2f84effd05 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -30,7 +30,7 @@ use std::cell::Cell; use std::{cmp, iter, mem}; use crate::const_eval::{is_const_fn, is_unstable_const_fn}; -use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item}; +use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstCx, ConstKind}; use crate::transform::{MirPass, MirSource}; /// A `MirPass` for promotion. @@ -61,11 +61,15 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> { let def_id = src.def_id(); - let mut rpo = traversal::reverse_postorder(body); - let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo); + let read_only_body = read_only!(body); - let promotable_candidates = - validate_candidates(tcx, read_only!(body), def_id, &temps, &all_candidates); + let mut rpo = traversal::reverse_postorder(&read_only_body); + + let ccx = ConstCx::new(tcx, def_id, read_only_body); + + let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo); + + let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates); let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates); self.promoted_fragments.set(promoted); @@ -140,8 +144,7 @@ fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option> { } struct Collector<'a, 'tcx> { - tcx: TyCtxt<'tcx>, - body: &'a Body<'tcx>, + ccx: &'a ConstCx<'a, 'tcx>, temps: IndexVec, candidates: Vec, span: Span, @@ -151,7 +154,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) { debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location); // We're only interested in temporaries and the return place - match self.body.local_kind(index) { + match self.ccx.body.local_kind(index) { LocalKind::Temp | LocalKind::ReturnPointer => {} LocalKind::Arg | LocalKind::Var => return, } @@ -204,7 +207,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { Rvalue::Ref(..) => { self.candidates.push(Candidate::Ref(location)); } - Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => { + Rvalue::Repeat(..) if self.ccx.tcx.features().const_in_array_repeat_expressions => { // FIXME(#49147) only promote the element when it isn't `Copy` // (so that code that can copy it at runtime is unaffected). self.candidates.push(Candidate::Repeat(location)); @@ -217,10 +220,10 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { self.super_terminator_kind(kind, location); if let TerminatorKind::Call { ref func, .. } = *kind { - if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind { - let fn_sig = self.tcx.fn_sig(def_id); + if let ty::FnDef(def_id, _) = func.ty(*self.ccx.body, self.ccx.tcx).kind { + let fn_sig = self.ccx.tcx.fn_sig(def_id); if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() { - let name = self.tcx.item_name(def_id); + let name = self.ccx.tcx.item_name(def_id); // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles. if name.as_str().starts_with("simd_shuffle") { self.candidates.push(Candidate::Argument { bb: location.block, index: 2 }); @@ -229,7 +232,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { } } - if let Some(constant_args) = args_required_const(self.tcx, def_id) { + if let Some(constant_args) = args_required_const(self.ccx.tcx, def_id) { for index in constant_args { self.candidates.push(Candidate::Argument { bb: location.block, index }); } @@ -244,16 +247,14 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { } pub fn collect_temps_and_candidates( - tcx: TyCtxt<'tcx>, - body: &Body<'tcx>, + ccx: &ConstCx<'mir, 'tcx>, rpo: &mut ReversePostorder<'_, 'tcx>, ) -> (IndexVec, Vec) { let mut collector = Collector { - tcx, - body, - temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls), + temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls), candidates: vec![], - span: body.span, + span: ccx.body.span, + ccx, }; for (bb, data) in rpo { collector.visit_basic_block_data(bb, data); @@ -265,7 +266,7 @@ pub fn collect_temps_and_candidates( /// /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion. struct Validator<'a, 'tcx> { - item: Item<'a, 'tcx>, + ccx: &'a ConstCx<'a, 'tcx>, temps: &'a IndexVec, /// Explicit promotion happens e.g. for constant arguments declared via @@ -278,10 +279,10 @@ struct Validator<'a, 'tcx> { } impl std::ops::Deref for Validator<'a, 'tcx> { - type Target = Item<'a, 'tcx>; + type Target = ConstCx<'a, 'tcx>; fn deref(&self) -> &Self::Target { - &self.item + &self.ccx } } @@ -414,7 +415,7 @@ impl<'tcx> Validator<'_, 'tcx> { let statement = &self.body[loc.block].statements[loc.statement_index]; match &statement.kind { StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::( - &self.item, + &self.ccx, &mut |l| self.qualif_local::(l), rhs, ), @@ -431,7 +432,7 @@ impl<'tcx> Validator<'_, 'tcx> { match &terminator.kind { TerminatorKind::Call { .. } => { let return_ty = self.body.local_decls[local].ty; - Q::in_any_value_of_ty(&self.item, return_ty) + Q::in_any_value_of_ty(&self.ccx, return_ty) } kind => { span_bug!(terminator.source_info.span, "{:?} not promotable", kind); @@ -718,13 +719,11 @@ impl<'tcx> Validator<'_, 'tcx> { // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`. pub fn validate_candidates( - tcx: TyCtxt<'tcx>, - body: ReadOnlyBodyAndCache<'_, 'tcx>, - def_id: DefId, + ccx: &ConstCx<'_, '_>, temps: &IndexVec, candidates: &[Candidate], ) -> Vec { - let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false }; + let mut validator = Validator { ccx, temps, explicit: false }; candidates .iter() @@ -736,11 +735,23 @@ pub fn validate_candidates( // and `#[rustc_args_required_const]` arguments here. let is_promotable = validator.validate_candidate(candidate).is_ok(); + + // If we use explicit validation, we carry the risk of turning a legitimate run-time + // operation into a failing compile-time operation. Make sure that does not happen + // by asserting that there is no possible run-time behavior here in case promotion + // fails. + if validator.explicit && !is_promotable { + ccx.tcx.sess.delay_span_bug( + ccx.body.span, + "Explicit promotion requested, but failed to promote", + ); + } + match candidate { Candidate::Argument { bb, index } if !is_promotable => { - let span = body[bb].terminator().source_info.span; + let span = ccx.body[bb].terminator().source_info.span; let msg = format!("argument {} is required to be a constant", index + 1); - tcx.sess.span_err(span, &msg); + ccx.tcx.sess.span_err(span, &msg); } _ => (), } @@ -1148,22 +1159,19 @@ pub fn promote_candidates<'tcx>( /// Feature attribute should be suggested if `operand` can be promoted and the feature is not /// enabled. crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>( - tcx: TyCtxt<'tcx>, - mir_def_id: DefId, - body: ReadOnlyBodyAndCache<'_, 'tcx>, + ccx: &ConstCx<'_, 'tcx>, operand: &Operand<'tcx>, ) -> bool { - let mut rpo = traversal::reverse_postorder(&body); - let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo); - let validator = - Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false }; + let mut rpo = traversal::reverse_postorder(&ccx.body); + let (temps, _) = collect_temps_and_candidates(&ccx, &mut rpo); + let validator = Validator { ccx, temps: &temps, explicit: false }; let should_promote = validator.validate_operand(operand).is_ok(); - let feature_flag = tcx.features().const_in_array_repeat_expressions; + let feature_flag = validator.ccx.tcx.features().const_in_array_repeat_expressions; debug!( - "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \ + "should_suggest_const_in_array_repeat_expressions_flag: def_id={:?} \ should_promote={:?} feature_flag={:?}", - mir_def_id, should_promote, feature_flag + validator.ccx.def_id, should_promote, feature_flag ); should_promote && !feature_flag } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 61a7d8ee5c948..1dd5adb2209ef 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -3338,6 +3338,10 @@ impl<'test> TestCx<'test> { } fn delete_file(&self, file: &PathBuf) { + if !file.exists() { + // Deleting a nonexistant file would error. + return; + } if let Err(e) = fs::remove_file(file) { self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,)); } @@ -3400,7 +3404,7 @@ impl<'test> TestCx<'test> { let examined_content = self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new()); - if examined_path.exists() && canon_content == &examined_content { + if canon_content == &examined_content { self.delete_file(&examined_path); } }