1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Propagates constants for early reporting of statically known
12 //! assertion failures
15 use rustc::hir::def::Def;
16 use rustc::mir::{Constant, Location, Place, Mir, Operand, Rvalue, Local};
17 use rustc::mir::{NullOp, UnOp, StatementKind, Statement, BasicBlock, LocalKind};
18 use rustc::mir::{TerminatorKind, ClearCrossCrate, SourceInfo, BinOp, ProjectionElem};
19 use rustc::mir::visit::{Visitor, PlaceContext, MutatingUseContext, NonMutatingUseContext};
20 use rustc::mir::interpret::{EvalErrorKind, Scalar, GlobalId, EvalResult};
21 use rustc::ty::{TyCtxt, self, Instance};
22 use syntax::source_map::{Span, DUMMY_SP};
23 use rustc::ty::subst::Substs;
24 use rustc_data_structures::indexed_vec::IndexVec;
25 use rustc::ty::ParamEnv;
26 use rustc::ty::layout::{
27 LayoutOf, TyLayout, LayoutError,
28 HasTyCtxt, TargetDataLayout, HasDataLayout,
31 use interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind};
33 CompileTimeInterpreter, const_to_op, error_to_const_error, eval_promoted, mk_borrowck_eval_cx
35 use transform::{MirPass, MirSource};
39 impl MirPass for ConstProp {
40 fn run_pass<'a, 'tcx>(&self,
41 tcx: TyCtxt<'a, 'tcx, 'tcx>,
43 mir: &mut Mir<'tcx>) {
44 // will be evaluated by miri and produce its errors there
45 if source.promoted.is_some() {
49 use rustc::hir::map::blocks::FnLikeNode;
50 let node_id = tcx.hir().as_local_node_id(source.def_id)
51 .expect("Non-local call to local provider is_const_fn");
53 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(node_id)).is_some();
54 let is_assoc_const = match tcx.describe_def(source.def_id) {
55 Some(Def::AssociatedConst(_)) => true,
59 // Only run const prop on functions, methods, closures and associated constants
60 if !is_fn_like && !is_assoc_const {
61 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
62 trace!("ConstProp skipped for {:?}", source.def_id);
66 trace!("ConstProp starting for {:?}", source.def_id);
68 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
69 // constants, instead of just checking for const-folding succeeding.
70 // That would require an uniform one-def no-mutation analysis
71 // and RPO (or recursing when needing the value of a local).
72 let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
73 optimization_finder.visit_mir(mir);
75 trace!("ConstProp done for {:?}", source.def_id);
79 type Const<'tcx> = (OpTy<'tcx>, Span);
81 /// Finds optimization opportunities on the MIR.
82 struct ConstPropagator<'a, 'mir, 'tcx:'a+'mir> {
83 ecx: EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
85 tcx: TyCtxt<'a, 'tcx, 'tcx>,
87 places: IndexVec<Local, Option<Const<'tcx>>>,
88 can_const_prop: IndexVec<Local, bool>,
89 param_env: ParamEnv<'tcx>,
92 impl<'a, 'b, 'tcx> LayoutOf for ConstPropagator<'a, 'b, 'tcx> {
93 type Ty = ty::Ty<'tcx>;
94 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
96 fn layout_of(&self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
97 self.tcx.layout_of(self.param_env.and(ty))
101 impl<'a, 'b, 'tcx> HasDataLayout for ConstPropagator<'a, 'b, 'tcx> {
103 fn data_layout(&self) -> &TargetDataLayout {
104 &self.tcx.data_layout
108 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'a, 'b, 'tcx> {
110 fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
115 impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> {
117 mir: &'mir Mir<'tcx>,
118 tcx: TyCtxt<'a, 'tcx, 'tcx>,
120 ) -> ConstPropagator<'a, 'mir, 'tcx> {
121 let param_env = tcx.param_env(source.def_id);
122 let substs = Substs::identity_for_item(tcx, source.def_id);
123 let instance = Instance::new(source.def_id, substs);
124 let ecx = mk_borrowck_eval_cx(tcx, instance, mir, DUMMY_SP).unwrap();
131 can_const_prop: CanConstProp::check(mir),
132 places: IndexVec::from_elem(None, &mir.local_decls),
138 source_info: SourceInfo,
142 F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
144 self.ecx.tcx.span = source_info.span;
145 let lint_root = match self.mir.source_scope_local_data {
146 ClearCrossCrate::Set(ref ivs) => {
147 //FIXME(#51314): remove this check
148 if source_info.scope.index() >= ivs.len() {
151 ivs[source_info.scope].lint_root
153 ClearCrossCrate::Clear => return None,
155 let r = match f(self) {
156 Ok(val) => Some(val),
158 let diagnostic = error_to_const_error(&self.ecx, error);
159 use rustc::mir::interpret::EvalErrorKind::*;
160 match diagnostic.error {
161 // don't report these, they make no sense in a const prop context
163 // at runtime these transformations might make sense
164 // FIXME: figure out the rules and start linting
165 | FunctionAbiMismatch(..)
166 | FunctionArgMismatch(..)
167 | FunctionRetMismatch(..)
168 | FunctionArgCountMismatch
169 // fine at runtime, might be a register address or sth
174 // don't report const evaluator limits
175 | StackFrameLimitReached
180 | InvalidMemoryAccess
181 | DanglingPointerDeref
183 | InvalidFunctionPointer
185 | InvalidDiscriminant(..)
186 | PointerOutOfBounds { .. }
187 | InvalidNullPointerUsage
188 | ValidationFailure(..)
193 | DerefFunctionPointer
198 | AlignmentCheckFailed{..}
199 | CalledClosureAsFunction
200 | VtableForArgumentlessMethod
201 | ModifiedConstantMemory
204 // FIXME: should probably be removed and turned into a bug! call
205 | TypeNotPrimitive(_)
206 | ReallocatedWrongMemoryKind(_, _)
207 | DeallocatedWrongMemoryKind(_, _)
208 | ReallocateNonBasePtr
209 | DeallocateNonBasePtr
210 | IncorrectAllocationInformation(..)
211 | UnterminatedCString(_)
213 | HeapAllocNonPowerOfTwoAlignment(_)
215 | ReadFromReturnPointer
216 | GeneratorResumedAfterReturn
217 | GeneratorResumedAfterPanic
221 // FIXME: report UB here
227 => bug!("these should not be in rustc, but in miri's machine errors"),
230 | UnimplementedTraitSelection
233 // these are just noise
248 diagnostic.report_as_lint(
250 "this expression will panic at runtime",
258 self.ecx.tcx.span = DUMMY_SP;
265 source_info: SourceInfo,
266 ) -> Option<Const<'tcx>> {
267 self.ecx.tcx.span = source_info.span;
268 match const_to_op(&self.ecx, c.literal) {
273 let err = error_to_const_error(&self.ecx, error);
274 err.report_as_error(self.ecx.tcx, "erroneous constant used");
280 fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
282 Place::Local(loc) => self.places[loc].clone(),
283 Place::Projection(ref proj) => match proj.elem {
284 ProjectionElem::Field(field, _) => {
285 trace!("field proj on {:?}", proj.base);
286 let (base, span) = self.eval_place(&proj.base, source_info)?;
287 let res = self.use_ecx(source_info, |this| {
288 this.ecx.operand_field(base, field.index() as u64)
292 // We could get more projections by using e.g., `operand_projection`,
293 // but we do not even have the stack frame set up properly so
294 // an `Index` projection would throw us off-track.
297 Place::Promoted(ref promoted) => {
298 let generics = self.tcx.generics_of(self.source.def_id);
299 if generics.requires_monomorphization(self.tcx) {
300 // FIXME: can't handle code with generics
303 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
304 let instance = Instance::new(self.source.def_id, substs);
307 promoted: Some(promoted.0),
309 // cannot use `const_eval` here, because that would require having the MIR
310 // for the current function available, but we're producing said MIR right now
311 let res = self.use_ecx(source_info, |this| {
312 eval_promoted(this.tcx, cid, this.mir, this.param_env)
314 trace!("evaluated promoted {:?} to {:?}", promoted, res);
315 Some((res.into(), source_info.span))
321 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
323 Operand::Constant(ref c) => self.eval_constant(c, source_info),
324 | Operand::Move(ref place)
325 | Operand::Copy(ref place) => self.eval_place(place, source_info),
331 rvalue: &Rvalue<'tcx>,
332 place_layout: TyLayout<'tcx>,
333 source_info: SourceInfo,
334 ) -> Option<Const<'tcx>> {
335 let span = source_info.span;
337 Rvalue::Use(ref op) => {
338 self.eval_operand(op, source_info)
342 Rvalue::Aggregate(..) |
343 Rvalue::NullaryOp(NullOp::Box, _) |
344 Rvalue::Discriminant(..) => None,
346 Rvalue::Cast(kind, ref operand, _) => {
347 let (op, span) = self.eval_operand(operand, source_info)?;
348 self.use_ecx(source_info, |this| {
349 let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
350 this.ecx.cast(op, kind, dest.into())?;
351 Ok((dest.into(), span))
355 // FIXME(oli-obk): evaluate static/constant slice lengths
356 Rvalue::Len(_) => None,
357 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
358 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some((
360 op: interpret::Operand::Immediate(Immediate::Scalar(
363 size: self.tcx.data_layout.pointer_size.bytes() as u8,
366 layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
371 Rvalue::UnaryOp(op, ref arg) => {
372 let def_id = if self.tcx.is_closure(self.source.def_id) {
373 self.tcx.closure_base_def_id(self.source.def_id)
377 let generics = self.tcx.generics_of(def_id);
378 if generics.requires_monomorphization(self.tcx) {
379 // FIXME: can't handle code with generics
383 let (arg, _) = self.eval_operand(arg, source_info)?;
384 let val = self.use_ecx(source_info, |this| {
385 let prim = this.ecx.read_scalar(arg)?.not_undef()?;
388 // Need to do overflow check here: For actual CTFE, MIR
389 // generation emits code that does this before calling the op.
390 let size = arg.layout.size;
391 if prim.to_bits(size)? == (1 << (size.bits() - 1)) {
392 return err!(OverflowNeg);
399 // Now run the actual operation.
400 this.ecx.unary_op(op, prim, arg.layout)
403 op: interpret::Operand::Immediate(Immediate::Scalar(val.into())),
404 layout: place_layout,
408 Rvalue::CheckedBinaryOp(op, ref left, ref right) |
409 Rvalue::BinaryOp(op, ref left, ref right) => {
410 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
411 let right = self.eval_operand(right, source_info)?;
412 let def_id = if self.tcx.is_closure(self.source.def_id) {
413 self.tcx.closure_base_def_id(self.source.def_id)
417 let generics = self.tcx.generics_of(def_id);
418 if generics.requires_monomorphization(self.tcx) {
419 // FIXME: can't handle code with generics
423 let r = self.use_ecx(source_info, |this| {
424 this.ecx.read_immediate(right.0)
426 if op == BinOp::Shr || op == BinOp::Shl {
427 let left_ty = left.ty(self.mir, self.tcx);
430 .layout_of(self.param_env.and(left_ty))
434 let right_size = right.0.layout.size;
435 let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
436 if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
437 let source_scope_local_data = match self.mir.source_scope_local_data {
438 ClearCrossCrate::Set(ref data) => data,
439 ClearCrossCrate::Clear => return None,
441 let dir = if op == BinOp::Shr {
446 let node_id = source_scope_local_data[source_info.scope].lint_root;
448 ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
451 &format!("attempt to shift {} with overflow", dir));
455 let left = self.eval_operand(left, source_info)?;
456 let l = self.use_ecx(source_info, |this| {
457 this.ecx.read_immediate(left.0)
459 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
460 let (val, overflow) = self.use_ecx(source_info, |this| {
461 this.ecx.binary_op_imm(op, l, r)
463 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
464 Immediate::ScalarPair(
466 Scalar::from_bool(overflow).into(),
470 let err = EvalErrorKind::Overflow(op).into();
471 let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
474 Immediate::Scalar(val.into())
477 op: interpret::Operand::Immediate(val),
478 layout: place_layout,
486 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
487 param_env: ty::ParamEnv<'tcx>,
488 ty: ty::Ty<'tcx>) -> Option<u64> {
489 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
492 struct CanConstProp {
493 can_const_prop: IndexVec<Local, bool>,
494 // false at the beginning, once set, there are not allowed to be any more assignments
495 found_assignment: IndexVec<Local, bool>,
499 /// returns true if `local` can be propagated
500 fn check(mir: &Mir) -> IndexVec<Local, bool> {
501 let mut cpv = CanConstProp {
502 can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
503 found_assignment: IndexVec::from_elem(false, &mir.local_decls),
505 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
506 // cannot use args at all
507 // cannot use locals because if x < y { y - x } else { x - y } would
509 // FIXME(oli-obk): lint variables until they are used in a condition
510 // FIXME(oli-obk): lint if return value is constant
511 *val = mir.local_kind(local) == LocalKind::Temp;
518 impl<'tcx> Visitor<'tcx> for CanConstProp {
522 context: PlaceContext<'tcx>,
525 use rustc::mir::visit::PlaceContext::*;
527 // Constants must have at most one write
528 // FIXME(oli-obk): we could be more powerful here, if the multiple writes
529 // only occur in independent execution paths
530 MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
531 self.can_const_prop[local] = false;
533 self.found_assignment[local] = true
535 // Reading constants is allowed an arbitrary number of times
536 NonMutatingUse(NonMutatingUseContext::Copy) |
537 NonMutatingUse(NonMutatingUseContext::Move) |
538 NonMutatingUse(NonMutatingUseContext::Inspect) |
539 NonMutatingUse(NonMutatingUseContext::Projection) |
540 MutatingUse(MutatingUseContext::Projection) |
542 _ => self.can_const_prop[local] = false,
547 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
550 constant: &Constant<'tcx>,
553 trace!("visit_constant: {:?}", constant);
554 self.super_constant(constant, location);
555 let source_info = *self.mir.source_info(location);
556 self.eval_constant(constant, source_info);
562 statement: &Statement<'tcx>,
565 trace!("visit_statement: {:?}", statement);
566 if let StatementKind::Assign(ref place, ref rval) = statement.kind {
567 let place_ty: ty::Ty<'tcx> = place
568 .ty(&self.mir.local_decls, self.tcx)
570 if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
571 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
572 if let Place::Local(local) = *place {
573 trace!("checking whether {:?} can be stored to {:?}", value, local);
574 if self.can_const_prop[local] {
575 trace!("storing {:?} to {:?}", value, local);
576 assert!(self.places[local].is_none());
577 self.places[local] = Some(value);
583 self.super_statement(block, statement, location);
586 fn visit_terminator_kind(
589 kind: &TerminatorKind<'tcx>,
592 self.super_terminator_kind(block, kind, location);
593 let source_info = *self.mir.source_info(location);
594 if let TerminatorKind::Assert { expected, msg, cond, .. } = kind {
595 if let Some(value) = self.eval_operand(cond, source_info) {
596 trace!("assertion on {:?} should be {:?}", value, expected);
597 let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
598 if expected != self.ecx.read_scalar(value.0).unwrap() {
599 // poison all places this operand references so that further code
600 // doesn't use the invalid value
602 Operand::Move(ref place) | Operand::Copy(ref place) => {
603 let mut place = place;
604 while let Place::Projection(ref proj) = *place {
607 if let Place::Local(local) = *place {
608 self.places[local] = None;
611 Operand::Constant(_) => {}
613 let span = self.mir[block]
622 .as_local_node_id(self.source.def_id)
623 .expect("some part of a failing const eval must be local");
624 use rustc::mir::interpret::EvalErrorKind::*;
625 let msg = match msg {
629 RemainderByZero => msg.description().to_owned(),
630 BoundsCheck { ref len, ref index } => {
632 .eval_operand(len, source_info)
633 .expect("len must be const");
634 let len = match self.ecx.read_scalar(len.0) {
635 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
638 other => bug!("const len not primitive: {:?}", other),
641 .eval_operand(index, source_info)
642 .expect("index must be const");
643 let index = match self.ecx.read_scalar(index.0) {
644 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
647 other => bug!("const index not primitive: {:?}", other),
650 "index out of bounds: \
651 the len is {} but the index is {}",
656 // Need proper const propagator for these
660 ::rustc::lint::builtin::CONST_ERR,