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, Literal, Location, Place, Mir, Operand, Rvalue, Local};
17 use rustc::mir::{NullOp, StatementKind, Statement, BasicBlock, LocalKind};
18 use rustc::mir::{TerminatorKind, ClearCrossCrate, SourceInfo, BinOp, ProjectionElem};
19 use rustc::mir::visit::{Visitor, PlaceContext};
20 use rustc::mir::interpret::{ConstVal, ConstEvalErr};
21 use rustc::ty::{TyCtxt, self, Instance};
22 use rustc::mir::interpret::{Value, Scalar, GlobalId, EvalResult};
23 use interpret::EvalContext;
24 use interpret::CompileTimeEvaluator;
25 use interpret::{eval_promoted, mk_borrowck_eval_cx, ValTy};
26 use transform::{MirPass, MirSource};
27 use syntax::codemap::{Span, DUMMY_SP};
28 use rustc::ty::subst::Substs;
29 use rustc_data_structures::indexed_vec::IndexVec;
30 use rustc::ty::ParamEnv;
31 use rustc::ty::layout::{
32 LayoutOf, TyLayout, LayoutError,
33 HasTyCtxt, TargetDataLayout, HasDataLayout,
38 impl MirPass for ConstProp {
39 fn run_pass<'a, 'tcx>(&self,
40 tcx: TyCtxt<'a, 'tcx, 'tcx>,
42 mir: &mut Mir<'tcx>) {
43 // will be evaluated by miri and produce its errors there
44 if source.promoted.is_some() {
47 match tcx.describe_def(source.def_id) {
48 // skip statics because they'll be evaluated by miri anyway
49 Some(Def::Static(..)) => return,
52 trace!("ConstProp starting for {:?}", source.def_id);
54 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
55 // constants, instead of just checking for const-folding succeeding.
56 // That would require an uniform one-def no-mutation analysis
57 // and RPO (or recursing when needing the value of a local).
58 let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
59 optimization_finder.visit_mir(mir);
61 trace!("ConstProp done for {:?}", source.def_id);
65 type Const<'tcx> = (Value, ty::Ty<'tcx>, Span);
67 /// Finds optimization opportunities on the MIR.
68 struct ConstPropagator<'b, 'a, 'tcx:'a+'b> {
69 ecx: EvalContext<'a, 'b, 'tcx, CompileTimeEvaluator>,
71 tcx: TyCtxt<'a, 'tcx, 'tcx>,
73 places: IndexVec<Local, Option<Const<'tcx>>>,
74 can_const_prop: IndexVec<Local, bool>,
75 param_env: ParamEnv<'tcx>,
78 impl<'a, 'b, 'tcx> LayoutOf for &'a ConstPropagator<'a, 'b, 'tcx> {
79 type Ty = ty::Ty<'tcx>;
80 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
82 fn layout_of(self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
83 self.tcx.layout_of(self.param_env.and(ty))
87 impl<'a, 'b, 'tcx> HasDataLayout for &'a ConstPropagator<'a, 'b, 'tcx> {
89 fn data_layout(&self) -> &TargetDataLayout {
94 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for &'a ConstPropagator<'a, 'b, 'tcx> {
96 fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
101 impl<'b, 'a, 'tcx:'b> ConstPropagator<'b, 'a, 'tcx> {
104 tcx: TyCtxt<'a, 'tcx, 'tcx>,
106 ) -> ConstPropagator<'b, 'a, 'tcx> {
107 let param_env = tcx.param_env(source.def_id);
108 let substs = Substs::identity_for_item(tcx, source.def_id);
109 let instance = Instance::new(source.def_id, substs);
110 let ecx = mk_borrowck_eval_cx(tcx, instance, mir, DUMMY_SP).unwrap();
117 can_const_prop: CanConstProp::check(mir),
118 places: IndexVec::from_elem(None, &mir.local_decls),
124 source_info: SourceInfo,
128 F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
130 self.ecx.tcx.span = source_info.span;
131 let lint_root = match self.mir.source_scope_local_data {
132 ClearCrossCrate::Set(ref ivs) => {
133 use rustc_data_structures::indexed_vec::Idx;
134 //FIXME(#51314): remove this check
135 if source_info.scope.index() >= ivs.len() {
138 ivs[source_info.scope].lint_root
140 ClearCrossCrate::Clear => return None,
142 let r = match f(self) {
143 Ok(val) => Some(val),
145 let (frames, span) = self.ecx.generate_stacktrace(None);
146 let err = ConstEvalErr {
153 "this expression will panic at runtime",
159 self.ecx.tcx.span = DUMMY_SP;
163 fn const_eval(&mut self, cid: GlobalId<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
164 let value = match self.tcx.const_eval(self.param_env.and(cid)) {
168 self.tcx.at(err.span),
169 "constant evaluation error",
174 let val = match value.val {
175 ConstVal::Value(v) => {
176 self.use_ecx(source_info, |this| this.ecx.const_value_to_value(v, value.ty))?
178 _ => bug!("eval produced: {:?}", value),
180 let val = (val, value.ty, source_info.span);
181 trace!("evaluated {:?} to {:?}", cid, val);
188 source_info: SourceInfo,
189 ) -> Option<Const<'tcx>> {
191 Literal::Value { value } => match value.val {
192 ConstVal::Value(v) => {
193 let v = self.use_ecx(source_info, |this| {
194 this.ecx.const_value_to_value(v, value.ty)
196 Some((v, value.ty, c.span))
198 ConstVal::Unevaluated(did, substs) => {
199 let instance = Instance::resolve(
209 self.const_eval(cid, source_info)
212 // evaluate the promoted and replace the constant with the evaluated result
213 Literal::Promoted { index } => {
214 let generics = self.tcx.generics_of(self.source.def_id);
215 if generics.requires_monomorphization(self.tcx) {
216 // FIXME: can't handle code with generics
219 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
220 let instance = Instance::new(self.source.def_id, substs);
223 promoted: Some(index),
225 // cannot use `const_eval` here, because that would require having the MIR
226 // for the current function available, but we're producing said MIR right now
227 let (value, _, ty) = self.use_ecx(source_info, |this| {
228 eval_promoted(&mut this.ecx, cid, this.mir, this.param_env)
230 let val = (value, ty, c.span);
231 trace!("evaluated {:?} to {:?}", c, val);
237 fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
239 Place::Local(loc) => self.places[loc].clone(),
240 Place::Projection(ref proj) => match proj.elem {
241 ProjectionElem::Field(field, _) => {
242 trace!("field proj on {:?}", proj.base);
243 let (base, ty, span) = self.eval_place(&proj.base, source_info)?;
244 let valty = self.use_ecx(source_info, |this| {
245 this.ecx.read_field(base, None, field, ty)
247 Some((valty.value, valty.ty, span))
255 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
257 Operand::Constant(ref c) => self.eval_constant(c, source_info),
258 | Operand::Move(ref place)
259 | Operand::Copy(ref place) => self.eval_place(place, source_info),
265 rvalue: &Rvalue<'tcx>,
266 place_ty: ty::Ty<'tcx>,
267 source_info: SourceInfo,
268 ) -> Option<Const<'tcx>> {
269 let span = source_info.span;
271 // This branch exists for the sanity type check
272 Rvalue::Use(Operand::Constant(ref c)) => {
273 assert_eq!(c.ty, place_ty);
274 self.eval_constant(c, source_info)
276 Rvalue::Use(ref op) => {
277 self.eval_operand(op, source_info)
282 Rvalue::Aggregate(..) |
283 Rvalue::NullaryOp(NullOp::Box, _) |
284 Rvalue::Discriminant(..) => None,
285 // FIXME(oli-obk): evaluate static/constant slice lengths
286 Rvalue::Len(_) => None,
287 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
288 let param_env = self.tcx.param_env(self.source.def_id);
289 type_size_of(self.tcx, param_env, ty).map(|n| (
290 Value::Scalar(Scalar::Bits {
292 defined: self.tcx.data_layout.pointer_size.bits() as u8,
294 self.tcx.types.usize,
298 Rvalue::UnaryOp(op, ref arg) => {
299 let def_id = if self.tcx.is_closure(self.source.def_id) {
300 self.tcx.closure_base_def_id(self.source.def_id)
304 let generics = self.tcx.generics_of(def_id);
305 if generics.requires_monomorphization(self.tcx) {
306 // FIXME: can't handle code with generics
310 let val = self.eval_operand(arg, source_info)?;
311 let prim = self.use_ecx(source_info, |this| {
312 this.ecx.value_to_scalar(ValTy { value: val.0, ty: val.1 })
314 let val = self.use_ecx(source_info, |this| this.ecx.unary_op(op, prim, val.1))?;
315 Some((Value::Scalar(val), place_ty, span))
317 Rvalue::CheckedBinaryOp(op, ref left, ref right) |
318 Rvalue::BinaryOp(op, ref left, ref right) => {
319 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
320 let right = self.eval_operand(right, source_info)?;
321 let def_id = if self.tcx.is_closure(self.source.def_id) {
322 self.tcx.closure_base_def_id(self.source.def_id)
326 let generics = self.tcx.generics_of(def_id);
327 if generics.requires_monomorphization(self.tcx) {
328 // FIXME: can't handle code with generics
332 let r = self.use_ecx(source_info, |this| {
333 this.ecx.value_to_scalar(ValTy { value: right.0, ty: right.1 })
335 if op == BinOp::Shr || op == BinOp::Shl {
336 let left_ty = left.ty(self.mir, self.tcx);
339 .layout_of(self.param_env.and(left_ty))
343 let right_size = self.tcx.layout_of(self.param_env.and(right.1)).unwrap().size;
344 if r.to_bits(right_size).ok().map_or(false, |b| b >= left_bits as u128) {
345 let source_scope_local_data = match self.mir.source_scope_local_data {
346 ClearCrossCrate::Set(ref data) => data,
347 ClearCrossCrate::Clear => return None,
349 let dir = if op == BinOp::Shr {
354 let node_id = source_scope_local_data[source_info.scope].lint_root;
356 ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
359 &format!("attempt to shift {} with overflow", dir));
363 let left = self.eval_operand(left, source_info)?;
364 let l = self.use_ecx(source_info, |this| {
365 this.ecx.value_to_scalar(ValTy { value: left.0, ty: left.1 })
367 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
368 let (val, overflow) = self.use_ecx(source_info, |this| {
369 this.ecx.binary_op(op, l, left.1, r, right.1)
371 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
374 Scalar::from_bool(overflow),
378 use rustc::mir::interpret::EvalErrorKind;
379 let err = EvalErrorKind::Overflow(op).into();
380 let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
385 Some((val, place_ty, span))
391 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
392 param_env: ty::ParamEnv<'tcx>,
393 ty: ty::Ty<'tcx>) -> Option<u64> {
394 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
397 struct CanConstProp {
398 can_const_prop: IndexVec<Local, bool>,
399 // false at the beginning, once set, there are not allowed to be any more assignments
400 found_assignment: IndexVec<Local, bool>,
404 /// returns true if `local` can be propagated
405 fn check(mir: &Mir) -> IndexVec<Local, bool> {
406 let mut cpv = CanConstProp {
407 can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
408 found_assignment: IndexVec::from_elem(false, &mir.local_decls),
410 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
411 // cannot use args at all
412 // cannot use locals because if x < y { y - x } else { x - y } would
414 // FIXME(oli-obk): lint variables until they are used in a condition
415 // FIXME(oli-obk): lint if return value is constant
416 *val = mir.local_kind(local) == LocalKind::Temp;
423 impl<'tcx> Visitor<'tcx> for CanConstProp {
427 context: PlaceContext<'tcx>,
430 use rustc::mir::visit::PlaceContext::*;
432 // Constants must have at most one write
433 // FIXME(oli-obk): we could be more powerful here, if the multiple writes
434 // only occur in independent execution paths
435 Store => if self.found_assignment[local] {
436 self.can_const_prop[local] = false;
438 self.found_assignment[local] = true
440 // Reading constants is allowed an arbitrary number of times
442 StorageDead | StorageLive |
446 _ => self.can_const_prop[local] = false,
451 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
454 constant: &Constant<'tcx>,
457 trace!("visit_constant: {:?}", constant);
458 self.super_constant(constant, location);
459 let source_info = *self.mir.source_info(location);
460 self.eval_constant(constant, source_info);
466 statement: &Statement<'tcx>,
469 trace!("visit_statement: {:?}", statement);
470 if let StatementKind::Assign(ref place, ref rval) = statement.kind {
472 .ty(&self.mir.local_decls, self.tcx)
474 if let Some(value) = self.const_prop(rval, place_ty, statement.source_info) {
475 if let Place::Local(local) = *place {
476 trace!("checking whether {:?} can be stored to {:?}", value, local);
477 if self.can_const_prop[local] {
478 trace!("storing {:?} to {:?}", value, local);
479 assert!(self.places[local].is_none());
480 self.places[local] = Some(value);
485 self.super_statement(block, statement, location);
488 fn visit_terminator_kind(
491 kind: &TerminatorKind<'tcx>,
494 self.super_terminator_kind(block, kind, location);
495 let source_info = *self.mir.source_info(location);
496 if let TerminatorKind::Assert { expected, msg, cond, .. } = kind {
497 if let Some(value) = self.eval_operand(cond, source_info) {
498 trace!("assertion on {:?} should be {:?}", value, expected);
499 if Value::Scalar(Scalar::from_bool(*expected)) != value.0 {
500 // poison all places this operand references so that further code
501 // doesn't use the invalid value
503 Operand::Move(ref place) | Operand::Copy(ref place) => {
504 let mut place = place;
505 while let Place::Projection(ref proj) = *place {
508 if let Place::Local(local) = *place {
509 self.places[local] = None;
512 Operand::Constant(_) => {}
514 let span = self.mir[block]
523 .as_local_node_id(self.source.def_id)
524 .expect("some part of a failing const eval must be local");
525 use rustc::mir::interpret::EvalErrorKind::*;
526 let msg = match msg {
530 RemainderByZero => msg.description().to_owned(),
531 BoundsCheck { ref len, ref index } => {
533 .eval_operand(len, source_info)
534 .expect("len must be const");
535 let len = match len.0 {
536 Value::Scalar(Scalar::Bits { bits, ..}) => bits,
537 _ => bug!("const len not primitive: {:?}", len),
540 .eval_operand(index, source_info)
541 .expect("index must be const");
542 let index = match index.0 {
543 Value::Scalar(Scalar::Bits { bits, .. }) => bits,
544 _ => bug!("const index not primitive: {:?}", index),
547 "index out of bounds: \
548 the len is {} but the index is {}",
553 // Need proper const propagator for these
557 ::rustc::lint::builtin::CONST_ERR,