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