]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Rollup merge of #57311 - dlrobertson:fix_valist_copy, r=KodrAus
[rust.git] / src / librustc_mir / transform / const_prop.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4
5 use rustc::hir::def::Def;
6 use rustc::mir::{Constant, Location, Place, Mir, Operand, Rvalue, Local};
7 use rustc::mir::{NullOp, UnOp, StatementKind, Statement, BasicBlock, LocalKind};
8 use rustc::mir::{TerminatorKind, ClearCrossCrate, SourceInfo, BinOp, ProjectionElem};
9 use rustc::mir::visit::{Visitor, PlaceContext, MutatingUseContext, NonMutatingUseContext};
10 use rustc::mir::interpret::{EvalErrorKind, Scalar, GlobalId, EvalResult};
11 use rustc::ty::{TyCtxt, self, Instance};
12 use syntax::source_map::{Span, DUMMY_SP};
13 use rustc::ty::subst::Substs;
14 use rustc_data_structures::indexed_vec::IndexVec;
15 use rustc::ty::ParamEnv;
16 use rustc::ty::layout::{
17     LayoutOf, TyLayout, LayoutError,
18     HasTyCtxt, TargetDataLayout, HasDataLayout,
19 };
20
21 use interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind};
22 use const_eval::{
23     CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_borrowck_eval_cx,
24     lazy_const_to_op,
25 };
26 use transform::{MirPass, MirSource};
27
28 pub struct ConstProp;
29
30 impl MirPass for ConstProp {
31     fn run_pass<'a, 'tcx>(&self,
32                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
33                           source: MirSource,
34                           mir: &mut Mir<'tcx>) {
35         // will be evaluated by miri and produce its errors there
36         if source.promoted.is_some() {
37             return;
38         }
39
40         use rustc::hir::map::blocks::FnLikeNode;
41         let node_id = tcx.hir().as_local_node_id(source.def_id)
42                              .expect("Non-local call to local provider is_const_fn");
43
44         let is_fn_like = FnLikeNode::from_node(tcx.hir().get(node_id)).is_some();
45         let is_assoc_const = match tcx.describe_def(source.def_id) {
46             Some(Def::AssociatedConst(_)) => true,
47             _ => false,
48         };
49
50         // Only run const prop on functions, methods, closures and associated constants
51         if !is_fn_like && !is_assoc_const  {
52             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
53             trace!("ConstProp skipped for {:?}", source.def_id);
54             return
55         }
56
57         trace!("ConstProp starting for {:?}", source.def_id);
58
59         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
60         // constants, instead of just checking for const-folding succeeding.
61         // That would require an uniform one-def no-mutation analysis
62         // and RPO (or recursing when needing the value of a local).
63         let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
64         optimization_finder.visit_mir(mir);
65
66         trace!("ConstProp done for {:?}", source.def_id);
67     }
68 }
69
70 type Const<'tcx> = (OpTy<'tcx>, Span);
71
72 /// Finds optimization opportunities on the MIR.
73 struct ConstPropagator<'a, 'mir, 'tcx:'a+'mir> {
74     ecx: EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
75     mir: &'mir Mir<'tcx>,
76     tcx: TyCtxt<'a, 'tcx, 'tcx>,
77     source: MirSource,
78     places: IndexVec<Local, Option<Const<'tcx>>>,
79     can_const_prop: IndexVec<Local, bool>,
80     param_env: ParamEnv<'tcx>,
81 }
82
83 impl<'a, 'b, 'tcx> LayoutOf for ConstPropagator<'a, 'b, 'tcx> {
84     type Ty = ty::Ty<'tcx>;
85     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
86
87     fn layout_of(&self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
88         self.tcx.layout_of(self.param_env.and(ty))
89     }
90 }
91
92 impl<'a, 'b, 'tcx> HasDataLayout for ConstPropagator<'a, 'b, 'tcx> {
93     #[inline]
94     fn data_layout(&self) -> &TargetDataLayout {
95         &self.tcx.data_layout
96     }
97 }
98
99 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'a, 'b, 'tcx> {
100     #[inline]
101     fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
102         self.tcx
103     }
104 }
105
106 impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> {
107     fn new(
108         mir: &'mir Mir<'tcx>,
109         tcx: TyCtxt<'a, 'tcx, 'tcx>,
110         source: MirSource,
111     ) -> ConstPropagator<'a, 'mir, 'tcx> {
112         let param_env = tcx.param_env(source.def_id);
113         let substs = Substs::identity_for_item(tcx, source.def_id);
114         let instance = Instance::new(source.def_id, substs);
115         let ecx = mk_borrowck_eval_cx(tcx, instance, mir, DUMMY_SP).unwrap();
116         ConstPropagator {
117             ecx,
118             mir,
119             tcx,
120             source,
121             param_env,
122             can_const_prop: CanConstProp::check(mir),
123             places: IndexVec::from_elem(None, &mir.local_decls),
124         }
125     }
126
127     fn use_ecx<F, T>(
128         &mut self,
129         source_info: SourceInfo,
130         f: F
131     ) -> Option<T>
132     where
133         F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
134     {
135         self.ecx.tcx.span = source_info.span;
136         let lint_root = match self.mir.source_scope_local_data {
137             ClearCrossCrate::Set(ref ivs) => {
138                 //FIXME(#51314): remove this check
139                 if source_info.scope.index() >= ivs.len() {
140                     return None;
141                 }
142                 ivs[source_info.scope].lint_root
143             },
144             ClearCrossCrate::Clear => return None,
145         };
146         let r = match f(self) {
147             Ok(val) => Some(val),
148             Err(error) => {
149                 let diagnostic = error_to_const_error(&self.ecx, error);
150                 use rustc::mir::interpret::EvalErrorKind::*;
151                 match diagnostic.error {
152                     // don't report these, they make no sense in a const prop context
153                     | MachineError(_)
154                     // at runtime these transformations might make sense
155                     // FIXME: figure out the rules and start linting
156                     | FunctionAbiMismatch(..)
157                     | FunctionArgMismatch(..)
158                     | FunctionRetMismatch(..)
159                     | FunctionArgCountMismatch
160                     // fine at runtime, might be a register address or sth
161                     | ReadBytesAsPointer
162                     // fine at runtime
163                     | ReadForeignStatic
164                     | Unimplemented(_)
165                     // don't report const evaluator limits
166                     | StackFrameLimitReached
167                     | NoMirFor(..)
168                     | InlineAsm
169                     => {},
170
171                     | InvalidMemoryAccess
172                     | DanglingPointerDeref
173                     | DoubleFree
174                     | InvalidFunctionPointer
175                     | InvalidBool
176                     | InvalidDiscriminant(..)
177                     | PointerOutOfBounds { .. }
178                     | InvalidNullPointerUsage
179                     | ValidationFailure(..)
180                     | InvalidPointerMath
181                     | ReadUndefBytes(_)
182                     | DeadLocal
183                     | InvalidBoolOp(_)
184                     | DerefFunctionPointer
185                     | ExecuteMemory
186                     | Intrinsic(..)
187                     | InvalidChar(..)
188                     | AbiViolation(_)
189                     | AlignmentCheckFailed{..}
190                     | CalledClosureAsFunction
191                     | VtableForArgumentlessMethod
192                     | ModifiedConstantMemory
193                     | ModifiedStatic
194                     | AssumptionNotHeld
195                     // FIXME: should probably be removed and turned into a bug! call
196                     | TypeNotPrimitive(_)
197                     | ReallocatedWrongMemoryKind(_, _)
198                     | DeallocatedWrongMemoryKind(_, _)
199                     | ReallocateNonBasePtr
200                     | DeallocateNonBasePtr
201                     | IncorrectAllocationInformation(..)
202                     | UnterminatedCString(_)
203                     | HeapAllocZeroBytes
204                     | HeapAllocNonPowerOfTwoAlignment(_)
205                     | Unreachable
206                     | ReadFromReturnPointer
207                     | GeneratorResumedAfterReturn
208                     | GeneratorResumedAfterPanic
209                     | ReferencedConstant
210                     | InfiniteLoop
211                     => {
212                         // FIXME: report UB here
213                     },
214
215                     | OutOfTls
216                     | TlsOutOfBounds
217                     | PathNotFound(_)
218                     => bug!("these should not be in rustc, but in miri's machine errors"),
219
220                     | Layout(_)
221                     | UnimplementedTraitSelection
222                     | TypeckError
223                     | TooGeneric
224                     // these are just noise
225                     => {},
226
227                     // non deterministic
228                     | ReadPointerAsBytes
229                     // FIXME: implement
230                     => {},
231
232                     | Panic { .. }
233                     | BoundsCheck{..}
234                     | Overflow(_)
235                     | OverflowNeg
236                     | DivisionByZero
237                     | RemainderByZero
238                     => {
239                         diagnostic.report_as_lint(
240                             self.ecx.tcx,
241                             "this expression will panic at runtime",
242                             lint_root,
243                         );
244                     }
245                 }
246                 None
247             },
248         };
249         self.ecx.tcx.span = DUMMY_SP;
250         r
251     }
252
253     fn eval_constant(
254         &mut self,
255         c: &Constant<'tcx>,
256         source_info: SourceInfo,
257     ) -> Option<Const<'tcx>> {
258         self.ecx.tcx.span = source_info.span;
259         match lazy_const_to_op(&self.ecx, *c.literal, c.ty) {
260             Ok(op) => {
261                 Some((op, c.span))
262             },
263             Err(error) => {
264                 let err = error_to_const_error(&self.ecx, error);
265                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
266                 None
267             },
268         }
269     }
270
271     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
272         match *place {
273             Place::Local(loc) => self.places[loc].clone(),
274             Place::Projection(ref proj) => match proj.elem {
275                 ProjectionElem::Field(field, _) => {
276                     trace!("field proj on {:?}", proj.base);
277                     let (base, span) = self.eval_place(&proj.base, source_info)?;
278                     let res = self.use_ecx(source_info, |this| {
279                         this.ecx.operand_field(base, field.index() as u64)
280                     })?;
281                     Some((res, span))
282                 },
283                 // We could get more projections by using e.g., `operand_projection`,
284                 // but we do not even have the stack frame set up properly so
285                 // an `Index` projection would throw us off-track.
286                 _ => None,
287             },
288             Place::Promoted(ref promoted) => {
289                 let generics = self.tcx.generics_of(self.source.def_id);
290                 if generics.requires_monomorphization(self.tcx) {
291                     // FIXME: can't handle code with generics
292                     return None;
293                 }
294                 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
295                 let instance = Instance::new(self.source.def_id, substs);
296                 let cid = GlobalId {
297                     instance,
298                     promoted: Some(promoted.0),
299                 };
300                 // cannot use `const_eval` here, because that would require having the MIR
301                 // for the current function available, but we're producing said MIR right now
302                 let res = self.use_ecx(source_info, |this| {
303                     eval_promoted(this.tcx, cid, this.mir, this.param_env)
304                 })?;
305                 trace!("evaluated promoted {:?} to {:?}", promoted, res);
306                 Some((res.into(), source_info.span))
307             },
308             _ => None,
309         }
310     }
311
312     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
313         match *op {
314             Operand::Constant(ref c) => self.eval_constant(c, source_info),
315             | Operand::Move(ref place)
316             | Operand::Copy(ref place) => self.eval_place(place, source_info),
317         }
318     }
319
320     fn const_prop(
321         &mut self,
322         rvalue: &Rvalue<'tcx>,
323         place_layout: TyLayout<'tcx>,
324         source_info: SourceInfo,
325     ) -> Option<Const<'tcx>> {
326         let span = source_info.span;
327         match *rvalue {
328             Rvalue::Use(ref op) => {
329                 self.eval_operand(op, source_info)
330             },
331             Rvalue::Repeat(..) |
332             Rvalue::Ref(..) |
333             Rvalue::Aggregate(..) |
334             Rvalue::NullaryOp(NullOp::Box, _) |
335             Rvalue::Discriminant(..) => None,
336
337             Rvalue::Cast(kind, ref operand, _) => {
338                 let (op, span) = self.eval_operand(operand, source_info)?;
339                 self.use_ecx(source_info, |this| {
340                     let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
341                     this.ecx.cast(op, kind, dest.into())?;
342                     Ok((dest.into(), span))
343                 })
344             }
345
346             // FIXME(oli-obk): evaluate static/constant slice lengths
347             Rvalue::Len(_) => None,
348             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
349                 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some((
350                     OpTy {
351                         op: interpret::Operand::Immediate(Immediate::Scalar(
352                             Scalar::Bits {
353                                 bits: n as u128,
354                                 size: self.tcx.data_layout.pointer_size.bytes() as u8,
355                             }.into()
356                         )),
357                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
358                     },
359                     span,
360                 )))
361             }
362             Rvalue::UnaryOp(op, ref arg) => {
363                 let def_id = if self.tcx.is_closure(self.source.def_id) {
364                     self.tcx.closure_base_def_id(self.source.def_id)
365                 } else {
366                     self.source.def_id
367                 };
368                 let generics = self.tcx.generics_of(def_id);
369                 if generics.requires_monomorphization(self.tcx) {
370                     // FIXME: can't handle code with generics
371                     return None;
372                 }
373
374                 let (arg, _) = self.eval_operand(arg, source_info)?;
375                 let val = self.use_ecx(source_info, |this| {
376                     let prim = this.ecx.read_scalar(arg)?.not_undef()?;
377                     match op {
378                         UnOp::Neg => {
379                             // Need to do overflow check here: For actual CTFE, MIR
380                             // generation emits code that does this before calling the op.
381                             let size = arg.layout.size;
382                             if prim.to_bits(size)? == (1 << (size.bits() - 1)) {
383                                 return err!(OverflowNeg);
384                             }
385                         }
386                         UnOp::Not => {
387                             // Cannot overflow
388                         }
389                     }
390                     // Now run the actual operation.
391                     this.ecx.unary_op(op, prim, arg.layout)
392                 })?;
393                 let res = OpTy {
394                     op: interpret::Operand::Immediate(Immediate::Scalar(val.into())),
395                     layout: place_layout,
396                 };
397                 Some((res, span))
398             }
399             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
400             Rvalue::BinaryOp(op, ref left, ref right) => {
401                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
402                 let right = self.eval_operand(right, source_info)?;
403                 let def_id = if self.tcx.is_closure(self.source.def_id) {
404                     self.tcx.closure_base_def_id(self.source.def_id)
405                 } else {
406                     self.source.def_id
407                 };
408                 let generics = self.tcx.generics_of(def_id);
409                 if generics.requires_monomorphization(self.tcx) {
410                     // FIXME: can't handle code with generics
411                     return None;
412                 }
413
414                 let r = self.use_ecx(source_info, |this| {
415                     this.ecx.read_immediate(right.0)
416                 })?;
417                 if op == BinOp::Shr || op == BinOp::Shl {
418                     let left_ty = left.ty(self.mir, self.tcx);
419                     let left_bits = self
420                         .tcx
421                         .layout_of(self.param_env.and(left_ty))
422                         .unwrap()
423                         .size
424                         .bits();
425                     let right_size = right.0.layout.size;
426                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
427                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
428                         let source_scope_local_data = match self.mir.source_scope_local_data {
429                             ClearCrossCrate::Set(ref data) => data,
430                             ClearCrossCrate::Clear => return None,
431                         };
432                         let dir = if op == BinOp::Shr {
433                             "right"
434                         } else {
435                             "left"
436                         };
437                         let node_id = source_scope_local_data[source_info.scope].lint_root;
438                         self.tcx.lint_node(
439                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
440                             node_id,
441                             span,
442                             &format!("attempt to shift {} with overflow", dir));
443                         return None;
444                     }
445                 }
446                 let left = self.eval_operand(left, source_info)?;
447                 let l = self.use_ecx(source_info, |this| {
448                     this.ecx.read_immediate(left.0)
449                 })?;
450                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
451                 let (val, overflow) = self.use_ecx(source_info, |this| {
452                     this.ecx.binary_op_imm(op, l, r)
453                 })?;
454                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
455                     Immediate::ScalarPair(
456                         val.into(),
457                         Scalar::from_bool(overflow).into(),
458                     )
459                 } else {
460                     if overflow {
461                         let err = EvalErrorKind::Overflow(op).into();
462                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
463                         return None;
464                     }
465                     Immediate::Scalar(val.into())
466                 };
467                 let res = OpTy {
468                     op: interpret::Operand::Immediate(val),
469                     layout: place_layout,
470                 };
471                 Some((res, span))
472             },
473         }
474     }
475 }
476
477 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
478                           param_env: ty::ParamEnv<'tcx>,
479                           ty: ty::Ty<'tcx>) -> Option<u64> {
480     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
481 }
482
483 struct CanConstProp {
484     can_const_prop: IndexVec<Local, bool>,
485     // false at the beginning, once set, there are not allowed to be any more assignments
486     found_assignment: IndexVec<Local, bool>,
487 }
488
489 impl CanConstProp {
490     /// returns true if `local` can be propagated
491     fn check(mir: &Mir) -> IndexVec<Local, bool> {
492         let mut cpv = CanConstProp {
493             can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
494             found_assignment: IndexVec::from_elem(false, &mir.local_decls),
495         };
496         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
497             // cannot use args at all
498             // cannot use locals because if x < y { y - x } else { x - y } would
499             //        lint for x != y
500             // FIXME(oli-obk): lint variables until they are used in a condition
501             // FIXME(oli-obk): lint if return value is constant
502             *val = mir.local_kind(local) == LocalKind::Temp;
503         }
504         cpv.visit_mir(mir);
505         cpv.can_const_prop
506     }
507 }
508
509 impl<'tcx> Visitor<'tcx> for CanConstProp {
510     fn visit_local(
511         &mut self,
512         &local: &Local,
513         context: PlaceContext<'tcx>,
514         _: Location,
515     ) {
516         use rustc::mir::visit::PlaceContext::*;
517         match context {
518             // Constants must have at most one write
519             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
520             // only occur in independent execution paths
521             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
522                 self.can_const_prop[local] = false;
523             } else {
524                 self.found_assignment[local] = true
525             },
526             // Reading constants is allowed an arbitrary number of times
527             NonMutatingUse(NonMutatingUseContext::Copy) |
528             NonMutatingUse(NonMutatingUseContext::Move) |
529             NonMutatingUse(NonMutatingUseContext::Inspect) |
530             NonMutatingUse(NonMutatingUseContext::Projection) |
531             MutatingUse(MutatingUseContext::Projection) |
532             NonUse(_) => {},
533             _ => self.can_const_prop[local] = false,
534         }
535     }
536 }
537
538 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
539     fn visit_constant(
540         &mut self,
541         constant: &Constant<'tcx>,
542         location: Location,
543     ) {
544         trace!("visit_constant: {:?}", constant);
545         self.super_constant(constant, location);
546         let source_info = *self.mir.source_info(location);
547         self.eval_constant(constant, source_info);
548     }
549
550     fn visit_statement(
551         &mut self,
552         block: BasicBlock,
553         statement: &Statement<'tcx>,
554         location: Location,
555     ) {
556         trace!("visit_statement: {:?}", statement);
557         if let StatementKind::Assign(ref place, ref rval) = statement.kind {
558             let place_ty: ty::Ty<'tcx> = place
559                 .ty(&self.mir.local_decls, self.tcx)
560                 .to_ty(self.tcx);
561             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
562                 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
563                     if let Place::Local(local) = *place {
564                         trace!("checking whether {:?} can be stored to {:?}", value, local);
565                         if self.can_const_prop[local] {
566                             trace!("storing {:?} to {:?}", value, local);
567                             assert!(self.places[local].is_none());
568                             self.places[local] = Some(value);
569                         }
570                     }
571                 }
572             }
573         }
574         self.super_statement(block, statement, location);
575     }
576
577     fn visit_terminator_kind(
578         &mut self,
579         block: BasicBlock,
580         kind: &TerminatorKind<'tcx>,
581         location: Location,
582     ) {
583         self.super_terminator_kind(block, kind, location);
584         let source_info = *self.mir.source_info(location);
585         if let TerminatorKind::Assert { expected, msg, cond, .. } = kind {
586             if let Some(value) = self.eval_operand(cond, source_info) {
587                 trace!("assertion on {:?} should be {:?}", value, expected);
588                 let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
589                 if expected != self.ecx.read_scalar(value.0).unwrap() {
590                     // poison all places this operand references so that further code
591                     // doesn't use the invalid value
592                     match cond {
593                         Operand::Move(ref place) | Operand::Copy(ref place) => {
594                             let mut place = place;
595                             while let Place::Projection(ref proj) = *place {
596                                 place = &proj.base;
597                             }
598                             if let Place::Local(local) = *place {
599                                 self.places[local] = None;
600                             }
601                         },
602                         Operand::Constant(_) => {}
603                     }
604                     let span = self.mir[block]
605                         .terminator
606                         .as_ref()
607                         .unwrap()
608                         .source_info
609                         .span;
610                     let node_id = self
611                         .tcx
612                         .hir()
613                         .as_local_node_id(self.source.def_id)
614                         .expect("some part of a failing const eval must be local");
615                     use rustc::mir::interpret::EvalErrorKind::*;
616                     let msg = match msg {
617                         Overflow(_) |
618                         OverflowNeg |
619                         DivisionByZero |
620                         RemainderByZero => msg.description().to_owned(),
621                         BoundsCheck { ref len, ref index } => {
622                             let len = self
623                                 .eval_operand(len, source_info)
624                                 .expect("len must be const");
625                             let len = match self.ecx.read_scalar(len.0) {
626                                 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
627                                     bits, ..
628                                 })) => bits,
629                                 other => bug!("const len not primitive: {:?}", other),
630                             };
631                             let index = self
632                                 .eval_operand(index, source_info)
633                                 .expect("index must be const");
634                             let index = match self.ecx.read_scalar(index.0) {
635                                 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
636                                     bits, ..
637                                 })) => bits,
638                                 other => bug!("const index not primitive: {:?}", other),
639                             };
640                             format!(
641                                 "index out of bounds: \
642                                 the len is {} but the index is {}",
643                                 len,
644                                 index,
645                             )
646                         },
647                         // Need proper const propagator for these
648                         _ => return,
649                     };
650                     self.tcx.lint_node(
651                         ::rustc::lint::builtin::CONST_ERR,
652                         node_id,
653                         span,
654                         &msg,
655                     );
656                 }
657             }
658         }
659     }
660 }