]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval.rs
5d6e9d64aeb58ab9134b5f670478e979ab14d519
[rust.git] / src / librustc_mir / const_eval.rs
1 // Not in interpret to make sure we do not use private implementation details
2
3 use std::fmt;
4 use std::error::Error;
5 use std::borrow::{Borrow, Cow};
6 use std::hash::Hash;
7 use std::collections::hash_map::Entry;
8
9 use rustc::hir::{self, def_id::DefId};
10 use rustc::hir::def::Def;
11 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
12 use rustc::mir;
13 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
14 use rustc::ty::layout::{self, LayoutOf, TyLayout, VariantIdx};
15 use rustc::ty::subst::Subst;
16 use rustc::traits::Reveal;
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc::util::common::ErrorReported;
19
20 use syntax::ast::Mutability;
21 use syntax::source_map::{Span, DUMMY_SP};
22
23 use crate::interpret::{self,
24     PlaceTy, MPlaceTy, MemPlace, OpTy, Operand, Immediate, Scalar, RawConst, ConstValue, Pointer,
25     EvalResult, EvalError, EvalErrorKind, GlobalId, EvalContext, StackPopCleanup,
26     Allocation, AllocId, MemoryKind,
27     snapshot, RefTracking,
28 };
29
30 /// Number of steps until the detector even starts doing anything.
31 /// Also, a warning is shown to the user when this number is reached.
32 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
33 /// The number of steps between loop detector snapshots.
34 /// Should be a power of two for performance reasons.
35 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
36
37 /// The `EvalContext` is only meant to be used to do field and index projections into constants for
38 /// `simd_shuffle` and const patterns in match arms.
39 ///
40 /// The function containing the `match` that is currently being analyzed may have generic bounds
41 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
42 /// of a function's generic parameter will require knowledge about the bounds on the generic
43 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
44 pub(crate) fn mk_eval_cx<'a, 'mir, 'tcx>(
45     tcx: TyCtxt<'a, 'tcx, 'tcx>,
46     span: Span,
47     param_env: ty::ParamEnv<'tcx>,
48 ) -> CompileTimeEvalContext<'a, 'mir, 'tcx> {
49     debug!("mk_eval_cx: {:?}", param_env);
50     EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new())
51 }
52
53 pub(crate) fn eval_promoted<'a, 'mir, 'tcx>(
54     tcx: TyCtxt<'a, 'tcx, 'tcx>,
55     cid: GlobalId<'tcx>,
56     mir: &'mir mir::Mir<'tcx>,
57     param_env: ty::ParamEnv<'tcx>,
58 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
59     let span = tcx.def_span(cid.instance.def_id());
60     let mut ecx = mk_eval_cx(tcx, span, param_env);
61     eval_body_using_ecx(&mut ecx, cid, Some(mir), param_env)
62 }
63
64 // FIXME: These two conversion functions are bad hacks.  We should just always use allocations.
65 pub fn op_to_const<'tcx>(
66     ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
67     op: OpTy<'tcx>,
68     may_normalize: bool,
69 ) -> EvalResult<'tcx, ty::Const<'tcx>> {
70     // We do not normalize just any data.  Only scalar layout and slices.
71     let normalize = may_normalize
72         && match op.layout.abi {
73             layout::Abi::Scalar(..) => true,
74             layout::Abi::ScalarPair(..) => op.layout.ty.is_slice(),
75             _ => false,
76         };
77     let normalized_op = if normalize {
78         ecx.try_read_immediate(op)?
79     } else {
80         match *op {
81             Operand::Indirect(mplace) => Err(mplace),
82             Operand::Immediate(val) => Ok(val)
83         }
84     };
85     let val = match normalized_op {
86         Err(MemPlace { ptr, align, meta }) => {
87             // extract alloc-offset pair
88             assert!(meta.is_none());
89             let ptr = ptr.to_ptr()?;
90             let alloc = ecx.memory.get(ptr.alloc_id)?;
91             assert!(alloc.align >= align);
92             assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= op.layout.size.bytes());
93             let mut alloc = alloc.clone();
94             alloc.align = align;
95             // FIXME shouldn't it be the case that `mark_static_initialized` has already
96             // interned this?  I thought that is the entire point of that `FinishStatic` stuff?
97             let alloc = ecx.tcx.intern_const_alloc(alloc);
98             ConstValue::ByRef(ptr.alloc_id, alloc, ptr.offset)
99         },
100         Ok(Immediate::Scalar(x)) =>
101             ConstValue::Scalar(x.not_undef()?),
102         Ok(Immediate::ScalarPair(a, b)) =>
103             ConstValue::Slice(a.not_undef()?, b.to_usize(ecx)?),
104     };
105     Ok(ty::Const { val, ty: op.layout.ty })
106 }
107
108 fn eval_body_and_ecx<'a, 'mir, 'tcx>(
109     tcx: TyCtxt<'a, 'tcx, 'tcx>,
110     cid: GlobalId<'tcx>,
111     mir: Option<&'mir mir::Mir<'tcx>>,
112     param_env: ty::ParamEnv<'tcx>,
113 ) -> (EvalResult<'tcx, MPlaceTy<'tcx>>, CompileTimeEvalContext<'a, 'mir, 'tcx>) {
114     // we start out with the best span we have
115     // and try improving it down the road when more information is available
116     let span = tcx.def_span(cid.instance.def_id());
117     let span = mir.map(|mir| mir.span).unwrap_or(span);
118     let mut ecx = EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new());
119     let r = eval_body_using_ecx(&mut ecx, cid, mir, param_env);
120     (r, ecx)
121 }
122
123 // Returns a pointer to where the result lives
124 fn eval_body_using_ecx<'mir, 'tcx>(
125     ecx: &mut CompileTimeEvalContext<'_, 'mir, 'tcx>,
126     cid: GlobalId<'tcx>,
127     mir: Option<&'mir mir::Mir<'tcx>>,
128     param_env: ty::ParamEnv<'tcx>,
129 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
130     debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
131     let tcx = ecx.tcx.tcx;
132     let mut mir = match mir {
133         Some(mir) => mir,
134         None => ecx.load_mir(cid.instance.def)?,
135     };
136     if let Some(index) = cid.promoted {
137         mir = &mir.promoted[index];
138     }
139     let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
140     assert!(!layout.is_unsized());
141     let ret = ecx.allocate(layout, MemoryKind::Stack);
142
143     let name = ty::tls::with(|tcx| tcx.item_path_str(cid.instance.def_id()));
144     let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
145     trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
146     assert!(mir.arg_count == 0);
147     ecx.push_stack_frame(
148         cid.instance,
149         mir.span,
150         mir,
151         Some(ret.into()),
152         StackPopCleanup::None { cleanup: false },
153     )?;
154
155     // The main interpreter loop.
156     ecx.run()?;
157
158     // Intern the result
159     let internally_mutable = !layout.ty.is_freeze(tcx, param_env, mir.span);
160     let is_static = tcx.is_static(cid.instance.def_id());
161     let mutability = if is_static == Some(hir::Mutability::MutMutable) || internally_mutable {
162         Mutability::Mutable
163     } else {
164         Mutability::Immutable
165     };
166     ecx.memory.intern_static(ret.ptr.to_ptr()?.alloc_id, mutability)?;
167
168     debug!("eval_body_using_ecx done: {:?}", *ret);
169     Ok(ret)
170 }
171
172 impl<'tcx> Into<EvalError<'tcx>> for ConstEvalError {
173     fn into(self) -> EvalError<'tcx> {
174         EvalErrorKind::MachineError(self.to_string()).into()
175     }
176 }
177
178 #[derive(Clone, Debug)]
179 enum ConstEvalError {
180     NeedsRfc(String),
181 }
182
183 impl fmt::Display for ConstEvalError {
184     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185         use self::ConstEvalError::*;
186         match *self {
187             NeedsRfc(ref msg) => {
188                 write!(
189                     f,
190                     "\"{}\" needs an rfc before being allowed inside constants",
191                     msg
192                 )
193             }
194         }
195     }
196 }
197
198 impl Error for ConstEvalError {
199     fn description(&self) -> &str {
200         use self::ConstEvalError::*;
201         match *self {
202             NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
203         }
204     }
205
206     fn cause(&self) -> Option<&dyn Error> {
207         None
208     }
209 }
210
211 // Extra machine state for CTFE, and the Machine instance
212 pub struct CompileTimeInterpreter<'a, 'mir, 'tcx: 'a+'mir> {
213     /// When this value is negative, it indicates the number of interpreter
214     /// steps *until* the loop detector is enabled. When it is positive, it is
215     /// the number of steps after the detector has been enabled modulo the loop
216     /// detector period.
217     pub(super) steps_since_detector_enabled: isize,
218
219     /// Extra state to detect loops.
220     pub(super) loop_detector: snapshot::InfiniteLoopDetector<'a, 'mir, 'tcx>,
221 }
222
223 impl<'a, 'mir, 'tcx> CompileTimeInterpreter<'a, 'mir, 'tcx> {
224     fn new() -> Self {
225         CompileTimeInterpreter {
226             loop_detector: Default::default(),
227             steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
228         }
229     }
230 }
231
232 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
233     #[inline(always)]
234     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
235         where K: Borrow<Q>
236     {
237         FxHashMap::contains_key(self, k)
238     }
239
240     #[inline(always)]
241     fn insert(&mut self, k: K, v: V) -> Option<V>
242     {
243         FxHashMap::insert(self, k, v)
244     }
245
246     #[inline(always)]
247     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
248         where K: Borrow<Q>
249     {
250         FxHashMap::remove(self, k)
251     }
252
253     #[inline(always)]
254     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
255         self.iter()
256             .filter_map(move |(k, v)| f(k, &*v))
257             .collect()
258     }
259
260     #[inline(always)]
261     fn get_or<E>(
262         &self,
263         k: K,
264         vacant: impl FnOnce() -> Result<V, E>
265     ) -> Result<&V, E>
266     {
267         match self.get(&k) {
268             Some(v) => Ok(v),
269             None => {
270                 vacant()?;
271                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
272             }
273         }
274     }
275
276     #[inline(always)]
277     fn get_mut_or<E>(
278         &mut self,
279         k: K,
280         vacant: impl FnOnce() -> Result<V, E>
281     ) -> Result<&mut V, E>
282     {
283         match self.entry(k) {
284             Entry::Occupied(e) => Ok(e.into_mut()),
285             Entry::Vacant(e) => {
286                 let v = vacant()?;
287                 Ok(e.insert(v))
288             }
289         }
290     }
291 }
292
293 type CompileTimeEvalContext<'a, 'mir, 'tcx> =
294     EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>;
295
296 impl interpret::MayLeak for ! {
297     #[inline(always)]
298     fn may_leak(self) -> bool {
299         // `self` is uninhabited
300         self
301     }
302 }
303
304 impl<'a, 'mir, 'tcx> interpret::Machine<'a, 'mir, 'tcx>
305     for CompileTimeInterpreter<'a, 'mir, 'tcx>
306 {
307     type MemoryKinds = !;
308     type PointerTag = ();
309
310     type FrameExtra = ();
311     type MemoryExtra = ();
312     type AllocExtra = ();
313
314     type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
315
316     const STATIC_KIND: Option<!> = None; // no copying of statics allowed
317
318     #[inline(always)]
319     fn enforce_validity(_ecx: &EvalContext<'a, 'mir, 'tcx, Self>) -> bool {
320         false // for now, we don't enforce validity
321     }
322
323     fn find_fn(
324         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
325         instance: ty::Instance<'tcx>,
326         args: &[OpTy<'tcx>],
327         dest: Option<PlaceTy<'tcx>>,
328         ret: Option<mir::BasicBlock>,
329     ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
330         debug!("eval_fn_call: {:?}", instance);
331         // Only check non-glue functions
332         if let ty::InstanceDef::Item(def_id) = instance.def {
333             // Execution might have wandered off into other crates, so we cannot to a stability-
334             // sensitive check here.  But we can at least rule out functions that are not const
335             // at all.
336             if !ecx.tcx.is_const_fn_raw(def_id) {
337                 // Some functions we support even if they are non-const -- but avoid testing
338                 // that for const fn!  We certainly do *not* want to actually call the fn
339                 // though, so be sure we return here.
340                 return if ecx.hook_fn(instance, args, dest)? {
341                     ecx.goto_block(ret)?; // fully evaluated and done
342                     Ok(None)
343                 } else {
344                     err!(MachineError(format!("calling non-const function `{}`", instance)))
345                 };
346             }
347         }
348         // This is a const fn. Call it.
349         Ok(Some(match ecx.load_mir(instance.def) {
350             Ok(mir) => mir,
351             Err(err) => {
352                 if let EvalErrorKind::NoMirFor(ref path) = err.kind {
353                     return Err(
354                         ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
355                             .into(),
356                     );
357                 }
358                 return Err(err);
359             }
360         }))
361     }
362
363     fn call_intrinsic(
364         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
365         instance: ty::Instance<'tcx>,
366         args: &[OpTy<'tcx>],
367         dest: PlaceTy<'tcx>,
368     ) -> EvalResult<'tcx> {
369         if ecx.emulate_intrinsic(instance, args, dest)? {
370             return Ok(());
371         }
372         // An intrinsic that we do not support
373         let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
374         Err(
375             ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
376         )
377     }
378
379     fn ptr_op(
380         _ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
381         _bin_op: mir::BinOp,
382         _left: Scalar,
383         _left_layout: TyLayout<'tcx>,
384         _right: Scalar,
385         _right_layout: TyLayout<'tcx>,
386     ) -> EvalResult<'tcx, (Scalar, bool)> {
387         Err(
388             ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
389         )
390     }
391
392     fn find_foreign_static(
393         _def_id: DefId,
394         _tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
395         _memory_extra: &(),
396     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
397         err!(ReadForeignStatic)
398     }
399
400     #[inline(always)]
401     fn adjust_static_allocation<'b>(
402         alloc: &'b Allocation,
403         _memory_extra: &(),
404     ) -> Cow<'b, Allocation<Self::PointerTag>> {
405         // We do not use a tag so we can just cheaply forward the reference
406         Cow::Borrowed(alloc)
407     }
408
409     fn box_alloc(
410         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
411         _dest: PlaceTy<'tcx>,
412     ) -> EvalResult<'tcx> {
413         Err(
414             ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
415         )
416     }
417
418     fn before_terminator(ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx> {
419         {
420             let steps = &mut ecx.machine.steps_since_detector_enabled;
421
422             *steps += 1;
423             if *steps < 0 {
424                 return Ok(());
425             }
426
427             *steps %= DETECTOR_SNAPSHOT_PERIOD;
428             if *steps != 0 {
429                 return Ok(());
430             }
431         }
432
433         let span = ecx.frame().span;
434         ecx.machine.loop_detector.observe_and_analyze(
435             &ecx.tcx,
436             span,
437             &ecx.memory,
438             &ecx.stack[..],
439         )
440     }
441
442     #[inline(always)]
443     fn tag_new_allocation(
444         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
445         ptr: Pointer,
446         _kind: MemoryKind<Self::MemoryKinds>,
447     ) -> Pointer {
448         ptr
449     }
450
451     #[inline(always)]
452     fn stack_push(
453         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
454     ) -> EvalResult<'tcx> {
455         Ok(())
456     }
457
458     /// Called immediately before a stack frame gets popped.
459     #[inline(always)]
460     fn stack_pop(
461         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
462         _extra: (),
463     ) -> EvalResult<'tcx> {
464         Ok(())
465     }
466 }
467
468 /// Projects to a field of a (variant of a) const.
469 pub fn const_field<'a, 'tcx>(
470     tcx: TyCtxt<'a, 'tcx, 'tcx>,
471     param_env: ty::ParamEnv<'tcx>,
472     variant: Option<VariantIdx>,
473     field: mir::Field,
474     value: ty::Const<'tcx>,
475 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
476     trace!("const_field: {:?}, {:?}", field, value);
477     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
478     let result = (|| {
479         // get the operand again
480         let op = ecx.lazy_const_to_op(ty::LazyConst::Evaluated(value), value.ty)?;
481         // downcast
482         let down = match variant {
483             None => op,
484             Some(variant) => ecx.operand_downcast(op, variant)?
485         };
486         // then project
487         let field = ecx.operand_field(down, field.index() as u64)?;
488         // and finally move back to the const world, always normalizing because
489         // this is not called for statics.
490         op_to_const(&ecx, field, true)
491     })();
492     result.map_err(|error| {
493         let err = error_to_const_error(&ecx, error);
494         err.report_as_error(ecx.tcx, "could not access field of constant");
495         ErrorHandled::Reported
496     })
497 }
498
499 pub fn const_variant_index<'a, 'tcx>(
500     tcx: TyCtxt<'a, 'tcx, 'tcx>,
501     param_env: ty::ParamEnv<'tcx>,
502     val: ty::Const<'tcx>,
503 ) -> EvalResult<'tcx, VariantIdx> {
504     trace!("const_variant_index: {:?}", val);
505     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
506     let op = ecx.lazy_const_to_op(ty::LazyConst::Evaluated(val), val.ty)?;
507     Ok(ecx.read_discriminant(op)?.1)
508 }
509
510 pub fn error_to_const_error<'a, 'mir, 'tcx>(
511     ecx: &EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
512     mut error: EvalError<'tcx>
513 ) -> ConstEvalErr<'tcx> {
514     error.print_backtrace();
515     let stacktrace = ecx.generate_stacktrace(None);
516     ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
517 }
518
519 fn validate_and_turn_into_const<'a, 'tcx>(
520     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
521     constant: RawConst<'tcx>,
522     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
523 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
524     let cid = key.value;
525     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
526     let val = (|| {
527         let op = ecx.raw_const_to_mplace(constant)?.into();
528         // FIXME: Once the visitor infrastructure landed, change validation to
529         // work directly on `MPlaceTy`.
530         let mut ref_tracking = RefTracking::new(op);
531         while let Some((op, path)) = ref_tracking.todo.pop() {
532             ecx.validate_operand(
533                 op,
534                 path,
535                 Some(&mut ref_tracking),
536                 true, // const mode
537             )?;
538         }
539         // Now that we validated, turn this into a proper constant.
540         let def_id = cid.instance.def.def_id();
541         let normalize = tcx.is_static(def_id).is_none() && cid.promoted.is_none();
542         op_to_const(&ecx, op, normalize)
543     })();
544
545     val.map_err(|error| {
546         let err = error_to_const_error(&ecx, error);
547         match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
548             Ok(mut diag) => {
549                 diag.note("The rules on what exactly is undefined behavior aren't clear, \
550                     so this check might be overzealous. Please open an issue on the rust compiler \
551                     repository if you believe it should not be considered undefined behavior",
552                 );
553                 diag.emit();
554                 ErrorHandled::Reported
555             }
556             Err(err) => err,
557         }
558     })
559 }
560
561 pub fn const_eval_provider<'a, 'tcx>(
562     tcx: TyCtxt<'a, 'tcx, 'tcx>,
563     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
564 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
565     // see comment in const_eval_provider for what we're doing here
566     if key.param_env.reveal == Reveal::All {
567         let mut key = key.clone();
568         key.param_env.reveal = Reveal::UserFacing;
569         match tcx.const_eval(key) {
570             // try again with reveal all as requested
571             Err(ErrorHandled::TooGeneric) => {
572                 // Promoteds should never be "too generic" when getting evaluated.
573                 // They either don't get evaluated, or we are in a monomorphic context
574                 assert!(key.value.promoted.is_none());
575             },
576             // dedupliate calls
577             other => return other,
578         }
579     }
580     tcx.const_eval_raw(key).and_then(|val| {
581         validate_and_turn_into_const(tcx, val, key)
582     })
583 }
584
585 pub fn const_eval_raw_provider<'a, 'tcx>(
586     tcx: TyCtxt<'a, 'tcx, 'tcx>,
587     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
588 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
589     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
590     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
591     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
592     // computed. For a large percentage of constants that will already have succeeded. Only
593     // associated constants of generic functions will fail due to not enough monomorphization
594     // information being available.
595
596     // In case we fail in the `UserFacing` variant, we just do the real computation.
597     if key.param_env.reveal == Reveal::All {
598         let mut key = key.clone();
599         key.param_env.reveal = Reveal::UserFacing;
600         match tcx.const_eval_raw(key) {
601             // try again with reveal all as requested
602             Err(ErrorHandled::TooGeneric) => {},
603             // dedupliate calls
604             other => return other,
605         }
606     }
607     // the first trace is for replicating an ice
608     // There's no tracking issue, but the next two lines concatenated link to the discussion on
609     // zulip. It's not really possible to test this, because it doesn't show up in diagnostics
610     // or MIR.
611     // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
612     // subject/anon_const_instance_printing/near/135980032
613     trace!("const eval: {}", key.value.instance);
614     trace!("const eval: {:?}", key);
615
616     let cid = key.value;
617     let def_id = cid.instance.def.def_id();
618
619     if let Some(id) = tcx.hir().as_local_node_id(def_id) {
620         let tables = tcx.typeck_tables_of(def_id);
621
622         // Do match-check before building MIR
623         if let Err(ErrorReported) = tcx.check_match(def_id) {
624             return Err(ErrorHandled::Reported)
625         }
626
627         if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(id) {
628             tcx.mir_const_qualif(def_id);
629         }
630
631         // Do not continue into miri if typeck errors occurred; it will fail horribly
632         if tables.tainted_by_errors {
633             return Err(ErrorHandled::Reported)
634         }
635     };
636
637     let (res, ecx) = eval_body_and_ecx(tcx, cid, None, key.param_env);
638     res.and_then(|place| {
639         Ok(RawConst {
640             alloc_id: place.to_ptr().expect("we allocated this ptr!").alloc_id,
641             ty: place.layout.ty
642         })
643     }).map_err(|error| {
644         let err = error_to_const_error(&ecx, error);
645         // errors in statics are always emitted as fatal errors
646         if tcx.is_static(def_id).is_some() {
647             let reported_err = err.report_as_error(ecx.tcx,
648                                                    "could not evaluate static initializer");
649             // Ensure that if the above error was either `TooGeneric` or `Reported`
650             // an error must be reported.
651             if tcx.sess.err_count() == 0 {
652                 tcx.sess.delay_span_bug(err.span,
653                                         &format!("static eval failure did not emit an error: {:#?}",
654                                                  reported_err));
655             }
656             reported_err
657         } else if def_id.is_local() {
658             // constant defined in this crate, we can figure out a lint level!
659             match tcx.describe_def(def_id) {
660                 // constants never produce a hard error at the definition site. Anything else is
661                 // a backwards compatibility hazard (and will break old versions of winapi for sure)
662                 //
663                 // note that validation may still cause a hard error on this very same constant,
664                 // because any code that existed before validation could not have failed validation
665                 // thus preventing such a hard error from being a backwards compatibility hazard
666                 Some(Def::Const(_)) | Some(Def::AssociatedConst(_)) => {
667                     let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
668                     err.report_as_lint(
669                         tcx.at(tcx.def_span(def_id)),
670                         "any use of this value will cause an error",
671                         node_id,
672                     )
673                 },
674                 // promoting runtime code is only allowed to error if it references broken constants
675                 // any other kind of error will be reported to the user as a deny-by-default lint
676                 _ => if let Some(p) = cid.promoted {
677                     let span = tcx.optimized_mir(def_id).promoted[p].span;
678                     if let EvalErrorKind::ReferencedConstant = err.error {
679                         err.report_as_error(
680                             tcx.at(span),
681                             "evaluation of constant expression failed",
682                         )
683                     } else {
684                         err.report_as_lint(
685                             tcx.at(span),
686                             "reaching this expression at runtime will panic or abort",
687                             tcx.hir().as_local_node_id(def_id).unwrap(),
688                         )
689                     }
690                 // anything else (array lengths, enum initializers, constant patterns) are reported
691                 // as hard errors
692                 } else {
693                     err.report_as_error(
694                         ecx.tcx,
695                         "evaluation of constant value failed",
696                     )
697                 },
698             }
699         } else {
700             // use of broken constant from other crate
701             err.report_as_error(ecx.tcx, "could not evaluate constant")
702         }
703     })
704 }