]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Auto merge of #63269 - Aaron1011:feature/proc-macro-data, r=eddyb,petrochenkov
[rust.git] / src / librustc_mir / transform / const_prop.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4 use std::cell::Cell;
5
6 use rustc::hir::def::DefKind;
7 use rustc::mir::{
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, Promoted,
12 };
13 use rustc::mir::visit::{
14     Visitor, PlaceContext, MutatingUseContext, MutVisitor, NonMutatingUseContext,
15 };
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,
23 };
24
25 use crate::interpret::{
26     self, InterpCx, ScalarMaybeUndef, Immediate, OpTy,
27     ImmTy, MemoryKind, StackPopCleanup, LocalValue, LocalState,
28 };
29 use crate::const_eval::{
30     CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_eval_cx,
31 };
32 use crate::transform::{MirPass, MirSource};
33
34 pub struct ConstProp;
35
36 impl MirPass for ConstProp {
37     fn run_pass<'tcx>(&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() {
40             return;
41         }
42
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");
46
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,
50             _ => false,
51         };
52
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());
57             return
58         }
59
60         trace!("ConstProp starting for {:?}", source.def_id());
61
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
66         );
67         let promoted = std::mem::replace(
68             &mut body.promoted,
69             IndexVec::new()
70         );
71
72         let dummy_body =
73             &Body::new(
74                 body.basic_blocks().clone(),
75                 Default::default(),
76                 ClearCrossCrate::Clear,
77                 Default::default(),
78                 None,
79                 body.local_decls.clone(),
80                 Default::default(),
81                 body.arg_count,
82                 Default::default(),
83                 tcx.def_span(source.def_id()),
84                 Default::default(),
85             );
86
87         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
88         // constants, instead of just checking for const-folding succeeding.
89         // That would require an uniform one-def no-mutation analysis
90         // and RPO (or recursing when needing the value of a local).
91         let mut optimization_finder = ConstPropagator::new(
92             body,
93             dummy_body,
94             source_scope_local_data,
95             promoted,
96             tcx,
97             source
98         );
99         optimization_finder.visit_body(body);
100
101         // put back the data we stole from `mir`
102         let (source_scope_local_data, promoted) = optimization_finder.release_stolen_data();
103         std::mem::replace(
104             &mut body.source_scope_local_data,
105             source_scope_local_data
106         );
107         std::mem::replace(
108             &mut body.promoted,
109             promoted
110         );
111
112         trace!("ConstProp done for {:?}", source.def_id());
113     }
114 }
115
116 type Const<'tcx> = OpTy<'tcx>;
117
118 /// Finds optimization opportunities on the MIR.
119 struct ConstPropagator<'mir, 'tcx> {
120     ecx: InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>,
121     tcx: TyCtxt<'tcx>,
122     source: MirSource<'tcx>,
123     can_const_prop: IndexVec<Local, bool>,
124     param_env: ParamEnv<'tcx>,
125     source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
126     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
127     promoted: IndexVec<Promoted, Body<'tcx>>,
128 }
129
130 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
131     type Ty = Ty<'tcx>;
132     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
133
134     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
135         self.tcx.layout_of(self.param_env.and(ty))
136     }
137 }
138
139 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
140     #[inline]
141     fn data_layout(&self) -> &TargetDataLayout {
142         &self.tcx.data_layout
143     }
144 }
145
146 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
147     #[inline]
148     fn tcx(&self) -> TyCtxt<'tcx> {
149         self.tcx
150     }
151 }
152
153 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
154     fn new(
155         body: &Body<'tcx>,
156         dummy_body: &'mir Body<'tcx>,
157         source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
158         promoted: IndexVec<Promoted, Body<'tcx>>,
159         tcx: TyCtxt<'tcx>,
160         source: MirSource<'tcx>,
161     ) -> ConstPropagator<'mir, 'tcx> {
162         let def_id = source.def_id();
163         let param_env = tcx.param_env(def_id);
164         let span = tcx.def_span(def_id);
165         let mut ecx = mk_eval_cx(tcx, span, param_env);
166         let can_const_prop = CanConstProp::check(body);
167
168         ecx.push_stack_frame(
169             Instance::new(def_id, &InternalSubsts::identity_for_item(tcx, def_id)),
170             span,
171             dummy_body,
172             None,
173             StackPopCleanup::None {
174                 cleanup: false,
175             },
176         ).expect("failed to push initial stack frame");
177
178         ConstPropagator {
179             ecx,
180             tcx,
181             source,
182             param_env,
183             can_const_prop,
184             source_scope_local_data,
185             //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
186             local_decls: body.local_decls.clone(),
187             promoted,
188         }
189     }
190
191     fn release_stolen_data(
192         self,
193     ) -> (
194         ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
195         IndexVec<Promoted, Body<'tcx>>,
196     ) {
197         (self.source_scope_local_data, self.promoted)
198     }
199
200     fn get_const(&self, local: Local) -> Option<Const<'tcx>> {
201         let l = &self.ecx.frame().locals[local];
202
203         // If the local is `Unitialized` or `Dead` then we haven't propagated a value into it.
204         //
205         // `InterpCx::access_local()` mostly takes care of this for us however, for ZSTs,
206         // it will synthesize a value for us. In doing so, that will cause the
207         // `get_const(l).is_empty()` assert right before we call `set_const()` in `visit_statement`
208         // to fail.
209         if let LocalValue::Uninitialized | LocalValue::Dead = l.value {
210             return None;
211         }
212
213         self.ecx.access_local(self.ecx.frame(), local, None).ok()
214     }
215
216     fn set_const(&mut self, local: Local, c: Const<'tcx>) {
217         let frame = self.ecx.frame_mut();
218
219         if let Some(layout) = frame.locals[local].layout.get() {
220             debug_assert_eq!(c.layout, layout);
221         }
222
223         frame.locals[local] = LocalState {
224             value: LocalValue::Live(*c),
225             layout: Cell::new(Some(c.layout)),
226         };
227     }
228
229     fn remove_const(&mut self, local: Local) {
230         self.ecx.frame_mut().locals[local] = LocalState {
231             value: LocalValue::Uninitialized,
232             layout: Cell::new(None),
233         };
234     }
235
236     fn use_ecx<F, T>(
237         &mut self,
238         source_info: SourceInfo,
239         f: F
240     ) -> Option<T>
241     where
242         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
243     {
244         self.ecx.tcx.span = source_info.span;
245         let lint_root = match self.source_scope_local_data {
246             ClearCrossCrate::Set(ref ivs) => {
247                 //FIXME(#51314): remove this check
248                 if source_info.scope.index() >= ivs.len() {
249                     return None;
250                 }
251                 ivs[source_info.scope].lint_root
252             },
253             ClearCrossCrate::Clear => return None,
254         };
255         let r = match f(self) {
256             Ok(val) => Some(val),
257             Err(error) => {
258                 let diagnostic = error_to_const_error(&self.ecx, error);
259                 use rustc::mir::interpret::InterpError::*;
260                 match diagnostic.error {
261                     Exit(_) => bug!("the CTFE program cannot exit"),
262                     Unsupported(_)
263                     | UndefinedBehavior(_)
264                     | InvalidProgram(_)
265                     | ResourceExhaustion(_) => {
266                         // Ignore these errors.
267                     }
268                     Panic(_) => {
269                         diagnostic.report_as_lint(
270                             self.ecx.tcx,
271                             "this expression will panic at runtime",
272                             lint_root,
273                             None,
274                         );
275                     }
276                 }
277                 None
278             },
279         };
280         self.ecx.tcx.span = DUMMY_SP;
281         r
282     }
283
284     fn eval_constant(
285         &mut self,
286         c: &Constant<'tcx>,
287     ) -> Option<Const<'tcx>> {
288         self.ecx.tcx.span = c.span;
289         match self.ecx.eval_const_to_op(c.literal, None) {
290             Ok(op) => {
291                 Some(op)
292             },
293             Err(error) => {
294                 let err = error_to_const_error(&self.ecx, error);
295                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
296                 None
297             },
298         }
299     }
300
301     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
302         trace!("eval_place(place={:?})", place);
303         place.iterate(|place_base, place_projection| {
304             let mut eval = match place_base {
305                 PlaceBase::Local(loc) => self.get_const(*loc).clone()?,
306                 PlaceBase::Static(box Static {kind: StaticKind::Promoted(promoted), ..}) => {
307                     let generics = self.tcx.generics_of(self.source.def_id());
308                     if generics.requires_monomorphization(self.tcx) {
309                         // FIXME: can't handle code with generics
310                         return None;
311                     }
312                     let substs = InternalSubsts::identity_for_item(self.tcx, self.source.def_id());
313                     let instance = Instance::new(self.source.def_id(), substs);
314                     let cid = GlobalId {
315                         instance,
316                         promoted: Some(*promoted),
317                     };
318                     // cannot use `const_eval` here, because that would require having the MIR
319                     // for the current function available, but we're producing said MIR right now
320                     let res = self.use_ecx(source_info, |this| {
321                         let body = &this.promoted[*promoted];
322                         eval_promoted(this.tcx, cid, body, this.param_env)
323                     })?;
324                     trace!("evaluated promoted {:?} to {:?}", promoted, res);
325                     res.into()
326                 }
327                 _ => return None,
328             };
329
330             for proj in place_projection {
331                 match proj.elem {
332                     ProjectionElem::Field(field, _) => {
333                         trace!("field proj on {:?}", proj.base);
334                         eval = self.use_ecx(source_info, |this| {
335                             this.ecx.operand_field(eval, field.index() as u64)
336                         })?;
337                     },
338                     ProjectionElem::Deref => {
339                         trace!("processing deref");
340                         eval = self.use_ecx(source_info, |this| {
341                             this.ecx.deref_operand(eval)
342                         })?.into();
343                     }
344                     // We could get more projections by using e.g., `operand_projection`,
345                     // but we do not even have the stack frame set up properly so
346                     // an `Index` projection would throw us off-track.
347                     _ => return None,
348                 }
349             }
350
351             Some(eval)
352         })
353     }
354
355     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
356         match *op {
357             Operand::Constant(ref c) => self.eval_constant(c),
358             | Operand::Move(ref place)
359             | Operand::Copy(ref place) => self.eval_place(place, source_info),
360         }
361     }
362
363     fn const_prop(
364         &mut self,
365         rvalue: &Rvalue<'tcx>,
366         place_layout: TyLayout<'tcx>,
367         source_info: SourceInfo,
368     ) -> Option<Const<'tcx>> {
369         let span = source_info.span;
370         match *rvalue {
371             Rvalue::Use(ref op) => {
372                 self.eval_operand(op, source_info)
373             },
374             Rvalue::Ref(_, _, ref place) => {
375                 let src = self.eval_place(place, source_info)?;
376                 let mplace = src.try_as_mplace().ok()?;
377                 Some(ImmTy::from_scalar(mplace.ptr.into(), place_layout).into())
378             },
379             Rvalue::Repeat(..) |
380             Rvalue::Aggregate(..) |
381             Rvalue::NullaryOp(NullOp::Box, _) |
382             Rvalue::Discriminant(..) => None,
383
384             Rvalue::Cast(kind, ref operand, _) => {
385                 let op = self.eval_operand(operand, source_info)?;
386                 self.use_ecx(source_info, |this| {
387                     let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
388                     this.ecx.cast(op, kind, dest.into())?;
389                     Ok(dest.into())
390                 })
391             },
392             Rvalue::Len(ref place) => {
393                 let place = self.eval_place(&place, source_info)?;
394                 let mplace = place.try_as_mplace().ok()?;
395
396                 if let ty::Slice(_) = mplace.layout.ty.sty {
397                     let len = mplace.meta.unwrap().to_usize(&self.ecx).unwrap();
398
399                     Some(ImmTy::from_uint(
400                         len,
401                         self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
402                     ).into())
403                 } else {
404                     trace!("not slice: {:?}", mplace.layout.ty.sty);
405                     None
406                 }
407             },
408             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
409                 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some(
410                     ImmTy::from_uint(
411                         n,
412                         self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
413                     ).into()
414                 ))
415             }
416             Rvalue::UnaryOp(op, ref arg) => {
417                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
418                     self.tcx.closure_base_def_id(self.source.def_id())
419                 } else {
420                     self.source.def_id()
421                 };
422                 let generics = self.tcx.generics_of(def_id);
423                 if generics.requires_monomorphization(self.tcx) {
424                     // FIXME: can't handle code with generics
425                     return None;
426                 }
427
428                 let arg = self.eval_operand(arg, source_info)?;
429                 let val = self.use_ecx(source_info, |this| {
430                     let prim = this.ecx.read_immediate(arg)?;
431                     match op {
432                         UnOp::Neg => {
433                             // Need to do overflow check here: For actual CTFE, MIR
434                             // generation emits code that does this before calling the op.
435                             if prim.to_bits()? == (1 << (prim.layout.size.bits() - 1)) {
436                                 throw_panic!(OverflowNeg)
437                             }
438                         }
439                         UnOp::Not => {
440                             // Cannot overflow
441                         }
442                     }
443                     // Now run the actual operation.
444                     this.ecx.unary_op(op, prim)
445                 })?;
446                 Some(val.into())
447             }
448             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
449             Rvalue::BinaryOp(op, ref left, ref right) => {
450                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
451                 let right = self.eval_operand(right, source_info)?;
452                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
453                     self.tcx.closure_base_def_id(self.source.def_id())
454                 } else {
455                     self.source.def_id()
456                 };
457                 let generics = self.tcx.generics_of(def_id);
458                 if generics.requires_monomorphization(self.tcx) {
459                     // FIXME: can't handle code with generics
460                     return None;
461                 }
462
463                 let r = self.use_ecx(source_info, |this| {
464                     this.ecx.read_immediate(right)
465                 })?;
466                 if op == BinOp::Shr || op == BinOp::Shl {
467                     let left_ty = left.ty(&self.local_decls, self.tcx);
468                     let left_bits = self
469                         .tcx
470                         .layout_of(self.param_env.and(left_ty))
471                         .unwrap()
472                         .size
473                         .bits();
474                     let right_size = right.layout.size;
475                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
476                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
477                         let source_scope_local_data = match self.source_scope_local_data {
478                             ClearCrossCrate::Set(ref data) => data,
479                             ClearCrossCrate::Clear => return None,
480                         };
481                         let dir = if op == BinOp::Shr {
482                             "right"
483                         } else {
484                             "left"
485                         };
486                         let hir_id = source_scope_local_data[source_info.scope].lint_root;
487                         self.tcx.lint_hir(
488                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
489                             hir_id,
490                             span,
491                             &format!("attempt to shift {} with overflow", dir));
492                         return None;
493                     }
494                 }
495                 let left = self.eval_operand(left, source_info)?;
496                 let l = self.use_ecx(source_info, |this| {
497                     this.ecx.read_immediate(left)
498                 })?;
499                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
500                 let (val, overflow, _ty) = self.use_ecx(source_info, |this| {
501                     this.ecx.overflowing_binary_op(op, l, r)
502                 })?;
503                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
504                     Immediate::ScalarPair(
505                         val.into(),
506                         Scalar::from_bool(overflow).into(),
507                     )
508                 } else {
509                     if overflow {
510                         let err = err_panic!(Overflow(op)).into();
511                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
512                         return None;
513                     }
514                     Immediate::Scalar(val.into())
515                 };
516                 let res = ImmTy {
517                     imm: val,
518                     layout: place_layout,
519                 };
520                 Some(res.into())
521             },
522         }
523     }
524
525     fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
526         Operand::Constant(Box::new(
527             Constant {
528                 span,
529                 user_ty: None,
530                 literal: self.tcx.mk_const(*ty::Const::from_scalar(
531                     self.tcx,
532                     scalar,
533                     ty,
534                 ))
535             }
536         ))
537     }
538
539     fn replace_with_const(
540         &mut self,
541         rval: &mut Rvalue<'tcx>,
542         value: Const<'tcx>,
543         source_info: SourceInfo,
544     ) {
545         trace!("attepting to replace {:?} with {:?}", rval, value);
546         if let Err(e) = self.ecx.validate_operand(
547             value,
548             vec![],
549             // FIXME: is ref tracking too expensive?
550             Some(&mut interpret::RefTracking::empty()),
551         ) {
552             trace!("validation error, attempt failed: {:?}", e);
553             return;
554         }
555
556         // FIXME> figure out what tho do when try_read_immediate fails
557         let imm = self.use_ecx(source_info, |this| {
558             this.ecx.try_read_immediate(value)
559         });
560
561         if let Some(Ok(imm)) = imm {
562             match *imm {
563                 interpret::Immediate::Scalar(ScalarMaybeUndef::Scalar(scalar)) => {
564                     *rval = Rvalue::Use(
565                         self.operand_from_scalar(scalar, value.layout.ty, source_info.span));
566                 },
567                 Immediate::ScalarPair(
568                     ScalarMaybeUndef::Scalar(one),
569                     ScalarMaybeUndef::Scalar(two)
570                 ) => {
571                     let ty = &value.layout.ty.sty;
572                     if let ty::Tuple(substs) = ty {
573                         *rval = Rvalue::Aggregate(
574                             Box::new(AggregateKind::Tuple),
575                             vec![
576                                 self.operand_from_scalar(
577                                     one, substs[0].expect_ty(), source_info.span
578                                 ),
579                                 self.operand_from_scalar(
580                                     two, substs[1].expect_ty(), source_info.span
581                                 ),
582                             ],
583                         );
584                     }
585                 },
586                 _ => { }
587             }
588         }
589     }
590
591     fn should_const_prop(&self) -> bool {
592         self.tcx.sess.opts.debugging_opts.mir_opt_level >= 2
593     }
594 }
595
596 fn type_size_of<'tcx>(
597     tcx: TyCtxt<'tcx>,
598     param_env: ty::ParamEnv<'tcx>,
599     ty: Ty<'tcx>,
600 ) -> Option<u64> {
601     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
602 }
603
604 struct CanConstProp {
605     can_const_prop: IndexVec<Local, bool>,
606     // false at the beginning, once set, there are not allowed to be any more assignments
607     found_assignment: IndexVec<Local, bool>,
608 }
609
610 impl CanConstProp {
611     /// returns true if `local` can be propagated
612     fn check(body: &Body<'_>) -> IndexVec<Local, bool> {
613         let mut cpv = CanConstProp {
614             can_const_prop: IndexVec::from_elem(true, &body.local_decls),
615             found_assignment: IndexVec::from_elem(false, &body.local_decls),
616         };
617         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
618             // cannot use args at all
619             // cannot use locals because if x < y { y - x } else { x - y } would
620             //        lint for x != y
621             // FIXME(oli-obk): lint variables until they are used in a condition
622             // FIXME(oli-obk): lint if return value is constant
623             *val = body.local_kind(local) == LocalKind::Temp;
624
625             if !*val {
626                 trace!("local {:?} can't be propagated because it's not a temporary", local);
627             }
628         }
629         cpv.visit_body(body);
630         cpv.can_const_prop
631     }
632 }
633
634 impl<'tcx> Visitor<'tcx> for CanConstProp {
635     fn visit_local(
636         &mut self,
637         &local: &Local,
638         context: PlaceContext,
639         _: Location,
640     ) {
641         use rustc::mir::visit::PlaceContext::*;
642         match context {
643             // Constants must have at most one write
644             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
645             // only occur in independent execution paths
646             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
647                 trace!("local {:?} can't be propagated because of multiple assignments", local);
648                 self.can_const_prop[local] = false;
649             } else {
650                 self.found_assignment[local] = true
651             },
652             // Reading constants is allowed an arbitrary number of times
653             NonMutatingUse(NonMutatingUseContext::Copy) |
654             NonMutatingUse(NonMutatingUseContext::Move) |
655             NonMutatingUse(NonMutatingUseContext::Inspect) |
656             NonMutatingUse(NonMutatingUseContext::Projection) |
657             MutatingUse(MutatingUseContext::Projection) |
658             NonUse(_) => {},
659             _ => {
660                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
661                 self.can_const_prop[local] = false;
662             },
663         }
664     }
665 }
666
667 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
668     fn visit_constant(
669         &mut self,
670         constant: &mut Constant<'tcx>,
671         location: Location,
672     ) {
673         trace!("visit_constant: {:?}", constant);
674         self.super_constant(constant, location);
675         self.eval_constant(constant);
676     }
677
678     fn visit_statement(
679         &mut self,
680         statement: &mut Statement<'tcx>,
681         location: Location,
682     ) {
683         trace!("visit_statement: {:?}", statement);
684         if let StatementKind::Assign(ref place, ref mut rval) = statement.kind {
685             let place_ty: Ty<'tcx> = place
686                 .ty(&self.local_decls, self.tcx)
687                 .ty;
688             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
689                 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
690                     if let Place {
691                         base: PlaceBase::Local(local),
692                         projection: None,
693                     } = *place {
694                         trace!("checking whether {:?} can be stored to {:?}", value, local);
695                         if self.can_const_prop[local] {
696                             trace!("storing {:?} to {:?}", value, local);
697                             assert!(self.get_const(local).is_none());
698                             self.set_const(local, value);
699
700                             if self.should_const_prop() {
701                                 self.replace_with_const(
702                                     rval,
703                                     value,
704                                     statement.source_info,
705                                 );
706                             }
707                         }
708                     }
709                 }
710             }
711         }
712         self.super_statement(statement, location);
713     }
714
715     fn visit_terminator(
716         &mut self,
717         terminator: &mut Terminator<'tcx>,
718         location: Location,
719     ) {
720         self.super_terminator(terminator, location);
721         let source_info = terminator.source_info;
722         match &mut terminator.kind {
723             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
724                 if let Some(value) = self.eval_operand(&cond, source_info) {
725                     trace!("assertion on {:?} should be {:?}", value, expected);
726                     let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
727                     let value_const = self.ecx.read_scalar(value).unwrap();
728                     if expected != value_const {
729                         // poison all places this operand references so that further code
730                         // doesn't use the invalid value
731                         match cond {
732                             Operand::Move(ref place) | Operand::Copy(ref place) => {
733                                 if let PlaceBase::Local(local) = place.base {
734                                     self.remove_const(local);
735                                 }
736                             },
737                             Operand::Constant(_) => {}
738                         }
739                         let span = terminator.source_info.span;
740                         let hir_id = self
741                             .tcx
742                             .hir()
743                             .as_local_hir_id(self.source.def_id())
744                             .expect("some part of a failing const eval must be local");
745                         let msg = match msg {
746                             PanicInfo::Overflow(_) |
747                             PanicInfo::OverflowNeg |
748                             PanicInfo::DivisionByZero |
749                             PanicInfo::RemainderByZero =>
750                                 msg.description().to_owned(),
751                             PanicInfo::BoundsCheck { ref len, ref index } => {
752                                 let len = self
753                                     .eval_operand(len, source_info)
754                                     .expect("len must be const");
755                                 let len = match self.ecx.read_scalar(len) {
756                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
757                                         data, ..
758                                     })) => data,
759                                     other => bug!("const len not primitive: {:?}", other),
760                                 };
761                                 let index = self
762                                     .eval_operand(index, source_info)
763                                     .expect("index must be const");
764                                 let index = match self.ecx.read_scalar(index) {
765                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
766                                         data, ..
767                                     })) => data,
768                                     other => bug!("const index not primitive: {:?}", other),
769                                 };
770                                 format!(
771                                     "index out of bounds: \
772                                     the len is {} but the index is {}",
773                                     len,
774                                     index,
775                                 )
776                             },
777                             // Need proper const propagator for these
778                             _ => return,
779                         };
780                         self.tcx.lint_hir(
781                             ::rustc::lint::builtin::CONST_ERR,
782                             hir_id,
783                             span,
784                             &msg,
785                         );
786                     } else {
787                         if self.should_const_prop() {
788                             if let ScalarMaybeUndef::Scalar(scalar) = value_const {
789                                 *cond = self.operand_from_scalar(
790                                     scalar,
791                                     self.tcx.types.bool,
792                                     source_info.span,
793                                 );
794                             }
795                         }
796                     }
797                 }
798             },
799             TerminatorKind::SwitchInt { ref mut discr, switch_ty, .. } => {
800                 if self.should_const_prop() {
801                     if let Some(value) = self.eval_operand(&discr, source_info) {
802                         if let ScalarMaybeUndef::Scalar(scalar) =
803                                 self.ecx.read_scalar(value).unwrap() {
804                             *discr = self.operand_from_scalar(scalar, switch_ty, source_info.span);
805                         }
806                     }
807                 }
808             },
809             //none of these have Operands to const-propagate
810             TerminatorKind::Goto { .. } |
811             TerminatorKind::Resume |
812             TerminatorKind::Abort |
813             TerminatorKind::Return |
814             TerminatorKind::Unreachable |
815             TerminatorKind::Drop { .. } |
816             TerminatorKind::DropAndReplace { .. } |
817             TerminatorKind::Yield { .. } |
818             TerminatorKind::GeneratorDrop |
819             TerminatorKind::FalseEdges { .. } |
820             TerminatorKind::FalseUnwind { .. } => { }
821             //FIXME(wesleywiser) Call does have Operands that could be const-propagated
822             TerminatorKind::Call { .. } => { }
823         }
824     }
825 }