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