]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Auto merge of #56962 - nivkner:fixme_fixup4, r=pnkfelix
[rust.git] / src / librustc_mir / transform / const_prop.rs
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.
4 //
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.
10
11 //! Propagates constants for early reporting of statically known
12 //! assertion failures
13
14
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,
29 };
30
31 use interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind};
32 use const_eval::{
33     CompileTimeInterpreter, const_to_op, error_to_const_error, eval_promoted, mk_borrowck_eval_cx
34 };
35 use transform::{MirPass, MirSource};
36
37 pub struct ConstProp;
38
39 impl MirPass for ConstProp {
40     fn run_pass<'a, 'tcx>(&self,
41                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
42                           source: MirSource,
43                           mir: &mut Mir<'tcx>) {
44         // will be evaluated by miri and produce its errors there
45         if source.promoted.is_some() {
46             return;
47         }
48
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");
52
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,
56             _ => false,
57         };
58
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);
63             return
64         }
65
66         trace!("ConstProp starting for {:?}", source.def_id);
67
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);
74
75         trace!("ConstProp done for {:?}", source.def_id);
76     }
77 }
78
79 type Const<'tcx> = (OpTy<'tcx>, Span);
80
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>>,
84     mir: &'mir Mir<'tcx>,
85     tcx: TyCtxt<'a, 'tcx, 'tcx>,
86     source: MirSource,
87     places: IndexVec<Local, Option<Const<'tcx>>>,
88     can_const_prop: IndexVec<Local, bool>,
89     param_env: ParamEnv<'tcx>,
90 }
91
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>>;
95
96     fn layout_of(&self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
97         self.tcx.layout_of(self.param_env.and(ty))
98     }
99 }
100
101 impl<'a, 'b, 'tcx> HasDataLayout for ConstPropagator<'a, 'b, 'tcx> {
102     #[inline]
103     fn data_layout(&self) -> &TargetDataLayout {
104         &self.tcx.data_layout
105     }
106 }
107
108 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'a, 'b, 'tcx> {
109     #[inline]
110     fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
111         self.tcx
112     }
113 }
114
115 impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> {
116     fn new(
117         mir: &'mir Mir<'tcx>,
118         tcx: TyCtxt<'a, 'tcx, 'tcx>,
119         source: MirSource,
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();
125         ConstPropagator {
126             ecx,
127             mir,
128             tcx,
129             source,
130             param_env,
131             can_const_prop: CanConstProp::check(mir),
132             places: IndexVec::from_elem(None, &mir.local_decls),
133         }
134     }
135
136     fn use_ecx<F, T>(
137         &mut self,
138         source_info: SourceInfo,
139         f: F
140     ) -> Option<T>
141     where
142         F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
143     {
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() {
149                     return None;
150                 }
151                 ivs[source_info.scope].lint_root
152             },
153             ClearCrossCrate::Clear => return None,
154         };
155         let r = match f(self) {
156             Ok(val) => Some(val),
157             Err(error) => {
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
162                     | MachineError(_)
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
170                     | ReadBytesAsPointer
171                     // fine at runtime
172                     | ReadForeignStatic
173                     | Unimplemented(_)
174                     // don't report const evaluator limits
175                     | StackFrameLimitReached
176                     | NoMirFor(..)
177                     | InlineAsm
178                     => {},
179
180                     | InvalidMemoryAccess
181                     | DanglingPointerDeref
182                     | DoubleFree
183                     | InvalidFunctionPointer
184                     | InvalidBool
185                     | InvalidDiscriminant(..)
186                     | PointerOutOfBounds { .. }
187                     | InvalidNullPointerUsage
188                     | ValidationFailure(..)
189                     | InvalidPointerMath
190                     | ReadUndefBytes(_)
191                     | DeadLocal
192                     | InvalidBoolOp(_)
193                     | DerefFunctionPointer
194                     | ExecuteMemory
195                     | Intrinsic(..)
196                     | InvalidChar(..)
197                     | AbiViolation(_)
198                     | AlignmentCheckFailed{..}
199                     | CalledClosureAsFunction
200                     | VtableForArgumentlessMethod
201                     | ModifiedConstantMemory
202                     | ModifiedStatic
203                     | AssumptionNotHeld
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(_)
212                     | HeapAllocZeroBytes
213                     | HeapAllocNonPowerOfTwoAlignment(_)
214                     | Unreachable
215                     | ReadFromReturnPointer
216                     | GeneratorResumedAfterReturn
217                     | GeneratorResumedAfterPanic
218                     | ReferencedConstant
219                     | InfiniteLoop
220                     => {
221                         // FIXME: report UB here
222                     },
223
224                     | OutOfTls
225                     | TlsOutOfBounds
226                     | PathNotFound(_)
227                     => bug!("these should not be in rustc, but in miri's machine errors"),
228
229                     | Layout(_)
230                     | UnimplementedTraitSelection
231                     | TypeckError
232                     | TooGeneric
233                     // these are just noise
234                     => {},
235
236                     // non deterministic
237                     | ReadPointerAsBytes
238                     // FIXME: implement
239                     => {},
240
241                     | Panic { .. }
242                     | BoundsCheck{..}
243                     | Overflow(_)
244                     | OverflowNeg
245                     | DivisionByZero
246                     | RemainderByZero
247                     => {
248                         diagnostic.report_as_lint(
249                             self.ecx.tcx,
250                             "this expression will panic at runtime",
251                             lint_root,
252                         );
253                     }
254                 }
255                 None
256             },
257         };
258         self.ecx.tcx.span = DUMMY_SP;
259         r
260     }
261
262     fn eval_constant(
263         &mut self,
264         c: &Constant<'tcx>,
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) {
269             Ok(op) => {
270                 Some((op, c.span))
271             },
272             Err(error) => {
273                 let err = error_to_const_error(&self.ecx, error);
274                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
275                 None
276             },
277         }
278     }
279
280     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
281         match *place {
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)
289                     })?;
290                     Some((res, span))
291                 },
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.
295                 _ => None,
296             },
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
301                     return None;
302                 }
303                 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
304                 let instance = Instance::new(self.source.def_id, substs);
305                 let cid = GlobalId {
306                     instance,
307                     promoted: Some(promoted.0),
308                 };
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)
313                 })?;
314                 trace!("evaluated promoted {:?} to {:?}", promoted, res);
315                 Some((res.into(), source_info.span))
316             },
317             _ => None,
318         }
319     }
320
321     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
322         match *op {
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),
326         }
327     }
328
329     fn const_prop(
330         &mut self,
331         rvalue: &Rvalue<'tcx>,
332         place_layout: TyLayout<'tcx>,
333         source_info: SourceInfo,
334     ) -> Option<Const<'tcx>> {
335         let span = source_info.span;
336         match *rvalue {
337             Rvalue::Use(ref op) => {
338                 self.eval_operand(op, source_info)
339             },
340             Rvalue::Repeat(..) |
341             Rvalue::Ref(..) |
342             Rvalue::Aggregate(..) |
343             Rvalue::NullaryOp(NullOp::Box, _) |
344             Rvalue::Discriminant(..) => None,
345
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))
352                 })
353             }
354
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((
359                     OpTy {
360                         op: interpret::Operand::Immediate(Immediate::Scalar(
361                             Scalar::Bits {
362                                 bits: n as u128,
363                                 size: self.tcx.data_layout.pointer_size.bytes() as u8,
364                             }.into()
365                         )),
366                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
367                     },
368                     span,
369                 )))
370             }
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)
374                 } else {
375                     self.source.def_id
376                 };
377                 let generics = self.tcx.generics_of(def_id);
378                 if generics.requires_monomorphization(self.tcx) {
379                     // FIXME: can't handle code with generics
380                     return None;
381                 }
382
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()?;
386                     match op {
387                         UnOp::Neg => {
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);
393                             }
394                         }
395                         UnOp::Not => {
396                             // Cannot overflow
397                         }
398                     }
399                     // Now run the actual operation.
400                     this.ecx.unary_op(op, prim, arg.layout)
401                 })?;
402                 let res = OpTy {
403                     op: interpret::Operand::Immediate(Immediate::Scalar(val.into())),
404                     layout: place_layout,
405                 };
406                 Some((res, span))
407             }
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)
414                 } else {
415                     self.source.def_id
416                 };
417                 let generics = self.tcx.generics_of(def_id);
418                 if generics.requires_monomorphization(self.tcx) {
419                     // FIXME: can't handle code with generics
420                     return None;
421                 }
422
423                 let r = self.use_ecx(source_info, |this| {
424                     this.ecx.read_immediate(right.0)
425                 })?;
426                 if op == BinOp::Shr || op == BinOp::Shl {
427                     let left_ty = left.ty(self.mir, self.tcx);
428                     let left_bits = self
429                         .tcx
430                         .layout_of(self.param_env.and(left_ty))
431                         .unwrap()
432                         .size
433                         .bits();
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,
440                         };
441                         let dir = if op == BinOp::Shr {
442                             "right"
443                         } else {
444                             "left"
445                         };
446                         let node_id = source_scope_local_data[source_info.scope].lint_root;
447                         self.tcx.lint_node(
448                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
449                             node_id,
450                             span,
451                             &format!("attempt to shift {} with overflow", dir));
452                         return None;
453                     }
454                 }
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)
458                 })?;
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)
462                 })?;
463                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
464                     Immediate::ScalarPair(
465                         val.into(),
466                         Scalar::from_bool(overflow).into(),
467                     )
468                 } else {
469                     if overflow {
470                         let err = EvalErrorKind::Overflow(op).into();
471                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
472                         return None;
473                     }
474                     Immediate::Scalar(val.into())
475                 };
476                 let res = OpTy {
477                     op: interpret::Operand::Immediate(val),
478                     layout: place_layout,
479                 };
480                 Some((res, span))
481             },
482         }
483     }
484 }
485
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())
490 }
491
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>,
496 }
497
498 impl CanConstProp {
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),
504         };
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
508             //        lint for x != y
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;
512         }
513         cpv.visit_mir(mir);
514         cpv.can_const_prop
515     }
516 }
517
518 impl<'tcx> Visitor<'tcx> for CanConstProp {
519     fn visit_local(
520         &mut self,
521         &local: &Local,
522         context: PlaceContext<'tcx>,
523         _: Location,
524     ) {
525         use rustc::mir::visit::PlaceContext::*;
526         match context {
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;
532             } else {
533                 self.found_assignment[local] = true
534             },
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) |
541             NonUse(_) => {},
542             _ => self.can_const_prop[local] = false,
543         }
544     }
545 }
546
547 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
548     fn visit_constant(
549         &mut self,
550         constant: &Constant<'tcx>,
551         location: Location,
552     ) {
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);
557     }
558
559     fn visit_statement(
560         &mut self,
561         block: BasicBlock,
562         statement: &Statement<'tcx>,
563         location: Location,
564     ) {
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)
569                 .to_ty(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);
578                         }
579                     }
580                 }
581             }
582         }
583         self.super_statement(block, statement, location);
584     }
585
586     fn visit_terminator_kind(
587         &mut self,
588         block: BasicBlock,
589         kind: &TerminatorKind<'tcx>,
590         location: Location,
591     ) {
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
601                     match cond {
602                         Operand::Move(ref place) | Operand::Copy(ref place) => {
603                             let mut place = place;
604                             while let Place::Projection(ref proj) = *place {
605                                 place = &proj.base;
606                             }
607                             if let Place::Local(local) = *place {
608                                 self.places[local] = None;
609                             }
610                         },
611                         Operand::Constant(_) => {}
612                     }
613                     let span = self.mir[block]
614                         .terminator
615                         .as_ref()
616                         .unwrap()
617                         .source_info
618                         .span;
619                     let node_id = self
620                         .tcx
621                         .hir()
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 {
626                         Overflow(_) |
627                         OverflowNeg |
628                         DivisionByZero |
629                         RemainderByZero => msg.description().to_owned(),
630                         BoundsCheck { ref len, ref index } => {
631                             let len = self
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 {
636                                     bits, ..
637                                 })) => bits,
638                                 other => bug!("const len not primitive: {:?}", other),
639                             };
640                             let index = self
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 {
645                                     bits, ..
646                                 })) => bits,
647                                 other => bug!("const index not primitive: {:?}", other),
648                             };
649                             format!(
650                                 "index out of bounds: \
651                                 the len is {} but the index is {}",
652                                 len,
653                                 index,
654                             )
655                         },
656                         // Need proper const propagator for these
657                         _ => return,
658                     };
659                     self.tcx.lint_node(
660                         ::rustc::lint::builtin::CONST_ERR,
661                         node_id,
662                         span,
663                         &msg,
664                     );
665                 }
666             }
667         }
668     }
669 }