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