2018-01-28 14:41:17 +01:00
|
|
|
//! Propagates constants for early reporting of statically known
|
|
|
|
//! assertion failures
|
|
|
|
|
2019-06-13 20:20:14 -04:00
|
|
|
use std::cell::Cell;
|
|
|
|
|
2020-04-27 23:26:11 +05:30
|
|
|
use rustc_ast::Mutability;
|
2020-06-26 11:02:43 +02:00
|
|
|
use rustc_data_structures::fx::FxHashSet;
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_hir::def::DefKind;
|
|
|
|
use rustc_hir::HirId;
|
2020-04-19 00:35:26 -04:00
|
|
|
use rustc_index::bit_set::BitSet;
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_index::vec::IndexVec;
|
|
|
|
use rustc_middle::mir::interpret::{InterpResult, Scalar};
|
|
|
|
use rustc_middle::mir::visit::{
|
2019-12-22 17:42:04 -05:00
|
|
|
MutVisitor, MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor,
|
|
|
|
};
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::mir::{
|
2020-08-14 18:01:14 +02:00
|
|
|
AssertKind, BasicBlock, BinOp, Body, ClearCrossCrate, Constant, Local, LocalDecl, LocalKind,
|
|
|
|
Location, Operand, Place, Rvalue, SourceInfo, SourceScope, SourceScopeData, Statement,
|
|
|
|
StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
|
2019-04-29 18:32:35 -04:00
|
|
|
};
|
2020-03-31 18:16:47 +02:00
|
|
|
use rustc_middle::ty::layout::{HasTyCtxt, LayoutError, TyAndLayout};
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::ty::subst::{InternalSubsts, Subst};
|
2020-06-19 18:57:15 +02:00
|
|
|
use rustc_middle::ty::{self, ConstInt, ConstKind, Instance, ParamEnv, Ty, TyCtxt, TypeFoldable};
|
2020-03-11 12:49:08 +01:00
|
|
|
use rustc_session::lint;
|
2020-03-21 19:19:10 +01:00
|
|
|
use rustc_span::{def_id::DefId, Span};
|
2020-03-31 18:16:47 +02:00
|
|
|
use rustc_target::abi::{HasDataLayout, LayoutOf, Size, TargetDataLayout};
|
2020-02-11 21:19:40 +01:00
|
|
|
use rustc_trait_selection::traits;
|
2018-01-28 14:41:17 +01:00
|
|
|
|
2020-08-09 15:37:32 +02:00
|
|
|
use crate::const_eval::ConstEvalErr;
|
2019-06-01 13:08:04 -05:00
|
|
|
use crate::interpret::{
|
2020-08-14 18:01:14 +02:00
|
|
|
self, compile_time_machine, truncate, AllocId, Allocation, ConstValue, Frame, ImmTy, Immediate,
|
|
|
|
InterpCx, LocalState, LocalValue, MemPlace, Memory, MemoryKind, OpTy, Operand as InterpOperand,
|
|
|
|
PlaceTy, Pointer, ScalarMaybeUninit, StackPopCleanup,
|
2018-11-06 16:16:27 +01:00
|
|
|
};
|
2019-02-08 06:28:15 +09:00
|
|
|
use crate::transform::{MirPass, MirSource};
|
2018-09-18 11:01:13 +02:00
|
|
|
|
2020-07-27 13:52:40 +02:00
|
|
|
/// The maximum number of bytes that we'll allocate space for a local or the return value.
|
|
|
|
/// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
|
|
|
|
/// Severely regress performance.
|
2019-11-13 19:19:25 -05:00
|
|
|
const MAX_ALLOC_LIMIT: u64 = 1024;
|
|
|
|
|
2020-03-23 10:58:43 +01:00
|
|
|
/// Macro for machine-specific `InterpError` without allocation.
|
|
|
|
/// (These will never be shown to the user, but they help diagnose ICEs.)
|
|
|
|
macro_rules! throw_machine_stop_str {
|
|
|
|
($($tt:tt)*) => {{
|
|
|
|
// We make a new local type for it. The type itself does not carry any information,
|
|
|
|
// but its vtable (for the `MachineStopType` trait) does.
|
|
|
|
struct Zst;
|
2020-04-30 11:03:55 +02:00
|
|
|
// Printing this type shows the desired string.
|
|
|
|
impl std::fmt::Display for Zst {
|
2020-03-23 10:58:43 +01:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, $($tt)*)
|
|
|
|
}
|
|
|
|
}
|
2020-03-29 16:41:09 +02:00
|
|
|
impl rustc_middle::mir::interpret::MachineStopType for Zst {}
|
2020-03-23 10:58:43 +01:00
|
|
|
throw_machine_stop!(Zst)
|
|
|
|
}};
|
|
|
|
}
|
|
|
|
|
2018-01-28 14:41:17 +01:00
|
|
|
pub struct ConstProp;
|
|
|
|
|
2019-08-04 16:20:00 -04:00
|
|
|
impl<'tcx> MirPass<'tcx> for ConstProp {
|
2020-04-12 10:31:00 -07:00
|
|
|
fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
|
2018-03-06 12:43:02 +01:00
|
|
|
// will be evaluated by miri and produce its errors there
|
|
|
|
if source.promoted.is_some() {
|
|
|
|
return;
|
|
|
|
}
|
2018-08-31 14:30:59 +02:00
|
|
|
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::hir::map::blocks::FnLikeNode;
|
2020-08-12 12:22:56 +02:00
|
|
|
let hir_id = tcx.hir().local_def_id_to_hir_id(source.def_id().expect_local());
|
2018-08-31 14:30:59 +02:00
|
|
|
|
2019-06-20 10:39:19 +02:00
|
|
|
let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
|
2020-04-17 21:55:17 +03:00
|
|
|
let is_assoc_const = tcx.def_kind(source.def_id()) == DefKind::AssocConst;
|
2018-08-31 14:30:59 +02:00
|
|
|
|
|
|
|
// Only run const prop on functions, methods, closures and associated constants
|
2019-12-22 17:42:04 -05:00
|
|
|
if !is_fn_like && !is_assoc_const {
|
2018-08-26 15:19:34 +02:00
|
|
|
// skip anon_const/statics/consts because they'll be evaluated by miri anyway
|
2019-02-03 11:51:07 +01:00
|
|
|
trace!("ConstProp skipped for {:?}", source.def_id());
|
2019-12-22 17:42:04 -05:00
|
|
|
return;
|
2018-03-06 12:43:02 +01:00
|
|
|
}
|
2018-08-31 14:30:59 +02:00
|
|
|
|
2019-09-12 22:03:20 -04:00
|
|
|
let is_generator = tcx.type_of(source.def_id()).is_generator();
|
|
|
|
// FIXME(welseywiser) const prop doesn't work on generators because of query cycles
|
|
|
|
// computing their layout.
|
|
|
|
if is_generator {
|
|
|
|
trace!("ConstProp skipped for generator {:?}", source.def_id());
|
2019-12-22 17:42:04 -05:00
|
|
|
return;
|
2019-09-12 22:03:20 -04:00
|
|
|
}
|
|
|
|
|
2020-01-07 10:53:04 -05:00
|
|
|
// Check if it's even possible to satisfy the 'where' clauses
|
2020-01-05 22:32:53 -05:00
|
|
|
// for this item.
|
|
|
|
// This branch will never be taken for any normal function.
|
|
|
|
// However, it's possible to `#!feature(trivial_bounds)]` to write
|
|
|
|
// a function with impossible to satisfy clauses, e.g.:
|
|
|
|
// `fn foo() where String: Copy {}`
|
|
|
|
//
|
|
|
|
// We don't usually need to worry about this kind of case,
|
|
|
|
// since we would get a compilation error if the user tried
|
|
|
|
// to call it. However, since we can do const propagation
|
|
|
|
// even without any calls to the function, we need to make
|
|
|
|
// sure that it even makes sense to try to evaluate the body.
|
|
|
|
// If there are unsatisfiable where clauses, then all bets are
|
|
|
|
// off, and we just give up.
|
2020-01-13 06:06:42 -05:00
|
|
|
//
|
2020-01-16 18:53:51 -05:00
|
|
|
// We manually filter the predicates, skipping anything that's not
|
|
|
|
// "global". We are in a potentially generic context
|
2020-01-17 08:13:04 -05:00
|
|
|
// (e.g. we are evaluating a function without substituting generic
|
2020-01-16 18:53:51 -05:00
|
|
|
// parameters, so this filtering serves two purposes:
|
2020-01-13 06:06:42 -05:00
|
|
|
//
|
2020-01-16 18:53:51 -05:00
|
|
|
// 1. We skip evaluating any predicates that we would
|
|
|
|
// never be able prove are unsatisfiable (e.g. `<T as Foo>`
|
|
|
|
// 2. We avoid trying to normalize predicates involving generic
|
|
|
|
// parameters (e.g. `<T as Foo>::MyItem`). This can confuse
|
|
|
|
// the normalization code (leading to cycle errors), since
|
|
|
|
// it's usually never invoked in this way.
|
|
|
|
let predicates = tcx
|
|
|
|
.predicates_of(source.def_id())
|
|
|
|
.predicates
|
|
|
|
.iter()
|
2020-04-17 18:31:25 -07:00
|
|
|
.filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
|
2020-06-22 13:22:45 +01:00
|
|
|
if traits::impossible_predicates(
|
2020-01-16 18:53:51 -05:00
|
|
|
tcx,
|
2020-03-03 15:07:04 -08:00
|
|
|
traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
|
2020-01-16 18:53:51 -05:00
|
|
|
) {
|
|
|
|
trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", source.def_id());
|
2020-01-05 22:32:53 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-02-03 11:51:07 +01:00
|
|
|
trace!("ConstProp starting for {:?}", source.def_id());
|
2018-01-28 14:41:17 +01:00
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
let dummy_body = &Body::new(
|
|
|
|
body.basic_blocks().clone(),
|
|
|
|
body.source_scopes.clone(),
|
|
|
|
body.local_decls.clone(),
|
|
|
|
Default::default(),
|
|
|
|
body.arg_count,
|
|
|
|
Default::default(),
|
|
|
|
tcx.def_span(source.def_id()),
|
|
|
|
body.generator_kind,
|
|
|
|
);
|
2019-06-13 20:20:14 -04:00
|
|
|
|
2018-01-29 15:12:45 +01:00
|
|
|
// FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
|
|
|
|
// constants, instead of just checking for const-folding succeeding.
|
|
|
|
// That would require an uniform one-def no-mutation analysis
|
|
|
|
// and RPO (or recursing when needing the value of a local).
|
2020-04-12 10:31:00 -07:00
|
|
|
let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx, source);
|
2019-06-03 18:26:48 -04:00
|
|
|
optimization_finder.visit_body(body);
|
2018-01-28 14:41:17 +01:00
|
|
|
|
2019-02-03 11:51:07 +01:00
|
|
|
trace!("ConstProp done for {:?}", source.def_id());
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-16 15:12:42 -07:00
|
|
|
struct ConstPropMachine<'mir, 'tcx> {
|
|
|
|
/// The virtual call stack.
|
|
|
|
stack: Vec<Frame<'mir, 'tcx, (), ()>>,
|
2020-06-26 11:02:43 +02:00
|
|
|
/// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
|
|
|
|
written_only_inside_own_block_locals: FxHashSet<Local>,
|
|
|
|
/// Locals that need to be cleared after every block terminates.
|
|
|
|
only_propagate_inside_block_locals: BitSet<Local>,
|
2020-07-27 15:01:25 +02:00
|
|
|
can_const_prop: IndexVec<Local, ConstPropMode>,
|
2020-03-16 15:12:42 -07:00
|
|
|
}
|
2019-09-24 21:12:59 -04:00
|
|
|
|
2020-03-16 15:12:42 -07:00
|
|
|
impl<'mir, 'tcx> ConstPropMachine<'mir, 'tcx> {
|
2020-07-27 15:01:25 +02:00
|
|
|
fn new(
|
|
|
|
only_propagate_inside_block_locals: BitSet<Local>,
|
|
|
|
can_const_prop: IndexVec<Local, ConstPropMode>,
|
|
|
|
) -> Self {
|
2020-06-26 11:02:43 +02:00
|
|
|
Self {
|
|
|
|
stack: Vec::new(),
|
|
|
|
written_only_inside_own_block_locals: Default::default(),
|
|
|
|
only_propagate_inside_block_locals,
|
2020-07-27 15:01:25 +02:00
|
|
|
can_const_prop,
|
2020-06-26 11:02:43 +02:00
|
|
|
}
|
2020-03-16 15:12:42 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
|
2020-04-27 19:01:30 +02:00
|
|
|
compile_time_machine!(<'mir, 'tcx>);
|
2019-09-24 21:12:59 -04:00
|
|
|
|
|
|
|
type MemoryExtra = ();
|
|
|
|
|
2019-11-30 17:53:02 +01:00
|
|
|
fn find_mir_or_eval_fn(
|
2019-09-24 21:12:59 -04:00
|
|
|
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
|
|
|
|
_instance: ty::Instance<'tcx>,
|
|
|
|
_args: &[OpTy<'tcx>],
|
2019-11-25 22:00:58 +01:00
|
|
|
_ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
|
2019-10-09 17:33:41 -04:00
|
|
|
_unwind: Option<BasicBlock>,
|
2019-09-24 21:12:59 -04:00
|
|
|
) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn call_intrinsic(
|
|
|
|
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
|
|
|
|
_instance: ty::Instance<'tcx>,
|
|
|
|
_args: &[OpTy<'tcx>],
|
2019-11-25 22:00:58 +01:00
|
|
|
_ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
|
2019-12-22 17:42:04 -05:00
|
|
|
_unwind: Option<BasicBlock>,
|
2019-09-24 21:12:59 -04:00
|
|
|
) -> InterpResult<'tcx> {
|
2020-03-23 10:58:43 +01:00
|
|
|
throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
|
2019-09-24 21:12:59 -04:00
|
|
|
}
|
|
|
|
|
2019-11-29 09:59:52 +01:00
|
|
|
fn assert_panic(
|
|
|
|
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
|
2020-03-29 16:41:09 +02:00
|
|
|
_msg: &rustc_middle::mir::AssertMessage<'tcx>,
|
|
|
|
_unwind: Option<rustc_middle::mir::BasicBlock>,
|
2019-11-29 09:59:52 +01:00
|
|
|
) -> InterpResult<'tcx> {
|
2020-03-19 09:07:43 +01:00
|
|
|
bug!("panics terminators are not evaluated in ConstProp")
|
2019-11-29 09:59:52 +01:00
|
|
|
}
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
|
2020-03-22 11:41:07 +01:00
|
|
|
throw_unsup!(ReadPointerAsBytes)
|
2019-09-24 21:12:59 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn binary_ptr_op(
|
|
|
|
_ecx: &InterpCx<'mir, 'tcx, Self>,
|
|
|
|
_bin_op: BinOp,
|
|
|
|
_left: ImmTy<'tcx>,
|
|
|
|
_right: ImmTy<'tcx>,
|
|
|
|
) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
|
|
|
|
// We can't do this because aliasing of memory can differ between const eval and llvm
|
2020-03-23 10:58:43 +01:00
|
|
|
throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
|
2019-09-24 21:12:59 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn box_alloc(
|
|
|
|
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
|
|
|
|
_dest: PlaceTy<'tcx>,
|
|
|
|
) -> InterpResult<'tcx> {
|
2020-03-23 10:58:43 +01:00
|
|
|
throw_machine_stop_str!("can't const prop heap allocations")
|
2019-09-24 21:12:59 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn access_local(
|
|
|
|
_ecx: &InterpCx<'mir, 'tcx, Self>,
|
|
|
|
frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
|
|
|
|
local: Local,
|
|
|
|
) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
|
|
|
|
let l = &frame.locals[local];
|
|
|
|
|
|
|
|
if l.value == LocalValue::Uninitialized {
|
2020-03-23 10:58:43 +01:00
|
|
|
throw_machine_stop_str!("tried to access an uninitialized local")
|
2019-09-24 21:12:59 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
l.access()
|
|
|
|
}
|
|
|
|
|
2020-06-26 11:02:43 +02:00
|
|
|
fn access_local_mut<'a>(
|
|
|
|
ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
|
|
|
|
frame: usize,
|
|
|
|
local: Local,
|
|
|
|
) -> InterpResult<'tcx, Result<&'a mut LocalValue<Self::PointerTag>, MemPlace<Self::PointerTag>>>
|
|
|
|
{
|
2020-07-27 15:01:25 +02:00
|
|
|
if ecx.machine.can_const_prop[local] == ConstPropMode::NoPropagation {
|
|
|
|
throw_machine_stop_str!("tried to write to a local that is marked as not propagatable")
|
|
|
|
}
|
2020-06-26 11:02:43 +02:00
|
|
|
if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
|
2020-05-17 15:39:35 +02:00
|
|
|
trace!(
|
|
|
|
"mutating local {:?} which is restricted to its block. \
|
|
|
|
Will remove it from const-prop after block is finished.",
|
|
|
|
local
|
|
|
|
);
|
2020-06-26 11:02:43 +02:00
|
|
|
ecx.machine.written_only_inside_own_block_locals.insert(local);
|
|
|
|
}
|
|
|
|
ecx.machine.stack[frame].locals[local].access_mut()
|
|
|
|
}
|
|
|
|
|
2020-03-21 19:19:10 +01:00
|
|
|
fn before_access_global(
|
2019-12-16 15:23:42 +01:00
|
|
|
_memory_extra: &(),
|
2020-03-21 20:44:39 +01:00
|
|
|
_alloc_id: AllocId,
|
2019-09-24 22:08:22 -04:00
|
|
|
allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
|
2020-03-31 15:25:12 +02:00
|
|
|
_static_def_id: Option<DefId>,
|
2020-03-21 19:19:10 +01:00
|
|
|
is_write: bool,
|
2019-09-24 21:12:59 -04:00
|
|
|
) -> InterpResult<'tcx> {
|
2020-03-21 19:19:10 +01:00
|
|
|
if is_write {
|
|
|
|
throw_machine_stop_str!("can't write to global");
|
|
|
|
}
|
2020-03-31 15:25:12 +02:00
|
|
|
// If the static allocation is mutable, then we can't const prop it as its content
|
|
|
|
// might be different at runtime.
|
2020-03-24 14:31:55 +01:00
|
|
|
if allocation.mutability == Mutability::Mut {
|
2020-03-31 15:25:12 +02:00
|
|
|
throw_machine_stop_str!("can't access mutable globals in ConstProp");
|
2019-09-24 22:08:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
2019-09-24 21:12:59 -04:00
|
|
|
}
|
|
|
|
|
2020-08-12 10:18:21 +02:00
|
|
|
#[inline(always)]
|
|
|
|
fn init_frame_extra(
|
|
|
|
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
|
|
|
|
frame: Frame<'mir, 'tcx>,
|
|
|
|
) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
|
|
|
|
Ok(frame)
|
|
|
|
}
|
|
|
|
|
2020-04-16 09:57:12 -07:00
|
|
|
#[inline(always)]
|
|
|
|
fn stack(
|
|
|
|
ecx: &'a InterpCx<'mir, 'tcx, Self>,
|
|
|
|
) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
|
|
|
|
&ecx.machine.stack
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline(always)]
|
|
|
|
fn stack_mut(
|
|
|
|
ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
|
|
|
|
) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
|
|
|
|
&mut ecx.machine.stack
|
|
|
|
}
|
2019-09-24 21:12:59 -04:00
|
|
|
}
|
|
|
|
|
2018-01-28 14:41:17 +01:00
|
|
|
/// Finds optimization opportunities on the MIR.
|
2019-06-11 22:03:44 +03:00
|
|
|
struct ConstPropagator<'mir, 'tcx> {
|
2020-03-16 15:12:42 -07:00
|
|
|
ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
|
2019-06-14 00:48:52 +03:00
|
|
|
tcx: TyCtxt<'tcx>,
|
2018-01-31 09:31:24 +01:00
|
|
|
param_env: ParamEnv<'tcx>,
|
2019-11-26 19:55:03 +02:00
|
|
|
// FIXME(eddyb) avoid cloning these two fields more than once,
|
|
|
|
// by accessing them through `ecx` instead.
|
2019-11-26 22:17:35 +02:00
|
|
|
source_scopes: IndexVec<SourceScope, SourceScopeData>,
|
2019-04-29 18:32:35 -04:00
|
|
|
local_decls: IndexVec<Local, LocalDecl<'tcx>>,
|
2019-12-29 00:26:25 +01:00
|
|
|
// Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
|
|
|
|
// the last known `SourceInfo` here and just keep revisiting it.
|
|
|
|
source_info: Option<SourceInfo>,
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
|
2019-06-11 22:03:44 +03:00
|
|
|
impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
|
2019-04-26 14:26:49 +02:00
|
|
|
type Ty = Ty<'tcx>;
|
2020-03-04 14:50:21 +00:00
|
|
|
type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
|
2018-03-06 12:43:02 +01:00
|
|
|
|
2020-03-04 14:50:21 +00:00
|
|
|
fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
|
2018-03-06 12:43:02 +01:00
|
|
|
self.tcx.layout_of(self.param_env.and(ty))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-11 22:03:44 +03:00
|
|
|
impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
|
2018-03-06 12:43:02 +01:00
|
|
|
#[inline]
|
|
|
|
fn data_layout(&self) -> &TargetDataLayout {
|
|
|
|
&self.tcx.data_layout
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-11 22:03:44 +03:00
|
|
|
impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
|
2018-03-06 12:43:02 +01:00
|
|
|
#[inline]
|
2019-06-14 00:48:52 +03:00
|
|
|
fn tcx(&self) -> TyCtxt<'tcx> {
|
2018-03-06 12:43:02 +01:00
|
|
|
self.tcx
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-11 22:03:44 +03:00
|
|
|
impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
|
2018-01-28 14:41:17 +01:00
|
|
|
fn new(
|
2020-04-12 10:31:00 -07:00
|
|
|
body: &Body<'tcx>,
|
2019-06-13 20:20:14 -04:00
|
|
|
dummy_body: &'mir Body<'tcx>,
|
2019-06-14 00:48:52 +03:00
|
|
|
tcx: TyCtxt<'tcx>,
|
2019-02-03 11:51:07 +01:00
|
|
|
source: MirSource<'tcx>,
|
2019-06-11 22:03:44 +03:00
|
|
|
) -> ConstPropagator<'mir, 'tcx> {
|
2019-06-13 20:20:14 -04:00
|
|
|
let def_id = source.def_id();
|
2019-12-27 11:44:36 -05:00
|
|
|
let substs = &InternalSubsts::identity_for_item(tcx, def_id);
|
2020-04-11 00:50:02 -04:00
|
|
|
let param_env = tcx.param_env_reveal_all_normalized(def_id);
|
2019-12-27 11:44:36 -05:00
|
|
|
|
2019-06-13 20:20:14 -04:00
|
|
|
let span = tcx.def_span(def_id);
|
2020-07-27 13:52:40 +02:00
|
|
|
// FIXME: `CanConstProp::check` computes the layout of all locals, return those layouts
|
|
|
|
// so we can write them to `ecx.frame_mut().locals.layout, reducing the duplication in
|
|
|
|
// `layout_of` query invocations.
|
|
|
|
let can_const_prop = CanConstProp::check(tcx, param_env, body);
|
2020-06-26 11:02:43 +02:00
|
|
|
let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
|
|
|
|
for (l, mode) in can_const_prop.iter_enumerated() {
|
|
|
|
if *mode == ConstPropMode::OnlyInsideOwnBlock {
|
|
|
|
only_propagate_inside_block_locals.insert(l);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let mut ecx = InterpCx::new(
|
|
|
|
tcx,
|
|
|
|
span,
|
|
|
|
param_env,
|
2020-07-27 15:01:25 +02:00
|
|
|
ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
|
2020-06-26 11:02:43 +02:00
|
|
|
(),
|
|
|
|
);
|
2019-06-13 20:20:14 -04:00
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
let ret = ecx
|
|
|
|
.layout_of(body.return_ty().subst(tcx, substs))
|
|
|
|
.ok()
|
|
|
|
// Don't bother allocating memory for ZST types which have no values
|
|
|
|
// or for large values.
|
|
|
|
.filter(|ret_layout| {
|
|
|
|
!ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
|
|
|
|
})
|
|
|
|
.map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
|
2019-11-07 19:13:03 -05:00
|
|
|
|
2019-06-13 20:20:14 -04:00
|
|
|
ecx.push_stack_frame(
|
2019-11-07 19:13:03 -05:00
|
|
|
Instance::new(def_id, substs),
|
2019-06-13 20:20:14 -04:00
|
|
|
dummy_body,
|
2019-11-07 19:13:03 -05:00
|
|
|
ret.map(Into::into),
|
2019-12-22 17:42:04 -05:00
|
|
|
StackPopCleanup::None { cleanup: false },
|
|
|
|
)
|
|
|
|
.expect("failed to push initial stack frame");
|
2019-04-29 18:32:35 -04:00
|
|
|
|
2018-01-30 14:12:16 +01:00
|
|
|
ConstPropagator {
|
2018-04-26 09:18:19 +02:00
|
|
|
ecx,
|
2018-01-28 14:41:17 +01:00
|
|
|
tcx,
|
2018-01-31 09:31:24 +01:00
|
|
|
param_env,
|
2019-11-26 19:55:03 +02:00
|
|
|
// FIXME(eddyb) avoid cloning these two fields more than once,
|
|
|
|
// by accessing them through `ecx` instead.
|
2019-11-26 22:17:35 +02:00
|
|
|
source_scopes: body.source_scopes.clone(),
|
2019-05-17 23:55:04 +02:00
|
|
|
//FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
|
2019-06-03 18:26:48 -04:00
|
|
|
local_decls: body.local_decls.clone(),
|
2019-12-29 00:26:25 +01:00
|
|
|
source_info: None,
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-06 19:28:48 +02:00
|
|
|
fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
|
2020-06-25 19:08:06 +02:00
|
|
|
let op = match self.ecx.eval_place_to_op(place, None) {
|
|
|
|
Ok(op) => op,
|
|
|
|
Err(e) => {
|
|
|
|
trace!("get_const failed: {}", e);
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
};
|
2019-11-07 19:13:03 -05:00
|
|
|
|
2020-04-19 14:25:07 +02:00
|
|
|
// Try to read the local as an immediate so that if it is representable as a scalar, we can
|
|
|
|
// handle it as such, but otherwise, just return the value as is.
|
2020-06-25 19:08:06 +02:00
|
|
|
Some(match self.ecx.try_read_immediate(op) {
|
|
|
|
Ok(Ok(imm)) => imm.into(),
|
2020-04-19 14:25:07 +02:00
|
|
|
_ => op,
|
2020-06-25 19:08:06 +02:00
|
|
|
})
|
2019-06-12 21:06:07 -04:00
|
|
|
}
|
|
|
|
|
2020-04-23 12:25:28 -04:00
|
|
|
/// Remove `local` from the pool of `Locals`. Allows writing to them,
|
|
|
|
/// but not reading from them anymore.
|
|
|
|
fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
|
|
|
|
ecx.frame_mut().locals[local] =
|
2019-12-22 17:42:04 -05:00
|
|
|
LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
|
2019-06-12 21:06:07 -04:00
|
|
|
}
|
|
|
|
|
2019-12-29 00:26:25 +01:00
|
|
|
fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
|
|
|
|
match &self.source_scopes[source_info.scope].local_data {
|
|
|
|
ClearCrossCrate::Set(data) => Some(data.lint_root),
|
|
|
|
ClearCrossCrate::Clear => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-08 22:21:20 +01:00
|
|
|
fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
|
2018-04-26 09:18:19 +02:00
|
|
|
where
|
2019-06-07 18:56:27 +02:00
|
|
|
F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
|
2018-04-26 09:18:19 +02:00
|
|
|
{
|
2020-03-22 00:20:58 +01:00
|
|
|
match f(self) {
|
2018-04-26 09:18:19 +02:00
|
|
|
Ok(val) => Some(val),
|
2018-07-25 13:05:05 +02:00
|
|
|
Err(error) => {
|
2020-05-17 15:39:35 +02:00
|
|
|
trace!("InterpCx operation failed: {:?}", error);
|
2020-03-04 08:40:13 +01:00
|
|
|
// Some errors shouldn't come up because creating them causes
|
|
|
|
// an allocation, which we should avoid. When that happens,
|
|
|
|
// dedicated error variants should be introduced instead.
|
2020-03-10 09:22:16 +01:00
|
|
|
assert!(
|
2020-03-04 08:40:13 +01:00
|
|
|
!error.kind.allocates(),
|
|
|
|
"const-prop encountered allocating error: {}",
|
|
|
|
error
|
|
|
|
);
|
2018-04-26 09:18:19 +02:00
|
|
|
None
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2020-03-22 00:20:58 +01:00
|
|
|
}
|
2018-04-26 09:18:19 +02:00
|
|
|
}
|
|
|
|
|
2020-04-22 22:43:52 -04:00
|
|
|
/// Returns the value, if any, of evaluating `c`.
|
2020-01-18 18:44:22 -05:00
|
|
|
fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
|
2019-11-22 17:26:09 -03:00
|
|
|
// FIXME we need to revisit this for #67176
|
|
|
|
if c.needs_subst() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2020-07-27 13:01:01 +02:00
|
|
|
match self.ecx.const_to_op(c.literal, None) {
|
2019-12-22 17:42:04 -05:00
|
|
|
Ok(op) => Some(op),
|
2018-07-22 01:01:07 +02:00
|
|
|
Err(error) => {
|
2020-06-01 10:15:17 +02:00
|
|
|
let tcx = self.ecx.tcx.at(c.span);
|
2020-08-09 15:37:32 +02:00
|
|
|
let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
|
2020-01-08 21:31:08 +01:00
|
|
|
if let Some(lint_root) = self.lint_root(source_info) {
|
|
|
|
let lint_only = match c.literal.val {
|
|
|
|
// Promoteds must lint and not error as the user didn't ask for them
|
|
|
|
ConstKind::Unevaluated(_, _, Some(_)) => true,
|
|
|
|
// Out of backwards compatibility we cannot report hard errors in unused
|
|
|
|
// generic functions using associated constants of the generic parameters.
|
|
|
|
_ => c.literal.needs_subst(),
|
|
|
|
};
|
|
|
|
if lint_only {
|
2019-12-29 00:26:25 +01:00
|
|
|
// Out of backwards compatibility we cannot report hard errors in unused
|
|
|
|
// generic functions using associated constants of the generic parameters.
|
2020-06-01 11:17:38 +02:00
|
|
|
err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
|
2020-01-08 21:31:08 +01:00
|
|
|
} else {
|
2020-06-01 10:15:17 +02:00
|
|
|
err.report_as_error(tcx, "erroneous constant used");
|
2019-12-29 00:26:25 +01:00
|
|
|
}
|
2020-01-08 21:31:08 +01:00
|
|
|
} else {
|
2020-06-01 10:15:17 +02:00
|
|
|
err.report_as_error(tcx, "erroneous constant used");
|
2019-12-29 00:26:25 +01:00
|
|
|
}
|
2018-07-22 01:01:07 +02:00
|
|
|
None
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-22 22:43:52 -04:00
|
|
|
/// Returns the value, if any, of evaluating `place`.
|
2020-03-31 12:19:29 -03:00
|
|
|
fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
|
2019-05-25 10:59:05 -04:00
|
|
|
trace!("eval_place(place={:?})", place);
|
2020-02-08 22:21:20 +01:00
|
|
|
self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
|
2018-03-06 12:43:02 +01:00
|
|
|
}
|
|
|
|
|
2020-04-22 22:43:52 -04:00
|
|
|
/// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
|
|
|
|
/// or `eval_place`, depending on the variant of `Operand` used.
|
2020-01-18 18:44:05 -05:00
|
|
|
fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
|
2018-01-28 14:41:17 +01:00
|
|
|
match *op {
|
2020-01-01 12:35:50 -03:00
|
|
|
Operand::Constant(ref c) => self.eval_constant(c, source_info),
|
2020-03-31 12:19:29 -03:00
|
|
|
Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-14 22:49:01 +01:00
|
|
|
fn report_assert_as_lint(
|
|
|
|
&self,
|
|
|
|
lint: &'static lint::Lint,
|
|
|
|
source_info: SourceInfo,
|
2020-02-15 15:42:13 +01:00
|
|
|
message: &'static str,
|
2020-07-10 19:00:38 +02:00
|
|
|
panic: AssertKind<impl std::fmt::Debug>,
|
2020-02-14 22:49:01 +01:00
|
|
|
) -> Option<()> {
|
2020-02-08 22:21:20 +01:00
|
|
|
let lint_root = self.lint_root(source_info)?;
|
2020-02-14 22:49:01 +01:00
|
|
|
self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
|
|
|
|
let mut err = lint.build(message);
|
|
|
|
err.span_label(source_info.span, format!("{:?}", panic));
|
|
|
|
err.emit()
|
|
|
|
});
|
2020-03-20 15:03:11 +01:00
|
|
|
None
|
2020-02-08 22:21:20 +01:00
|
|
|
}
|
|
|
|
|
2020-02-09 15:48:18 +01:00
|
|
|
fn check_unary_op(
|
|
|
|
&mut self,
|
|
|
|
op: UnOp,
|
|
|
|
arg: &Operand<'tcx>,
|
|
|
|
source_info: SourceInfo,
|
|
|
|
) -> Option<()> {
|
2020-06-19 18:57:15 +02:00
|
|
|
if let (val, true) = self.use_ecx(|this| {
|
2020-02-09 15:48:18 +01:00
|
|
|
let val = this.ecx.read_immediate(this.ecx.eval_operand(arg, None)?)?;
|
|
|
|
let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, val)?;
|
2020-06-19 18:57:15 +02:00
|
|
|
Ok((val, overflow))
|
2020-02-08 22:21:20 +01:00
|
|
|
})? {
|
2020-02-13 11:26:09 +01:00
|
|
|
// `AssertKind` only has an `OverflowNeg` variant, so make sure that is
|
2020-02-10 15:58:10 +01:00
|
|
|
// appropriate to use.
|
2020-02-08 22:21:20 +01:00
|
|
|
assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
|
2020-02-14 22:49:01 +01:00
|
|
|
self.report_assert_as_lint(
|
2020-02-18 22:49:47 +01:00
|
|
|
lint::builtin::ARITHMETIC_OVERFLOW,
|
2020-02-14 22:49:01 +01:00
|
|
|
source_info,
|
|
|
|
"this arithmetic operation will overflow",
|
2020-06-19 18:57:15 +02:00
|
|
|
AssertKind::OverflowNeg(val.to_const_int()),
|
2020-02-14 22:49:01 +01:00
|
|
|
)?;
|
2020-02-08 22:21:20 +01:00
|
|
|
}
|
2019-12-28 16:43:39 -05:00
|
|
|
|
|
|
|
Some(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_binary_op(
|
|
|
|
&mut self,
|
|
|
|
op: BinOp,
|
|
|
|
left: &Operand<'tcx>,
|
|
|
|
right: &Operand<'tcx>,
|
|
|
|
source_info: SourceInfo,
|
|
|
|
) -> Option<()> {
|
2020-07-19 00:43:51 +02:00
|
|
|
let r = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(right, None)?));
|
2020-06-19 18:57:15 +02:00
|
|
|
let l = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(left, None)?));
|
2020-02-10 15:58:10 +01:00
|
|
|
// Check for exceeding shifts *even if* we cannot evaluate the LHS.
|
2019-12-28 16:43:39 -05:00
|
|
|
if op == BinOp::Shr || op == BinOp::Shl {
|
2020-07-19 00:43:51 +02:00
|
|
|
let r = r?;
|
2020-02-15 11:43:54 +01:00
|
|
|
// We need the type of the LHS. We cannot use `place_layout` as that is the type
|
|
|
|
// of the result, which for checked binops is not the same!
|
|
|
|
let left_ty = left.ty(&self.local_decls, self.tcx);
|
2020-06-19 18:57:15 +02:00
|
|
|
let left_size = self.ecx.layout_of(left_ty).ok()?.size;
|
2019-12-28 16:43:39 -05:00
|
|
|
let right_size = r.layout.size;
|
2020-02-28 11:04:12 +01:00
|
|
|
let r_bits = r.to_scalar().ok();
|
|
|
|
// This is basically `force_bits`.
|
|
|
|
let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
|
2020-06-19 18:57:15 +02:00
|
|
|
if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
|
2020-06-11 13:48:46 -04:00
|
|
|
debug!("check_binary_op: reporting assert for {:?}", source_info);
|
2020-02-14 22:49:01 +01:00
|
|
|
self.report_assert_as_lint(
|
2020-02-18 22:49:47 +01:00
|
|
|
lint::builtin::ARITHMETIC_OVERFLOW,
|
2020-02-14 22:49:01 +01:00
|
|
|
source_info,
|
|
|
|
"this arithmetic operation will overflow",
|
2020-06-19 18:57:15 +02:00
|
|
|
AssertKind::Overflow(
|
|
|
|
op,
|
|
|
|
match l {
|
|
|
|
Some(l) => l.to_const_int(),
|
|
|
|
// Invent a dummy value, the diagnostic ignores it anyway
|
|
|
|
None => ConstInt::new(
|
|
|
|
1,
|
|
|
|
left_size,
|
|
|
|
left_ty.is_signed(),
|
|
|
|
left_ty.is_ptr_sized_integral(),
|
|
|
|
),
|
|
|
|
},
|
|
|
|
r.to_const_int(),
|
|
|
|
),
|
2020-02-14 22:49:01 +01:00
|
|
|
)?;
|
2019-12-28 16:43:39 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-19 00:43:51 +02:00
|
|
|
if let (Some(l), Some(r)) = (l, r) {
|
|
|
|
// The remaining operators are handled through `overflowing_binary_op`.
|
|
|
|
if self.use_ecx(|this| {
|
|
|
|
let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
|
|
|
|
Ok(overflow)
|
|
|
|
})? {
|
|
|
|
self.report_assert_as_lint(
|
|
|
|
lint::builtin::ARITHMETIC_OVERFLOW,
|
|
|
|
source_info,
|
|
|
|
"this arithmetic operation will overflow",
|
|
|
|
AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
|
|
|
|
)?;
|
|
|
|
}
|
2019-12-28 16:43:39 -05:00
|
|
|
}
|
|
|
|
Some(())
|
|
|
|
}
|
|
|
|
|
2020-07-23 17:58:54 +02:00
|
|
|
fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
|
2020-07-22 10:29:37 +02:00
|
|
|
match *operand {
|
|
|
|
Operand::Copy(l) | Operand::Move(l) => {
|
|
|
|
if let Some(value) = self.get_const(l) {
|
|
|
|
if self.should_const_prop(value) {
|
|
|
|
// FIXME(felix91gr): this code only handles `Scalar` cases.
|
|
|
|
// For now, we're not handling `ScalarPair` cases because
|
|
|
|
// doing so here would require a lot of code duplication.
|
|
|
|
// We should hopefully generalize `Operand` handling into a fn,
|
|
|
|
// and use it to do const-prop here and everywhere else
|
|
|
|
// where it makes sense.
|
|
|
|
if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
|
|
|
|
ScalarMaybeUninit::Scalar(scalar),
|
|
|
|
)) = *value
|
|
|
|
{
|
|
|
|
*operand = self.operand_from_scalar(
|
|
|
|
scalar,
|
|
|
|
value.layout.ty,
|
|
|
|
self.source_info.unwrap().span,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-07-23 17:58:54 +02:00
|
|
|
Operand::Constant(_) => (),
|
2020-07-22 10:29:37 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-28 14:41:17 +01:00
|
|
|
fn const_prop(
|
|
|
|
&mut self,
|
|
|
|
rvalue: &Rvalue<'tcx>,
|
2018-01-29 15:12:45 +01:00
|
|
|
source_info: SourceInfo,
|
2020-03-31 12:19:29 -03:00
|
|
|
place: Place<'tcx>,
|
2019-10-12 08:21:51 -04:00
|
|
|
) -> Option<()> {
|
2019-10-13 13:48:26 -04:00
|
|
|
// Perform any special handling for specific Rvalue types.
|
|
|
|
// Generally, checks here fall into one of two categories:
|
|
|
|
// 1. Additional checking to provide useful lints to the user
|
|
|
|
// - In this case, we will do some validation and then fall through to the
|
|
|
|
// end of the function which evals the assignment.
|
|
|
|
// 2. Working around bugs in other parts of the compiler
|
|
|
|
// - In this case, we'll return `None` from this function to stop evaluation.
|
2019-09-15 12:08:09 -04:00
|
|
|
match rvalue {
|
2020-02-10 15:58:10 +01:00
|
|
|
// Additional checking: give lints to the user if an overflow would occur.
|
2020-02-14 22:49:01 +01:00
|
|
|
// We do this here and not in the `Assert` terminator as that terminator is
|
|
|
|
// only sometimes emitted (overflow checks can be disabled), but we want to always
|
|
|
|
// lint.
|
|
|
|
Rvalue::UnaryOp(op, arg) => {
|
2020-02-09 15:48:18 +01:00
|
|
|
trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
|
|
|
|
self.check_unary_op(*op, arg, source_info)?;
|
2019-09-14 07:00:16 -04:00
|
|
|
}
|
2020-02-14 22:49:01 +01:00
|
|
|
Rvalue::BinaryOp(op, left, right) => {
|
2019-09-15 12:08:09 -04:00
|
|
|
trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
|
2020-02-15 11:43:54 +01:00
|
|
|
self.check_binary_op(*op, left, right, source_info)?;
|
2019-09-15 12:08:09 -04:00
|
|
|
}
|
2020-02-14 22:49:01 +01:00
|
|
|
Rvalue::CheckedBinaryOp(op, left, right) => {
|
|
|
|
trace!(
|
|
|
|
"checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
|
|
|
|
op,
|
|
|
|
left,
|
|
|
|
right
|
|
|
|
);
|
2020-02-15 11:43:54 +01:00
|
|
|
self.check_binary_op(*op, left, right, source_info)?;
|
2019-09-15 12:08:09 -04:00
|
|
|
}
|
2019-09-09 22:28:02 -04:00
|
|
|
|
2020-01-12 21:19:44 -05:00
|
|
|
// Do not try creating references (#67862)
|
2020-06-22 14:03:18 +02:00
|
|
|
Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
|
|
|
|
trace!("skipping AddressOf | Ref for {:?}", place);
|
|
|
|
|
|
|
|
// This may be creating mutable references or immutable references to cells.
|
|
|
|
// If that happens, the pointed to value could be mutated via that reference.
|
|
|
|
// Since we aren't tracking references, the const propagator loses track of what
|
|
|
|
// value the local has right now.
|
|
|
|
// Thus, all locals that have their reference taken
|
|
|
|
// must not take part in propagation.
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
2019-10-20 16:09:36 -04:00
|
|
|
|
2020-01-12 21:19:44 -05:00
|
|
|
return None;
|
2019-09-14 07:00:16 -04:00
|
|
|
}
|
2020-06-24 08:49:09 -04:00
|
|
|
Rvalue::ThreadLocalRef(def_id) => {
|
|
|
|
trace!("skipping ThreadLocalRef({:?})", def_id);
|
2019-09-15 12:08:09 -04:00
|
|
|
|
2020-06-24 08:49:09 -04:00
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
// There's no other checking to do at this time.
|
|
|
|
Rvalue::Aggregate(..)
|
|
|
|
| Rvalue::Use(..)
|
|
|
|
| Rvalue::Repeat(..)
|
|
|
|
| Rvalue::Len(..)
|
|
|
|
| Rvalue::Cast(..)
|
|
|
|
| Rvalue::Discriminant(..)
|
|
|
|
| Rvalue::NullaryOp(..) => {}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2019-09-14 07:00:16 -04:00
|
|
|
|
2020-04-29 19:35:45 +10:00
|
|
|
// FIXME we need to revisit this for #67176
|
|
|
|
if rvalue.needs_subst() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2020-07-19 00:43:51 +02:00
|
|
|
if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
|
|
|
|
self.eval_rvalue_with_identities(rvalue, place)
|
|
|
|
} else {
|
|
|
|
self.use_ecx(|this| this.ecx.eval_rvalue_into_place(rvalue, place))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Attempt to use albegraic identities to eliminate constant expressions
|
|
|
|
fn eval_rvalue_with_identities(
|
|
|
|
&mut self,
|
|
|
|
rvalue: &Rvalue<'tcx>,
|
|
|
|
place: Place<'tcx>,
|
|
|
|
) -> Option<()> {
|
2020-02-08 22:21:20 +01:00
|
|
|
self.use_ecx(|this| {
|
2020-07-19 00:43:51 +02:00
|
|
|
match rvalue {
|
|
|
|
Rvalue::BinaryOp(op, left, right) | Rvalue::CheckedBinaryOp(op, left, right) => {
|
|
|
|
let l = this.ecx.eval_operand(left, None);
|
|
|
|
let r = this.ecx.eval_operand(right, None);
|
|
|
|
|
|
|
|
let const_arg = match (l, r) {
|
|
|
|
(Ok(x), Err(_)) | (Err(_), Ok(x)) => this.ecx.read_immediate(x)?,
|
|
|
|
(Err(e), Err(_)) => return Err(e),
|
|
|
|
(Ok(_), Ok(_)) => {
|
|
|
|
this.ecx.eval_rvalue_into_place(rvalue, place)?;
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let arg_value =
|
|
|
|
this.ecx.force_bits(const_arg.to_scalar()?, const_arg.layout.size)?;
|
|
|
|
let dest = this.ecx.eval_place(place)?;
|
|
|
|
|
|
|
|
match op {
|
|
|
|
BinOp::BitAnd => {
|
|
|
|
if arg_value == 0 {
|
|
|
|
this.ecx.write_immediate(*const_arg, dest)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
BinOp::BitOr => {
|
|
|
|
if arg_value == truncate(u128::MAX, const_arg.layout.size)
|
|
|
|
|| (const_arg.layout.ty.is_bool() && arg_value == 1)
|
|
|
|
{
|
|
|
|
this.ecx.write_immediate(*const_arg, dest)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
BinOp::Mul => {
|
|
|
|
if const_arg.layout.ty.is_integral() && arg_value == 0 {
|
|
|
|
if let Rvalue::CheckedBinaryOp(_, _, _) = rvalue {
|
|
|
|
let val = Immediate::ScalarPair(
|
|
|
|
const_arg.to_scalar()?.into(),
|
|
|
|
Scalar::from_bool(false).into(),
|
|
|
|
);
|
|
|
|
this.ecx.write_immediate(val, dest)?;
|
|
|
|
} else {
|
|
|
|
this.ecx.write_immediate(*const_arg, dest)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
this.ecx.eval_rvalue_into_place(rvalue, place)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
this.ecx.eval_rvalue_into_place(rvalue, place)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-12 08:21:51 -04:00
|
|
|
Ok(())
|
2019-09-14 07:00:16 -04:00
|
|
|
})
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2019-04-28 21:58:40 -04:00
|
|
|
|
2020-04-22 22:43:52 -04:00
|
|
|
/// Creates a new `Operand::Constant` from a `Scalar` value
|
2019-04-28 21:58:40 -04:00
|
|
|
fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
|
2019-12-22 17:42:04 -05:00
|
|
|
Operand::Constant(Box::new(Constant {
|
|
|
|
span,
|
|
|
|
user_ty: None,
|
2020-05-28 23:59:54 +02:00
|
|
|
literal: ty::Const::from_scalar(self.tcx, scalar, ty),
|
2019-12-22 17:42:04 -05:00
|
|
|
}))
|
2019-04-28 21:58:40 -04:00
|
|
|
}
|
|
|
|
|
2019-06-01 13:08:04 -05:00
|
|
|
fn replace_with_const(
|
|
|
|
&mut self,
|
|
|
|
rval: &mut Rvalue<'tcx>,
|
2020-01-18 18:44:05 -05:00
|
|
|
value: OpTy<'tcx>,
|
2019-06-01 13:08:04 -05:00
|
|
|
source_info: SourceInfo,
|
2019-06-04 06:30:36 -04:00
|
|
|
) {
|
2020-04-23 17:09:21 -04:00
|
|
|
if let Rvalue::Use(Operand::Constant(c)) = rval {
|
|
|
|
if !matches!(c.literal.val, ConstKind::Unevaluated(..)) {
|
|
|
|
trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-25 10:59:05 -04:00
|
|
|
trace!("attepting to replace {:?} with {:?}", rval, value);
|
2020-03-05 23:31:39 +01:00
|
|
|
if let Err(e) = self.ecx.const_validate_operand(
|
2019-02-10 14:59:13 +01:00
|
|
|
value,
|
|
|
|
vec![],
|
|
|
|
// FIXME: is ref tracking too expensive?
|
2020-03-05 23:31:39 +01:00
|
|
|
&mut interpret::RefTracking::empty(),
|
|
|
|
/*may_ref_to_static*/ true,
|
2019-02-10 14:59:13 +01:00
|
|
|
) {
|
2019-06-04 21:51:30 -04:00
|
|
|
trace!("validation error, attempt failed: {:?}", e);
|
|
|
|
return;
|
|
|
|
}
|
2019-06-01 13:08:04 -05:00
|
|
|
|
2020-03-06 12:13:55 +01:00
|
|
|
// FIXME> figure out what to do when try_read_immediate fails
|
2020-02-08 22:21:20 +01:00
|
|
|
let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
|
2019-04-28 21:58:40 -04:00
|
|
|
|
2019-06-01 13:08:04 -05:00
|
|
|
if let Some(Ok(imm)) = imm {
|
2019-06-11 13:23:08 +02:00
|
|
|
match *imm {
|
2020-04-22 03:20:40 -04:00
|
|
|
interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
|
2019-12-22 17:42:04 -05:00
|
|
|
*rval = Rvalue::Use(self.operand_from_scalar(
|
|
|
|
scalar,
|
|
|
|
value.layout.ty,
|
|
|
|
source_info.span,
|
|
|
|
));
|
|
|
|
}
|
2019-04-28 21:58:40 -04:00
|
|
|
Immediate::ScalarPair(
|
2020-08-14 18:01:14 +02:00
|
|
|
ScalarMaybeUninit::Scalar(_),
|
|
|
|
ScalarMaybeUninit::Scalar(_),
|
2019-04-28 21:58:40 -04:00
|
|
|
) => {
|
2020-08-14 18:01:14 +02:00
|
|
|
// Found a value represented as a pair. For now only do const-prop if the type
|
|
|
|
// of `rvalue` is also a tuple with two scalars.
|
|
|
|
// FIXME: enable the general case stated above ^.
|
|
|
|
let ty = &value.layout.ty;
|
2019-12-05 10:40:24 +03:00
|
|
|
// Only do it for tuples
|
2020-08-14 18:01:14 +02:00
|
|
|
if let ty::Tuple(substs) = ty.kind {
|
2019-12-05 10:40:24 +03:00
|
|
|
// Only do it if tuple is also a pair with two scalars
|
|
|
|
if substs.len() == 2 {
|
2020-08-14 18:01:14 +02:00
|
|
|
let alloc = self.use_ecx(|this| {
|
2019-12-05 10:40:24 +03:00
|
|
|
let ty1 = substs[0].expect_ty();
|
|
|
|
let ty2 = substs[1].expect_ty();
|
|
|
|
let ty_is_scalar = |ty| {
|
2020-03-04 14:13:00 +00:00
|
|
|
this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
|
2019-12-05 10:40:24 +03:00
|
|
|
== Some(true)
|
|
|
|
};
|
|
|
|
if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
|
2020-08-14 18:01:14 +02:00
|
|
|
let alloc = this
|
|
|
|
.ecx
|
2020-08-18 13:44:57 +02:00
|
|
|
.intern_with_temp_alloc(value.layout, |ecx, dest| {
|
2020-08-14 18:01:14 +02:00
|
|
|
ecx.write_immediate_to_mplace(*imm, dest)
|
|
|
|
})
|
|
|
|
.unwrap();
|
|
|
|
Ok(Some(alloc))
|
2019-12-05 10:40:24 +03:00
|
|
|
} else {
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2020-08-14 18:01:14 +02:00
|
|
|
if let Some(Some(alloc)) = alloc {
|
|
|
|
*rval = Rvalue::Use(Operand::Constant(Box::new(Constant {
|
|
|
|
span: source_info.span,
|
|
|
|
user_ty: None,
|
|
|
|
literal: self.ecx.tcx.mk_const(ty::Const {
|
|
|
|
ty,
|
|
|
|
val: ty::ConstKind::Value(ConstValue::ByRef {
|
|
|
|
alloc,
|
|
|
|
offset: Size::ZERO,
|
|
|
|
}),
|
|
|
|
}),
|
|
|
|
})));
|
2019-12-05 10:40:24 +03:00
|
|
|
}
|
|
|
|
}
|
2019-04-28 21:58:40 -04:00
|
|
|
}
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2020-08-14 18:01:14 +02:00
|
|
|
// Scalars or scalar pairs that contain undef values are assumed to not have
|
|
|
|
// successfully evaluated and are thus not propagated.
|
2019-12-22 17:42:04 -05:00
|
|
|
_ => {}
|
2019-04-28 21:58:40 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-05-11 12:33:10 -04:00
|
|
|
|
2020-04-22 22:43:52 -04:00
|
|
|
/// Returns `true` if and only if this `op` should be const-propagated into.
|
2019-10-28 05:59:59 -04:00
|
|
|
fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
|
2019-11-24 19:09:58 -05:00
|
|
|
let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
|
|
|
|
|
|
|
|
if mir_opt_level == 0 {
|
2019-10-28 05:59:59 -04:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
match *op {
|
2020-04-22 03:20:40 -04:00
|
|
|
interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
|
2019-12-22 17:42:04 -05:00
|
|
|
s.is_bits()
|
|
|
|
}
|
|
|
|
interpret::Operand::Immediate(Immediate::ScalarPair(
|
2020-04-22 03:20:40 -04:00
|
|
|
ScalarMaybeUninit::Scalar(l),
|
|
|
|
ScalarMaybeUninit::Scalar(r),
|
2019-12-22 17:42:04 -05:00
|
|
|
)) => l.is_bits() && r.is_bits(),
|
|
|
|
_ => false,
|
2019-10-28 05:59:59 -04:00
|
|
|
}
|
2019-05-11 12:33:10 -04:00
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
|
2019-11-23 12:23:56 -05:00
|
|
|
/// The mode that `ConstProp` is allowed to run in for a given `Local`.
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
|
|
enum ConstPropMode {
|
|
|
|
/// The `Local` can be propagated into and reads of this `Local` can also be propagated.
|
|
|
|
FullConstProp,
|
2020-04-23 12:25:28 -04:00
|
|
|
/// The `Local` can only be propagated into and from its own block.
|
|
|
|
OnlyInsideOwnBlock,
|
2019-11-23 12:23:56 -05:00
|
|
|
/// The `Local` can be propagated into but reads cannot be propagated.
|
|
|
|
OnlyPropagateInto,
|
2020-06-22 14:03:18 +02:00
|
|
|
/// The `Local` cannot be part of propagation at all. Any statement
|
|
|
|
/// referencing it either for reading or writing will not get propagated.
|
|
|
|
NoPropagation,
|
2019-11-23 12:23:56 -05:00
|
|
|
}
|
|
|
|
|
2018-01-30 14:12:16 +01:00
|
|
|
struct CanConstProp {
|
2019-11-23 12:23:56 -05:00
|
|
|
can_const_prop: IndexVec<Local, ConstPropMode>,
|
2020-04-22 22:43:52 -04:00
|
|
|
// False at the beginning. Once set, no more assignments are allowed to that local.
|
2020-04-19 00:35:26 -04:00
|
|
|
found_assignment: BitSet<Local>,
|
2020-04-22 21:53:51 -04:00
|
|
|
// Cache of locals' information
|
|
|
|
local_kinds: IndexVec<Local, LocalKind>,
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
|
2018-01-30 14:12:16 +01:00
|
|
|
impl CanConstProp {
|
2020-04-22 22:43:52 -04:00
|
|
|
/// Returns true if `local` can be propagated
|
2020-07-27 13:52:40 +02:00
|
|
|
fn check(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
param_env: ParamEnv<'tcx>,
|
|
|
|
body: &Body<'tcx>,
|
|
|
|
) -> IndexVec<Local, ConstPropMode> {
|
2018-01-28 14:41:17 +01:00
|
|
|
let mut cpv = CanConstProp {
|
2019-11-23 12:23:56 -05:00
|
|
|
can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
|
2020-04-19 00:35:26 -04:00
|
|
|
found_assignment: BitSet::new_empty(body.local_decls.len()),
|
2020-04-22 21:53:51 -04:00
|
|
|
local_kinds: IndexVec::from_fn_n(
|
|
|
|
|local| body.local_kind(local),
|
|
|
|
body.local_decls.len(),
|
|
|
|
),
|
2018-01-28 14:41:17 +01:00
|
|
|
};
|
2018-01-30 09:40:46 +01:00
|
|
|
for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
|
2020-07-27 13:52:40 +02:00
|
|
|
let ty = body.local_decls[local].ty;
|
|
|
|
match tcx.layout_of(param_env.and(ty)) {
|
|
|
|
Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
|
|
|
|
// Either the layout fails to compute, then we can't use this local anyway
|
|
|
|
// or the local is too large, then we don't want to.
|
|
|
|
_ => {
|
|
|
|
*val = ConstPropMode::NoPropagation;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
2020-04-22 22:43:52 -04:00
|
|
|
// Cannot use args at all
|
|
|
|
// Cannot use locals because if x < y { y - x } else { x - y } would
|
2018-01-30 16:38:14 +01:00
|
|
|
// lint for x != y
|
|
|
|
// FIXME(oli-obk): lint variables until they are used in a condition
|
|
|
|
// FIXME(oli-obk): lint if return value is constant
|
2020-04-23 12:25:28 -04:00
|
|
|
if cpv.local_kinds[local] == LocalKind::Arg {
|
2019-11-23 12:23:56 -05:00
|
|
|
*val = ConstPropMode::OnlyPropagateInto;
|
2020-04-23 12:25:28 -04:00
|
|
|
trace!(
|
|
|
|
"local {:?} can't be const propagated because it's a function argument",
|
|
|
|
local
|
|
|
|
);
|
|
|
|
} else if cpv.local_kinds[local] == LocalKind::Var {
|
|
|
|
*val = ConstPropMode::OnlyInsideOwnBlock;
|
|
|
|
trace!(
|
|
|
|
"local {:?} will only be propagated inside its block, because it's a user variable",
|
|
|
|
local
|
|
|
|
);
|
2019-05-25 10:59:05 -04:00
|
|
|
}
|
2018-01-30 09:40:46 +01:00
|
|
|
}
|
2020-03-28 14:54:41 -07:00
|
|
|
cpv.visit_body(&body);
|
2018-01-28 14:41:17 +01:00
|
|
|
cpv.can_const_prop
|
|
|
|
}
|
2018-01-30 09:40:46 +01:00
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
|
2018-01-30 14:12:16 +01:00
|
|
|
impl<'tcx> Visitor<'tcx> for CanConstProp {
|
2019-12-22 17:42:04 -05:00
|
|
|
fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::mir::visit::PlaceContext::*;
|
2018-01-30 13:57:13 +01:00
|
|
|
match context {
|
2020-05-06 19:28:48 +02:00
|
|
|
// Projections are fine, because `&mut foo.x` will be caught by
|
|
|
|
// `MutatingUseContext::Borrow` elsewhere.
|
|
|
|
MutatingUse(MutatingUseContext::Projection)
|
2020-05-12 13:14:47 +02:00
|
|
|
// These are just stores, where the storing is not propagatable, but there may be later
|
|
|
|
// mutations of the same local via `Store`
|
|
|
|
| MutatingUse(MutatingUseContext::Call)
|
|
|
|
// Actual store that can possibly even propagate a value
|
2020-05-06 19:28:48 +02:00
|
|
|
| MutatingUse(MutatingUseContext::Store) => {
|
2020-04-19 00:35:26 -04:00
|
|
|
if !self.found_assignment.insert(local) {
|
2020-05-06 19:28:48 +02:00
|
|
|
match &mut self.can_const_prop[local] {
|
|
|
|
// If the local can only get propagated in its own block, then we don't have
|
|
|
|
// to worry about multiple assignments, as we'll nuke the const state at the
|
|
|
|
// end of the block anyway, and inside the block we overwrite previous
|
|
|
|
// states as applicable.
|
|
|
|
ConstPropMode::OnlyInsideOwnBlock => {}
|
2020-06-22 14:03:18 +02:00
|
|
|
ConstPropMode::NoPropagation => {}
|
|
|
|
ConstPropMode::OnlyPropagateInto => {}
|
|
|
|
other @ ConstPropMode::FullConstProp => {
|
2020-05-06 19:28:48 +02:00
|
|
|
trace!(
|
2020-05-17 15:39:35 +02:00
|
|
|
"local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
|
|
|
|
local, other,
|
2020-05-06 19:28:48 +02:00
|
|
|
);
|
2020-05-17 15:39:35 +02:00
|
|
|
*other = ConstPropMode::OnlyInsideOwnBlock;
|
2020-05-06 19:28:48 +02:00
|
|
|
}
|
|
|
|
}
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
|
|
|
}
|
2018-01-30 13:57:13 +01:00
|
|
|
// Reading constants is allowed an arbitrary number of times
|
2019-12-22 17:42:04 -05:00
|
|
|
NonMutatingUse(NonMutatingUseContext::Copy)
|
|
|
|
| NonMutatingUse(NonMutatingUseContext::Move)
|
|
|
|
| NonMutatingUse(NonMutatingUseContext::Inspect)
|
|
|
|
| NonMutatingUse(NonMutatingUseContext::Projection)
|
|
|
|
| NonUse(_) => {}
|
2020-05-12 13:14:47 +02:00
|
|
|
|
|
|
|
// These could be propagated with a smarter analysis or just some careful thinking about
|
|
|
|
// whether they'd be fine right now.
|
|
|
|
MutatingUse(MutatingUseContext::AsmOutput)
|
|
|
|
| MutatingUse(MutatingUseContext::Yield)
|
|
|
|
| MutatingUse(MutatingUseContext::Drop)
|
|
|
|
| MutatingUse(MutatingUseContext::Retag)
|
|
|
|
// These can't ever be propagated under any scheme, as we can't reason about indirect
|
|
|
|
// mutation.
|
|
|
|
| NonMutatingUse(NonMutatingUseContext::SharedBorrow)
|
|
|
|
| NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
|
|
|
|
| NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
|
|
|
|
| NonMutatingUse(NonMutatingUseContext::AddressOf)
|
|
|
|
| MutatingUse(MutatingUseContext::Borrow)
|
|
|
|
| MutatingUse(MutatingUseContext::AddressOf) => {
|
2019-05-25 10:59:05 -04:00
|
|
|
trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
|
2020-06-22 14:03:18 +02:00
|
|
|
self.can_const_prop[local] = ConstPropMode::NoPropagation;
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-11 22:03:44 +03:00
|
|
|
impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
|
2019-10-20 16:11:04 -04:00
|
|
|
fn tcx(&self) -> TyCtxt<'tcx> {
|
|
|
|
self.tcx
|
|
|
|
}
|
|
|
|
|
2020-04-21 15:53:00 -03:00
|
|
|
fn visit_body(&mut self, body: &mut Body<'tcx>) {
|
|
|
|
for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
|
|
|
|
self.visit_basic_block_data(bb, data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-22 10:29:37 +02:00
|
|
|
fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
|
2020-07-23 17:58:54 +02:00
|
|
|
self.super_operand(operand, location);
|
|
|
|
|
2020-07-22 10:29:37 +02:00
|
|
|
// Only const prop copies and moves on `mir_opt_level=3` as doing so
|
|
|
|
// currently increases compile time.
|
2020-07-23 17:58:54 +02:00
|
|
|
if self.tcx.sess.opts.debugging_opts.mir_opt_level >= 3 {
|
|
|
|
self.propagate_operand(operand)
|
2020-07-22 10:29:37 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
|
2018-01-28 14:41:17 +01:00
|
|
|
trace!("visit_constant: {:?}", constant);
|
|
|
|
self.super_constant(constant, location);
|
2020-01-01 12:35:50 -03:00
|
|
|
self.eval_constant(constant, self.source_info.unwrap());
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
|
2018-01-28 14:41:17 +01:00
|
|
|
trace!("visit_statement: {:?}", statement);
|
2019-12-29 00:26:25 +01:00
|
|
|
let source_info = statement.source_info;
|
|
|
|
self.source_info = Some(source_info);
|
2020-03-31 12:19:29 -03:00
|
|
|
if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
|
2020-07-27 15:01:25 +02:00
|
|
|
let can_const_prop = self.ecx.machine.can_const_prop[place.local];
|
2020-07-27 13:52:40 +02:00
|
|
|
if let Some(()) = self.const_prop(rval, source_info, place) {
|
|
|
|
// This will return None if the above `const_prop` invocation only "wrote" a
|
|
|
|
// type whose creation requires no write. E.g. a generator whose initial state
|
|
|
|
// consists solely of uninitialized memory (so it doesn't capture any locals).
|
|
|
|
if let Some(value) = self.get_const(place) {
|
|
|
|
if self.should_const_prop(value) {
|
|
|
|
trace!("replacing {:?} with {:?}", rval, value);
|
|
|
|
self.replace_with_const(rval, value, source_info);
|
|
|
|
if can_const_prop == ConstPropMode::FullConstProp
|
|
|
|
|| can_const_prop == ConstPropMode::OnlyInsideOwnBlock
|
|
|
|
{
|
|
|
|
trace!("propagated into {:?}", place);
|
2019-11-23 12:23:56 -05:00
|
|
|
}
|
|
|
|
}
|
2020-07-27 13:52:40 +02:00
|
|
|
}
|
|
|
|
match can_const_prop {
|
|
|
|
ConstPropMode::OnlyInsideOwnBlock => {
|
|
|
|
trace!(
|
|
|
|
"found local restricted to its block. \
|
2020-06-22 14:03:18 +02:00
|
|
|
Will remove it from const-prop after block is finished. Local: {:?}",
|
2020-07-27 13:52:40 +02:00
|
|
|
place.local
|
|
|
|
);
|
|
|
|
}
|
|
|
|
ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
|
|
|
|
trace!("can't propagate into {:?}", place);
|
|
|
|
if place.local != RETURN_PLACE {
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
2020-06-22 14:03:18 +02:00
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2020-07-27 13:52:40 +02:00
|
|
|
ConstPropMode::FullConstProp => {}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2020-06-22 14:03:18 +02:00
|
|
|
} else {
|
2020-07-27 13:52:40 +02:00
|
|
|
// Const prop failed, so erase the destination, ensuring that whatever happens
|
|
|
|
// from here on, does not know about the previous value.
|
|
|
|
// This is important in case we have
|
|
|
|
// ```rust
|
|
|
|
// let mut x = 42;
|
|
|
|
// x = SOME_MUTABLE_STATIC;
|
2020-08-08 07:53:47 -06:00
|
|
|
// // x must now be uninit
|
2020-07-27 13:52:40 +02:00
|
|
|
// ```
|
|
|
|
// FIXME: we overzealously erase the entire local, because that's easier to
|
|
|
|
// implement.
|
2020-06-22 14:03:18 +02:00
|
|
|
trace!(
|
2020-07-27 13:52:40 +02:00
|
|
|
"propagation into {:?} failed.
|
|
|
|
Nuking the entire site from orbit, it's the only way to be sure",
|
2020-06-22 14:03:18 +02:00
|
|
|
place,
|
|
|
|
);
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2019-09-13 08:40:43 -04:00
|
|
|
} else {
|
|
|
|
match statement.kind {
|
2020-05-17 15:39:35 +02:00
|
|
|
StatementKind::SetDiscriminant { ref place, .. } => {
|
|
|
|
match self.ecx.machine.can_const_prop[place.local] {
|
|
|
|
ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
|
|
|
|
if self.use_ecx(|this| this.ecx.statement(statement)).is_some() {
|
|
|
|
trace!("propped discriminant into {:?}", place);
|
|
|
|
} else {
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-12-22 17:42:04 -05:00
|
|
|
StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
|
2019-09-13 08:40:43 -04:00
|
|
|
let frame = self.ecx.frame_mut();
|
|
|
|
frame.locals[local].value =
|
|
|
|
if let StatementKind::StorageLive(_) = statement.kind {
|
|
|
|
LocalValue::Uninitialized
|
|
|
|
} else {
|
|
|
|
LocalValue::Dead
|
|
|
|
};
|
|
|
|
}
|
|
|
|
_ => {}
|
2019-09-05 21:06:57 -04:00
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2019-09-13 08:40:43 -04:00
|
|
|
|
2019-04-22 21:07:14 +01:00
|
|
|
self.super_statement(statement, location);
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
|
2019-05-11 10:55:34 -04:00
|
|
|
let source_info = terminator.source_info;
|
2019-12-29 00:26:25 +01:00
|
|
|
self.source_info = Some(source_info);
|
|
|
|
self.super_terminator(terminator, location);
|
2019-05-11 10:55:34 -04:00
|
|
|
match &mut terminator.kind {
|
2019-07-24 09:12:21 +02:00
|
|
|
TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
|
2019-05-11 10:55:34 -04:00
|
|
|
if let Some(value) = self.eval_operand(&cond, source_info) {
|
|
|
|
trace!("assertion on {:?} should be {:?}", value, expected);
|
2020-04-22 03:20:40 -04:00
|
|
|
let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
|
2019-05-11 10:55:34 -04:00
|
|
|
let value_const = self.ecx.read_scalar(value).unwrap();
|
|
|
|
if expected != value_const {
|
2020-07-10 19:00:38 +02:00
|
|
|
enum DbgVal<T> {
|
|
|
|
Val(T),
|
|
|
|
Underscore,
|
|
|
|
}
|
|
|
|
impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
|
|
|
|
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
Self::Val(val) => val.fmt(fmt),
|
|
|
|
Self::Underscore => fmt.write_str("_"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-06-19 18:57:15 +02:00
|
|
|
let mut eval_to_int = |op| {
|
2020-07-10 19:00:38 +02:00
|
|
|
// This can be `None` if the lhs wasn't const propagated and we just
|
|
|
|
// triggered the assert on the value of the rhs.
|
|
|
|
match self.eval_operand(op, source_info) {
|
|
|
|
Some(op) => {
|
|
|
|
DbgVal::Val(self.ecx.read_immediate(op).unwrap().to_const_int())
|
|
|
|
}
|
|
|
|
None => DbgVal::Underscore,
|
|
|
|
}
|
2020-06-19 18:57:15 +02:00
|
|
|
};
|
2020-02-14 22:49:01 +01:00
|
|
|
let msg = match msg {
|
2020-06-19 18:57:15 +02:00
|
|
|
AssertKind::DivisionByZero(op) => {
|
2020-07-04 19:30:45 +02:00
|
|
|
Some(AssertKind::DivisionByZero(eval_to_int(op)))
|
2020-06-19 18:57:15 +02:00
|
|
|
}
|
|
|
|
AssertKind::RemainderByZero(op) => {
|
2020-07-04 19:30:45 +02:00
|
|
|
Some(AssertKind::RemainderByZero(eval_to_int(op)))
|
2020-06-19 18:57:15 +02:00
|
|
|
}
|
2020-02-14 22:49:01 +01:00
|
|
|
AssertKind::BoundsCheck { ref len, ref index } => {
|
2020-06-19 18:57:15 +02:00
|
|
|
let len = eval_to_int(len);
|
|
|
|
let index = eval_to_int(index);
|
2020-07-04 19:30:45 +02:00
|
|
|
Some(AssertKind::BoundsCheck { len, index })
|
2020-02-14 22:49:01 +01:00
|
|
|
}
|
|
|
|
// Overflow is are already covered by checks on the binary operators.
|
2020-07-04 19:30:45 +02:00
|
|
|
AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
|
2020-02-14 22:49:01 +01:00
|
|
|
// Need proper const propagator for these.
|
2020-07-04 19:30:45 +02:00
|
|
|
_ => None,
|
2020-02-14 22:49:01 +01:00
|
|
|
};
|
2020-07-04 19:30:45 +02:00
|
|
|
// Poison all places this operand references so that further code
|
|
|
|
// doesn't use the invalid value
|
|
|
|
match cond {
|
|
|
|
Operand::Move(ref place) | Operand::Copy(ref place) => {
|
|
|
|
Self::remove_const(&mut self.ecx, place.local);
|
|
|
|
}
|
|
|
|
Operand::Constant(_) => {}
|
|
|
|
}
|
|
|
|
if let Some(msg) = msg {
|
|
|
|
self.report_assert_as_lint(
|
|
|
|
lint::builtin::UNCONDITIONAL_PANIC,
|
|
|
|
source_info,
|
|
|
|
"this operation will panic at runtime",
|
|
|
|
msg,
|
|
|
|
);
|
|
|
|
}
|
2019-05-11 10:55:34 -04:00
|
|
|
} else {
|
2019-10-28 05:59:59 -04:00
|
|
|
if self.should_const_prop(value) {
|
2020-04-22 03:20:40 -04:00
|
|
|
if let ScalarMaybeUninit::Scalar(scalar) = value_const {
|
2019-05-11 12:33:10 -04:00
|
|
|
*cond = self.operand_from_scalar(
|
|
|
|
scalar,
|
|
|
|
self.tcx.types.bool,
|
|
|
|
source_info.span,
|
|
|
|
);
|
|
|
|
}
|
2019-05-11 10:55:34 -04:00
|
|
|
}
|
2018-03-06 12:43:02 +01:00
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2020-07-22 10:29:37 +02:00
|
|
|
TerminatorKind::SwitchInt { ref mut discr, .. } => {
|
|
|
|
// FIXME: This is currently redundant with `visit_operand`, but sadly
|
2020-07-22 12:32:02 +02:00
|
|
|
// always visiting operands currently causes a perf regression in LLVM codegen, so
|
2020-07-22 10:29:37 +02:00
|
|
|
// `visit_operand` currently only runs for propagates places for `mir_opt_level=3`.
|
2020-07-23 17:58:54 +02:00
|
|
|
self.propagate_operand(discr)
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2020-07-22 10:29:37 +02:00
|
|
|
// None of these have Operands to const-propagate.
|
2019-12-22 17:42:04 -05:00
|
|
|
TerminatorKind::Goto { .. }
|
|
|
|
| TerminatorKind::Resume
|
|
|
|
| TerminatorKind::Abort
|
|
|
|
| TerminatorKind::Return
|
|
|
|
| TerminatorKind::Unreachable
|
|
|
|
| TerminatorKind::Drop { .. }
|
|
|
|
| TerminatorKind::DropAndReplace { .. }
|
|
|
|
| TerminatorKind::Yield { .. }
|
|
|
|
| TerminatorKind::GeneratorDrop
|
2020-06-02 09:15:24 +02:00
|
|
|
| TerminatorKind::FalseEdge { .. }
|
2020-02-14 18:17:50 +00:00
|
|
|
| TerminatorKind::FalseUnwind { .. }
|
|
|
|
| TerminatorKind::InlineAsm { .. } => {}
|
2020-07-22 10:29:37 +02:00
|
|
|
// Every argument in our function calls have already been propagated in `visit_operand`.
|
|
|
|
//
|
|
|
|
// NOTE: because LLVM codegen gives performance regressions with it, so this is gated
|
|
|
|
// on `mir_opt_level=3`.
|
|
|
|
TerminatorKind::Call { .. } => {}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
2020-06-26 11:02:43 +02:00
|
|
|
|
|
|
|
// We remove all Locals which are restricted in propagation to their containing blocks and
|
|
|
|
// which were modified in the current block.
|
2020-07-22 10:29:37 +02:00
|
|
|
// Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
|
2020-06-26 11:02:43 +02:00
|
|
|
let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
|
|
|
|
for &local in locals.iter() {
|
2020-04-23 12:25:28 -04:00
|
|
|
Self::remove_const(&mut self.ecx, local);
|
|
|
|
}
|
2020-06-26 11:02:43 +02:00
|
|
|
locals.clear();
|
|
|
|
// Put it back so we reuse the heap of the storage
|
|
|
|
self.ecx.machine.written_only_inside_own_block_locals = locals;
|
|
|
|
if cfg!(debug_assertions) {
|
|
|
|
// Ensure we are correctly erasing locals with the non-debug-assert logic.
|
|
|
|
for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
|
|
|
|
assert!(
|
|
|
|
self.get_const(local.into()).is_none()
|
|
|
|
|| self
|
|
|
|
.layout_of(self.local_decls[local].ty)
|
|
|
|
.map_or(true, |layout| layout.is_zst())
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2018-01-28 14:41:17 +01:00
|
|
|
}
|
|
|
|
}
|