1 //! Propagates constants for early reporting of statically known
6 use rustc::hir::def::DefKind;
8 AggregateKind, Constant, Location, Place, PlaceBase, Body, Operand, Rvalue,
9 Local, NullOp, UnOp, StatementKind, Statement, LocalKind, Static, StaticKind,
10 TerminatorKind, Terminator, ClearCrossCrate, SourceInfo, BinOp, ProjectionElem,
11 SourceScope, SourceScopeLocalData, LocalDecl,
13 use rustc::mir::visit::{
14 Visitor, PlaceContext, MutatingUseContext, MutVisitor, NonMutatingUseContext,
16 use rustc::mir::interpret::{Scalar, GlobalId, InterpResult, PanicInfo};
17 use rustc::ty::{self, Instance, ParamEnv, Ty, TyCtxt};
18 use syntax_pos::{Span, DUMMY_SP};
19 use rustc::ty::subst::InternalSubsts;
20 use rustc_data_structures::indexed_vec::IndexVec;
21 use rustc::ty::layout::{
22 LayoutOf, TyLayout, LayoutError, HasTyCtxt, TargetDataLayout, HasDataLayout,
25 use crate::interpret::{
26 self, InterpCx, ScalarMaybeUndef, Immediate, OpTy,
27 ImmTy, MemoryKind, StackPopCleanup, LocalValue, LocalState,
29 use crate::const_eval::{
30 CompileTimeInterpreter, error_to_const_error, mk_eval_cx,
32 use crate::transform::{MirPass, MirSource};
36 impl<'tcx> MirPass<'tcx> for ConstProp {
37 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
38 // will be evaluated by miri and produce its errors there
39 if source.promoted.is_some() {
43 use rustc::hir::map::blocks::FnLikeNode;
44 let hir_id = tcx.hir().as_local_hir_id(source.def_id())
45 .expect("Non-local call to local provider is_const_fn");
47 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
48 let is_assoc_const = match tcx.def_kind(source.def_id()) {
49 Some(DefKind::AssocConst) => true,
53 // Only run const prop on functions, methods, closures and associated constants
54 if !is_fn_like && !is_assoc_const {
55 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
56 trace!("ConstProp skipped for {:?}", source.def_id());
60 trace!("ConstProp starting for {:?}", source.def_id());
62 // Steal some data we need from `body`.
63 let source_scope_local_data = std::mem::replace(
64 &mut body.source_scope_local_data,
65 ClearCrossCrate::Clear
70 body.basic_blocks().clone(),
72 ClearCrossCrate::Clear,
74 body.local_decls.clone(),
78 tcx.def_span(source.def_id()),
82 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
83 // constants, instead of just checking for const-folding succeeding.
84 // That would require an uniform one-def no-mutation analysis
85 // and RPO (or recursing when needing the value of a local).
86 let mut optimization_finder = ConstPropagator::new(
89 source_scope_local_data,
93 optimization_finder.visit_body(body);
95 // put back the data we stole from `mir`
96 let source_scope_local_data = optimization_finder.release_stolen_data();
98 &mut body.source_scope_local_data,
99 source_scope_local_data
102 trace!("ConstProp done for {:?}", source.def_id());
106 type Const<'tcx> = OpTy<'tcx>;
108 /// Finds optimization opportunities on the MIR.
109 struct ConstPropagator<'mir, 'tcx> {
110 ecx: InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>,
112 source: MirSource<'tcx>,
113 can_const_prop: IndexVec<Local, bool>,
114 param_env: ParamEnv<'tcx>,
115 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
116 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
119 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
121 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
123 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
124 self.tcx.layout_of(self.param_env.and(ty))
128 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
130 fn data_layout(&self) -> &TargetDataLayout {
131 &self.tcx.data_layout
135 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
137 fn tcx(&self) -> TyCtxt<'tcx> {
142 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
145 dummy_body: &'mir Body<'tcx>,
146 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
148 source: MirSource<'tcx>,
149 ) -> ConstPropagator<'mir, 'tcx> {
150 let def_id = source.def_id();
151 let param_env = tcx.param_env(def_id);
152 let span = tcx.def_span(def_id);
153 let mut ecx = mk_eval_cx(tcx, span, param_env);
154 let can_const_prop = CanConstProp::check(body);
156 ecx.push_stack_frame(
157 Instance::new(def_id, &InternalSubsts::identity_for_item(tcx, def_id)),
161 StackPopCleanup::None {
164 ).expect("failed to push initial stack frame");
172 source_scope_local_data,
173 //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
174 local_decls: body.local_decls.clone(),
178 fn release_stolen_data(self) -> ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>> {
179 self.source_scope_local_data
182 fn get_const(&self, local: Local) -> Option<Const<'tcx>> {
183 let l = &self.ecx.frame().locals[local];
185 // If the local is `Unitialized` or `Dead` then we haven't propagated a value into it.
187 // `InterpCx::access_local()` mostly takes care of this for us however, for ZSTs,
188 // it will synthesize a value for us. In doing so, that will cause the
189 // `get_const(l).is_empty()` assert right before we call `set_const()` in `visit_statement`
191 if let LocalValue::Uninitialized | LocalValue::Dead = l.value {
195 self.ecx.access_local(self.ecx.frame(), local, None).ok()
198 fn set_const(&mut self, local: Local, c: Const<'tcx>) {
199 let frame = self.ecx.frame_mut();
201 if let Some(layout) = frame.locals[local].layout.get() {
202 debug_assert_eq!(c.layout, layout);
205 frame.locals[local] = LocalState {
206 value: LocalValue::Live(*c),
207 layout: Cell::new(Some(c.layout)),
211 fn remove_const(&mut self, local: Local) {
212 self.ecx.frame_mut().locals[local] = LocalState {
213 value: LocalValue::Uninitialized,
214 layout: Cell::new(None),
220 source_info: SourceInfo,
224 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
226 self.ecx.tcx.span = source_info.span;
227 let lint_root = match self.source_scope_local_data {
228 ClearCrossCrate::Set(ref ivs) => {
229 //FIXME(#51314): remove this check
230 if source_info.scope.index() >= ivs.len() {
233 ivs[source_info.scope].lint_root
235 ClearCrossCrate::Clear => return None,
237 let r = match f(self) {
238 Ok(val) => Some(val),
240 use rustc::mir::interpret::InterpError::*;
242 Exit(_) => bug!("the CTFE program cannot exit"),
244 | UndefinedBehavior(_)
246 | ResourceExhaustion(_) => {
247 // Ignore these errors.
250 let diagnostic = error_to_const_error(&self.ecx, error);
251 diagnostic.report_as_lint(
253 "this expression will panic at runtime",
262 self.ecx.tcx.span = DUMMY_SP;
269 ) -> Option<Const<'tcx>> {
270 self.ecx.tcx.span = c.span;
271 match self.ecx.eval_const_to_op(c.literal, None) {
276 let err = error_to_const_error(&self.ecx, error);
277 err.report_as_error(self.ecx.tcx, "erroneous constant used");
283 fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
284 trace!("eval_place(place={:?})", place);
285 let mut eval = match place.base {
286 PlaceBase::Local(loc) => self.get_const(loc).clone()?,
287 PlaceBase::Static(box Static {kind: StaticKind::Promoted(promoted, _), ..}) => {
288 let generics = self.tcx.generics_of(self.source.def_id());
289 if generics.requires_monomorphization(self.tcx) {
290 // FIXME: can't handle code with generics
293 let substs = InternalSubsts::identity_for_item(self.tcx, self.source.def_id());
294 let instance = Instance::new(self.source.def_id(), substs);
297 promoted: Some(promoted),
299 let res = self.use_ecx(source_info, |this| {
300 this.ecx.const_eval_raw(cid)
302 trace!("evaluated promoted {:?} to {:?}", promoted, res);
308 for (i, elem) in place.projection.iter().enumerate() {
309 let proj_base = &place.projection[..i];
312 ProjectionElem::Field(field, _) => {
313 trace!("field proj on {:?}", proj_base);
314 eval = self.use_ecx(source_info, |this| {
315 this.ecx.operand_field(eval, field.index() as u64)
318 ProjectionElem::Deref => {
319 trace!("processing deref");
320 eval = self.use_ecx(source_info, |this| {
321 this.ecx.deref_operand(eval)
324 // We could get more projections by using e.g., `operand_projection`,
325 // but we do not even have the stack frame set up properly so
326 // an `Index` projection would throw us off-track.
334 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
336 Operand::Constant(ref c) => self.eval_constant(c),
337 | Operand::Move(ref place)
338 | Operand::Copy(ref place) => self.eval_place(place, source_info),
344 rvalue: &Rvalue<'tcx>,
345 place_layout: TyLayout<'tcx>,
346 source_info: SourceInfo,
347 ) -> Option<Const<'tcx>> {
348 let span = source_info.span;
350 Rvalue::Use(ref op) => {
351 self.eval_operand(op, source_info)
353 Rvalue::Ref(_, _, ref place) => {
354 let src = self.eval_place(place, source_info)?;
355 let mplace = src.try_as_mplace().ok()?;
356 Some(ImmTy::from_scalar(mplace.ptr.into(), place_layout).into())
359 Rvalue::Aggregate(..) |
360 Rvalue::NullaryOp(NullOp::Box, _) |
361 Rvalue::Discriminant(..) => None,
363 Rvalue::Cast(kind, ref operand, _) => {
364 let op = self.eval_operand(operand, source_info)?;
365 self.use_ecx(source_info, |this| {
366 let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
367 this.ecx.cast(op, kind, dest.into())?;
371 Rvalue::Len(ref place) => {
372 let place = self.eval_place(&place, source_info)?;
373 let mplace = place.try_as_mplace().ok()?;
375 if let ty::Slice(_) = mplace.layout.ty.sty {
376 let len = mplace.meta.unwrap().to_usize(&self.ecx).unwrap();
378 Some(ImmTy::from_uint(
380 self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
383 trace!("not slice: {:?}", mplace.layout.ty.sty);
387 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
388 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some(
391 self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
395 Rvalue::UnaryOp(op, ref arg) => {
396 let def_id = if self.tcx.is_closure(self.source.def_id()) {
397 self.tcx.closure_base_def_id(self.source.def_id())
401 let generics = self.tcx.generics_of(def_id);
402 if generics.requires_monomorphization(self.tcx) {
403 // FIXME: can't handle code with generics
407 let arg = self.eval_operand(arg, source_info)?;
408 let oflo_check = self.tcx.sess.overflow_checks();
409 let val = self.use_ecx(source_info, |this| {
410 let prim = this.ecx.read_immediate(arg)?;
413 // We check overflow in debug mode already
414 // so should only check in release mode.
416 && prim.layout.ty.is_signed()
417 && prim.to_bits()? == (1 << (prim.layout.size.bits() - 1)) {
418 throw_panic!(OverflowNeg)
425 // Now run the actual operation.
426 this.ecx.unary_op(op, prim)
430 Rvalue::CheckedBinaryOp(op, ref left, ref right) |
431 Rvalue::BinaryOp(op, ref left, ref right) => {
432 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
433 let right = self.eval_operand(right, source_info)?;
434 let def_id = if self.tcx.is_closure(self.source.def_id()) {
435 self.tcx.closure_base_def_id(self.source.def_id())
439 let generics = self.tcx.generics_of(def_id);
440 if generics.requires_monomorphization(self.tcx) {
441 // FIXME: can't handle code with generics
445 let r = self.use_ecx(source_info, |this| {
446 this.ecx.read_immediate(right)
448 if op == BinOp::Shr || op == BinOp::Shl {
449 let left_ty = left.ty(&self.local_decls, self.tcx);
452 .layout_of(self.param_env.and(left_ty))
456 let right_size = right.layout.size;
457 let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
458 if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
459 let source_scope_local_data = match self.source_scope_local_data {
460 ClearCrossCrate::Set(ref data) => data,
461 ClearCrossCrate::Clear => return None,
463 let dir = if op == BinOp::Shr {
468 let hir_id = source_scope_local_data[source_info.scope].lint_root;
470 ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
473 &format!("attempt to shift {} with overflow", dir));
477 let left = self.eval_operand(left, source_info)?;
478 let l = self.use_ecx(source_info, |this| {
479 this.ecx.read_immediate(left)
481 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
482 let (val, overflow, _ty) = self.use_ecx(source_info, |this| {
483 this.ecx.overflowing_binary_op(op, l, r)
485 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
486 Immediate::ScalarPair(
488 Scalar::from_bool(overflow).into(),
491 // We check overflow in debug mode already
492 // so should only check in release mode.
493 if !self.tcx.sess.overflow_checks() && overflow {
494 let err = err_panic!(Overflow(op)).into();
495 let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
498 Immediate::Scalar(val.into())
502 layout: place_layout,
509 fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
510 Operand::Constant(Box::new(
514 literal: self.tcx.mk_const(*ty::Const::from_scalar(
523 fn replace_with_const(
525 rval: &mut Rvalue<'tcx>,
527 source_info: SourceInfo,
529 trace!("attepting to replace {:?} with {:?}", rval, value);
530 if let Err(e) = self.ecx.validate_operand(
533 // FIXME: is ref tracking too expensive?
534 Some(&mut interpret::RefTracking::empty()),
536 trace!("validation error, attempt failed: {:?}", e);
540 // FIXME> figure out what tho do when try_read_immediate fails
541 let imm = self.use_ecx(source_info, |this| {
542 this.ecx.try_read_immediate(value)
545 if let Some(Ok(imm)) = imm {
547 interpret::Immediate::Scalar(ScalarMaybeUndef::Scalar(scalar)) => {
549 self.operand_from_scalar(scalar, value.layout.ty, source_info.span));
551 Immediate::ScalarPair(
552 ScalarMaybeUndef::Scalar(one),
553 ScalarMaybeUndef::Scalar(two)
555 let ty = &value.layout.ty.sty;
556 if let ty::Tuple(substs) = ty {
557 *rval = Rvalue::Aggregate(
558 Box::new(AggregateKind::Tuple),
560 self.operand_from_scalar(
561 one, substs[0].expect_ty(), source_info.span
563 self.operand_from_scalar(
564 two, substs[1].expect_ty(), source_info.span
575 fn should_const_prop(&self) -> bool {
576 self.tcx.sess.opts.debugging_opts.mir_opt_level >= 2
580 fn type_size_of<'tcx>(
582 param_env: ty::ParamEnv<'tcx>,
585 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
588 struct CanConstProp {
589 can_const_prop: IndexVec<Local, bool>,
590 // false at the beginning, once set, there are not allowed to be any more assignments
591 found_assignment: IndexVec<Local, bool>,
595 /// returns true if `local` can be propagated
596 fn check(body: &Body<'_>) -> IndexVec<Local, bool> {
597 let mut cpv = CanConstProp {
598 can_const_prop: IndexVec::from_elem(true, &body.local_decls),
599 found_assignment: IndexVec::from_elem(false, &body.local_decls),
601 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
602 // cannot use args at all
603 // cannot use locals because if x < y { y - x } else { x - y } would
605 // FIXME(oli-obk): lint variables until they are used in a condition
606 // FIXME(oli-obk): lint if return value is constant
607 *val = body.local_kind(local) == LocalKind::Temp;
610 trace!("local {:?} can't be propagated because it's not a temporary", local);
613 cpv.visit_body(body);
618 impl<'tcx> Visitor<'tcx> for CanConstProp {
622 context: PlaceContext,
625 use rustc::mir::visit::PlaceContext::*;
627 // Constants must have at most one write
628 // FIXME(oli-obk): we could be more powerful here, if the multiple writes
629 // only occur in independent execution paths
630 MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
631 trace!("local {:?} can't be propagated because of multiple assignments", local);
632 self.can_const_prop[local] = false;
634 self.found_assignment[local] = true
636 // Reading constants is allowed an arbitrary number of times
637 NonMutatingUse(NonMutatingUseContext::Copy) |
638 NonMutatingUse(NonMutatingUseContext::Move) |
639 NonMutatingUse(NonMutatingUseContext::Inspect) |
640 NonMutatingUse(NonMutatingUseContext::Projection) |
641 MutatingUse(MutatingUseContext::Projection) |
644 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
645 self.can_const_prop[local] = false;
651 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
654 constant: &mut Constant<'tcx>,
657 trace!("visit_constant: {:?}", constant);
658 self.super_constant(constant, location);
659 self.eval_constant(constant);
664 statement: &mut Statement<'tcx>,
667 trace!("visit_statement: {:?}", statement);
668 if let StatementKind::Assign(box(ref place, ref mut rval)) = statement.kind {
669 let place_ty: Ty<'tcx> = place
670 .ty(&self.local_decls, self.tcx)
672 if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
673 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
675 base: PlaceBase::Local(local),
678 trace!("checking whether {:?} can be stored to {:?}", value, local);
679 if self.can_const_prop[local] {
680 trace!("storing {:?} to {:?}", value, local);
681 assert!(self.get_const(local).is_none());
682 self.set_const(local, value);
684 if self.should_const_prop() {
685 self.replace_with_const(
688 statement.source_info,
696 self.super_statement(statement, location);
701 terminator: &mut Terminator<'tcx>,
704 self.super_terminator(terminator, location);
705 let source_info = terminator.source_info;
706 match &mut terminator.kind {
707 TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
708 if let Some(value) = self.eval_operand(&cond, source_info) {
709 trace!("assertion on {:?} should be {:?}", value, expected);
710 let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
711 let value_const = self.ecx.read_scalar(value).unwrap();
712 if expected != value_const {
713 // poison all places this operand references so that further code
714 // doesn't use the invalid value
716 Operand::Move(ref place) | Operand::Copy(ref place) => {
717 if let PlaceBase::Local(local) = place.base {
718 self.remove_const(local);
721 Operand::Constant(_) => {}
723 let span = terminator.source_info.span;
727 .as_local_hir_id(self.source.def_id())
728 .expect("some part of a failing const eval must be local");
729 let msg = match msg {
730 PanicInfo::Overflow(_) |
731 PanicInfo::OverflowNeg |
732 PanicInfo::DivisionByZero |
733 PanicInfo::RemainderByZero =>
734 msg.description().to_owned(),
735 PanicInfo::BoundsCheck { ref len, ref index } => {
737 .eval_operand(len, source_info)
738 .expect("len must be const");
739 let len = match self.ecx.read_scalar(len) {
740 Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
743 other => bug!("const len not primitive: {:?}", other),
746 .eval_operand(index, source_info)
747 .expect("index must be const");
748 let index = match self.ecx.read_scalar(index) {
749 Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
752 other => bug!("const index not primitive: {:?}", other),
755 "index out of bounds: \
756 the len is {} but the index is {}",
761 // Need proper const propagator for these
765 ::rustc::lint::builtin::CONST_ERR,
771 if self.should_const_prop() {
772 if let ScalarMaybeUndef::Scalar(scalar) = value_const {
773 *cond = self.operand_from_scalar(
783 TerminatorKind::SwitchInt { ref mut discr, switch_ty, .. } => {
784 if self.should_const_prop() {
785 if let Some(value) = self.eval_operand(&discr, source_info) {
786 if let ScalarMaybeUndef::Scalar(scalar) =
787 self.ecx.read_scalar(value).unwrap() {
788 *discr = self.operand_from_scalar(scalar, switch_ty, source_info.span);
793 //none of these have Operands to const-propagate
794 TerminatorKind::Goto { .. } |
795 TerminatorKind::Resume |
796 TerminatorKind::Abort |
797 TerminatorKind::Return |
798 TerminatorKind::Unreachable |
799 TerminatorKind::Drop { .. } |
800 TerminatorKind::DropAndReplace { .. } |
801 TerminatorKind::Yield { .. } |
802 TerminatorKind::GeneratorDrop |
803 TerminatorKind::FalseEdges { .. } |
804 TerminatorKind::FalseUnwind { .. } => { }
805 //FIXME(wesleywiser) Call does have Operands that could be const-propagated
806 TerminatorKind::Call { .. } => { }