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