]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval.rs
Rollup merge of #57860 - jethrogb:jb/sgx-os-ffi, r=joshtriplett
[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 fat pointers.
71     let normalize = may_normalize
72         && match op.layout.abi {
73             layout::Abi::Scalar(..) => true,
74             layout::Abi::ScalarPair(..) => {
75                 // Must be a fat pointer
76                 op.layout.ty.builtin_deref(true).is_some()
77             },
78             _ => false,
79         };
80     let normalized_op = if normalize {
81         ecx.try_read_immediate(op)?
82     } else {
83         match op.op {
84             Operand::Indirect(mplace) => Err(mplace),
85             Operand::Immediate(val) => Ok(val)
86         }
87     };
88     let val = match normalized_op {
89         Err(MemPlace { ptr, align, meta }) => {
90             // extract alloc-offset pair
91             assert!(meta.is_none());
92             let ptr = ptr.to_ptr()?;
93             let alloc = ecx.memory.get(ptr.alloc_id)?;
94             assert!(alloc.align >= align);
95             assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= op.layout.size.bytes());
96             let mut alloc = alloc.clone();
97             alloc.align = align;
98             // FIXME shouldn't it be the case that `mark_static_initialized` has already
99             // interned this?  I thought that is the entire point of that `FinishStatic` stuff?
100             let alloc = ecx.tcx.intern_const_alloc(alloc);
101             ConstValue::ByRef(ptr.alloc_id, alloc, ptr.offset)
102         },
103         Ok(Immediate::Scalar(x)) =>
104             ConstValue::Scalar(x.not_undef()?),
105         Ok(Immediate::ScalarPair(a, b)) =>
106             ConstValue::ScalarPair(a.not_undef()?, b.not_undef()?),
107     };
108     Ok(ty::Const { val, ty: op.layout.ty })
109 }
110
111 pub fn lazy_const_to_op<'tcx>(
112     ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
113     cnst: ty::LazyConst<'tcx>,
114     ty: ty::Ty<'tcx>,
115 ) -> EvalResult<'tcx, OpTy<'tcx>> {
116     let op = ecx.const_value_to_op(cnst)?;
117     Ok(OpTy { op, layout: ecx.layout_of(ty)? })
118 }
119
120 fn eval_body_and_ecx<'a, 'mir, 'tcx>(
121     tcx: TyCtxt<'a, 'tcx, 'tcx>,
122     cid: GlobalId<'tcx>,
123     mir: Option<&'mir mir::Mir<'tcx>>,
124     param_env: ty::ParamEnv<'tcx>,
125 ) -> (EvalResult<'tcx, MPlaceTy<'tcx>>, CompileTimeEvalContext<'a, 'mir, 'tcx>) {
126     // we start out with the best span we have
127     // and try improving it down the road when more information is available
128     let span = tcx.def_span(cid.instance.def_id());
129     let span = mir.map(|mir| mir.span).unwrap_or(span);
130     let mut ecx = EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new());
131     let r = eval_body_using_ecx(&mut ecx, cid, mir, param_env);
132     (r, ecx)
133 }
134
135 // Returns a pointer to where the result lives
136 fn eval_body_using_ecx<'mir, 'tcx>(
137     ecx: &mut CompileTimeEvalContext<'_, 'mir, 'tcx>,
138     cid: GlobalId<'tcx>,
139     mir: Option<&'mir mir::Mir<'tcx>>,
140     param_env: ty::ParamEnv<'tcx>,
141 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
142     debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
143     let tcx = ecx.tcx.tcx;
144     let mut mir = match mir {
145         Some(mir) => mir,
146         None => ecx.load_mir(cid.instance.def)?,
147     };
148     if let Some(index) = cid.promoted {
149         mir = &mir.promoted[index];
150     }
151     let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
152     assert!(!layout.is_unsized());
153     let ret = ecx.allocate(layout, MemoryKind::Stack);
154
155     let name = ty::tls::with(|tcx| tcx.item_path_str(cid.instance.def_id()));
156     let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
157     trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
158     assert!(mir.arg_count == 0);
159     ecx.push_stack_frame(
160         cid.instance,
161         mir.span,
162         mir,
163         Some(ret.into()),
164         StackPopCleanup::None { cleanup: false },
165     )?;
166
167     // The main interpreter loop.
168     ecx.run()?;
169
170     // Intern the result
171     let internally_mutable = !layout.ty.is_freeze(tcx, param_env, mir.span);
172     let is_static = tcx.is_static(cid.instance.def_id());
173     let mutability = if is_static == Some(hir::Mutability::MutMutable) || internally_mutable {
174         Mutability::Mutable
175     } else {
176         Mutability::Immutable
177     };
178     ecx.memory.intern_static(ret.ptr.to_ptr()?.alloc_id, mutability)?;
179
180     debug!("eval_body_using_ecx done: {:?}", *ret);
181     Ok(ret)
182 }
183
184 impl<'tcx> Into<EvalError<'tcx>> for ConstEvalError {
185     fn into(self) -> EvalError<'tcx> {
186         EvalErrorKind::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<'a, 'mir, 'tcx: 'a+'mir> {
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<'a, 'mir, 'tcx>,
233 }
234
235 impl<'a, 'mir, 'tcx> CompileTimeInterpreter<'a, '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 type CompileTimeEvalContext<'a, 'mir, 'tcx> =
306     EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, '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<'a, 'mir, 'tcx> interpret::Machine<'a, 'mir, 'tcx>
317     for CompileTimeInterpreter<'a, 'mir, 'tcx>
318 {
319     type MemoryKinds = !;
320     type PointerTag = ();
321
322     type FrameExtra = ();
323     type MemoryExtra = ();
324     type AllocExtra = ();
325
326     type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
327
328     const STATIC_KIND: Option<!> = None; // no copying of statics allowed
329
330     #[inline(always)]
331     fn enforce_validity(_ecx: &EvalContext<'a, 'mir, 'tcx, Self>) -> bool {
332         false // for now, we don't enforce validity
333     }
334
335     fn find_fn(
336         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
337         instance: ty::Instance<'tcx>,
338         args: &[OpTy<'tcx>],
339         dest: Option<PlaceTy<'tcx>>,
340         ret: Option<mir::BasicBlock>,
341     ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
342         debug!("eval_fn_call: {:?}", instance);
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(instance.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         // This is a const fn. Call it.
358         Ok(Some(match ecx.load_mir(instance.def) {
359             Ok(mir) => mir,
360             Err(err) => {
361                 if let EvalErrorKind::NoMirFor(ref path) = err.kind {
362                     return Err(
363                         ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
364                             .into(),
365                     );
366                 }
367                 return Err(err);
368             }
369         }))
370     }
371
372     fn call_intrinsic(
373         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
374         instance: ty::Instance<'tcx>,
375         args: &[OpTy<'tcx>],
376         dest: PlaceTy<'tcx>,
377     ) -> EvalResult<'tcx> {
378         if ecx.emulate_intrinsic(instance, args, dest)? {
379             return Ok(());
380         }
381         // An intrinsic that we do not support
382         let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
383         Err(
384             ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
385         )
386     }
387
388     fn ptr_op(
389         _ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
390         _bin_op: mir::BinOp,
391         _left: Scalar,
392         _left_layout: TyLayout<'tcx>,
393         _right: Scalar,
394         _right_layout: TyLayout<'tcx>,
395     ) -> EvalResult<'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<'a, 'tcx, 'tcx>,
404         _memory_extra: &(),
405     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
406         err!(ReadForeignStatic)
407     }
408
409     #[inline(always)]
410     fn adjust_static_allocation<'b>(
411         alloc: &'b Allocation,
412         _memory_extra: &(),
413     ) -> Cow<'b, Allocation<Self::PointerTag>> {
414         // We do not use a tag so we can just cheaply forward the reference
415         Cow::Borrowed(alloc)
416     }
417
418     fn box_alloc(
419         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
420         _dest: PlaceTy<'tcx>,
421     ) -> EvalResult<'tcx> {
422         Err(
423             ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
424         )
425     }
426
427     fn before_terminator(ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx> {
428         {
429             let steps = &mut ecx.machine.steps_since_detector_enabled;
430
431             *steps += 1;
432             if *steps < 0 {
433                 return Ok(());
434             }
435
436             *steps %= DETECTOR_SNAPSHOT_PERIOD;
437             if *steps != 0 {
438                 return Ok(());
439             }
440         }
441
442         let span = ecx.frame().span;
443         ecx.machine.loop_detector.observe_and_analyze(
444             &ecx.tcx,
445             span,
446             &ecx.memory,
447             &ecx.stack[..],
448         )
449     }
450
451     #[inline(always)]
452     fn tag_new_allocation(
453         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
454         ptr: Pointer,
455         _kind: MemoryKind<Self::MemoryKinds>,
456     ) -> Pointer {
457         ptr
458     }
459
460     #[inline(always)]
461     fn stack_push(
462         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
463     ) -> EvalResult<'tcx> {
464         Ok(())
465     }
466
467     /// Called immediately before a stack frame gets popped
468     #[inline(always)]
469     fn stack_pop(
470         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
471         _extra: (),
472     ) -> EvalResult<'tcx> {
473         Ok(())
474     }
475 }
476
477 /// Project to a field of a (variant of a) const
478 pub fn const_field<'a, 'tcx>(
479     tcx: TyCtxt<'a, 'tcx, 'tcx>,
480     param_env: ty::ParamEnv<'tcx>,
481     variant: Option<VariantIdx>,
482     field: mir::Field,
483     value: ty::Const<'tcx>,
484 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
485     trace!("const_field: {:?}, {:?}", field, value);
486     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
487     let result = (|| {
488         // get the operand again
489         let op = lazy_const_to_op(&ecx, ty::LazyConst::Evaluated(value), value.ty)?;
490         // downcast
491         let down = match variant {
492             None => op,
493             Some(variant) => ecx.operand_downcast(op, variant)?
494         };
495         // then project
496         let field = ecx.operand_field(down, field.index() as u64)?;
497         // and finally move back to the const world, always normalizing because
498         // this is not called for statics.
499         op_to_const(&ecx, field, true)
500     })();
501     result.map_err(|error| {
502         let err = error_to_const_error(&ecx, error);
503         err.report_as_error(ecx.tcx, "could not access field of constant");
504         ErrorHandled::Reported
505     })
506 }
507
508 pub fn const_variant_index<'a, 'tcx>(
509     tcx: TyCtxt<'a, 'tcx, 'tcx>,
510     param_env: ty::ParamEnv<'tcx>,
511     val: ty::Const<'tcx>,
512 ) -> EvalResult<'tcx, VariantIdx> {
513     trace!("const_variant_index: {:?}", val);
514     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
515     let op = lazy_const_to_op(&ecx, ty::LazyConst::Evaluated(val), val.ty)?;
516     Ok(ecx.read_discriminant(op)?.1)
517 }
518
519 pub fn error_to_const_error<'a, 'mir, 'tcx>(
520     ecx: &EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
521     mut error: EvalError<'tcx>
522 ) -> ConstEvalErr<'tcx> {
523     error.print_backtrace();
524     let stacktrace = ecx.generate_stacktrace(None);
525     ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
526 }
527
528 fn validate_and_turn_into_const<'a, 'tcx>(
529     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
530     constant: RawConst<'tcx>,
531     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
532 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
533     let cid = key.value;
534     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
535     let val = (|| {
536         let op = ecx.raw_const_to_mplace(constant)?.into();
537         // FIXME: Once the visitor infrastructure landed, change validation to
538         // work directly on `MPlaceTy`.
539         let mut ref_tracking = RefTracking::new(op);
540         while let Some((op, path)) = ref_tracking.todo.pop() {
541             ecx.validate_operand(
542                 op,
543                 path,
544                 Some(&mut ref_tracking),
545                 /* const_mode */ true,
546             )?;
547         }
548         // Now that we validated, turn this into a proper constant
549         let def_id = cid.instance.def.def_id();
550         let normalize = tcx.is_static(def_id).is_none() && cid.promoted.is_none();
551         op_to_const(&ecx, op, normalize)
552     })();
553
554     val.map_err(|error| {
555         let err = error_to_const_error(&ecx, error);
556         match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
557             Ok(mut diag) => {
558                 diag.note("The rules on what exactly is undefined behavior aren't clear, \
559                     so this check might be overzealous. Please open an issue on the rust compiler \
560                     repository if you believe it should not be considered undefined behavior",
561                 );
562                 diag.emit();
563                 ErrorHandled::Reported
564             }
565             Err(err) => err,
566         }
567     })
568 }
569
570 pub fn const_eval_provider<'a, 'tcx>(
571     tcx: TyCtxt<'a, 'tcx, 'tcx>,
572     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
573 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
574     // see comment in const_eval_provider for what we're doing here
575     if key.param_env.reveal == Reveal::All {
576         let mut key = key.clone();
577         key.param_env.reveal = Reveal::UserFacing;
578         match tcx.const_eval(key) {
579             // try again with reveal all as requested
580             Err(ErrorHandled::TooGeneric) => {
581                 // Promoteds should never be "too generic" when getting evaluated.
582                 // They either don't get evaluated, or we are in a monomorphic context
583                 assert!(key.value.promoted.is_none());
584             },
585             // dedupliate calls
586             other => return other,
587         }
588     }
589     tcx.const_eval_raw(key).and_then(|val| {
590         validate_and_turn_into_const(tcx, val, key)
591     })
592 }
593
594 pub fn const_eval_raw_provider<'a, 'tcx>(
595     tcx: TyCtxt<'a, 'tcx, 'tcx>,
596     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
597 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
598     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
599     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
600     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
601     // computed. For a large percentage of constants that will already have succeeded. Only
602     // associated constants of generic functions will fail due to not enough monomorphization
603     // information being available.
604
605     // In case we fail in the `UserFacing` variant, we just do the real computation.
606     if key.param_env.reveal == Reveal::All {
607         let mut key = key.clone();
608         key.param_env.reveal = Reveal::UserFacing;
609         match tcx.const_eval_raw(key) {
610             // try again with reveal all as requested
611             Err(ErrorHandled::TooGeneric) => {},
612             // dedupliate calls
613             other => return other,
614         }
615     }
616     // the first trace is for replicating an ice
617     // There's no tracking issue, but the next two lines concatenated link to the discussion on
618     // zulip. It's not really possible to test this, because it doesn't show up in diagnostics
619     // or MIR.
620     // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
621     // subject/anon_const_instance_printing/near/135980032
622     trace!("const eval: {}", key.value.instance);
623     trace!("const eval: {:?}", key);
624
625     let cid = key.value;
626     let def_id = cid.instance.def.def_id();
627
628     if let Some(id) = tcx.hir().as_local_node_id(def_id) {
629         let tables = tcx.typeck_tables_of(def_id);
630
631         // Do match-check before building MIR
632         if let Err(ErrorReported) = tcx.check_match(def_id) {
633             return Err(ErrorHandled::Reported)
634         }
635
636         if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(id) {
637             tcx.mir_const_qualif(def_id);
638         }
639
640         // Do not continue into miri if typeck errors occurred; it will fail horribly
641         if tables.tainted_by_errors {
642             return Err(ErrorHandled::Reported)
643         }
644     };
645
646     let (res, ecx) = eval_body_and_ecx(tcx, cid, None, key.param_env);
647     res.and_then(|place| {
648         Ok(RawConst {
649             alloc_id: place.to_ptr().expect("we allocated this ptr!").alloc_id,
650             ty: place.layout.ty
651         })
652     }).map_err(|error| {
653         let err = error_to_const_error(&ecx, error);
654         // errors in statics are always emitted as fatal errors
655         if tcx.is_static(def_id).is_some() {
656             let reported_err = err.report_as_error(ecx.tcx,
657                                                    "could not evaluate static initializer");
658             // Ensure that if the above error was either `TooGeneric` or `Reported`
659             // an error must be reported.
660             if tcx.sess.err_count() == 0 {
661                 tcx.sess.delay_span_bug(err.span,
662                                         &format!("static eval failure did not emit an error: {:#?}",
663                                                  reported_err));
664             }
665             reported_err
666         } else if def_id.is_local() {
667             // constant defined in this crate, we can figure out a lint level!
668             match tcx.describe_def(def_id) {
669                 // constants never produce a hard error at the definition site. Anything else is
670                 // a backwards compatibility hazard (and will break old versions of winapi for sure)
671                 //
672                 // note that validation may still cause a hard error on this very same constant,
673                 // because any code that existed before validation could not have failed validation
674                 // thus preventing such a hard error from being a backwards compatibility hazard
675                 Some(Def::Const(_)) | Some(Def::AssociatedConst(_)) => {
676                     let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
677                     err.report_as_lint(
678                         tcx.at(tcx.def_span(def_id)),
679                         "any use of this value will cause an error",
680                         node_id,
681                     )
682                 },
683                 // promoting runtime code is only allowed to error if it references broken constants
684                 // any other kind of error will be reported to the user as a deny-by-default lint
685                 _ => if let Some(p) = cid.promoted {
686                     let span = tcx.optimized_mir(def_id).promoted[p].span;
687                     if let EvalErrorKind::ReferencedConstant = err.error {
688                         err.report_as_error(
689                             tcx.at(span),
690                             "evaluation of constant expression failed",
691                         )
692                     } else {
693                         err.report_as_lint(
694                             tcx.at(span),
695                             "reaching this expression at runtime will panic or abort",
696                             tcx.hir().as_local_node_id(def_id).unwrap(),
697                         )
698                     }
699                 // anything else (array lengths, enum initializers, constant patterns) are reported
700                 // as hard errors
701                 } else {
702                     err.report_as_error(
703                         ecx.tcx,
704                         "evaluation of constant value failed",
705                     )
706                 },
707             }
708         } else {
709             // use of broken constant from other crate
710             err.report_as_error(ecx.tcx, "could not evaluate constant")
711         }
712     })
713 }