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