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