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