1 // Not in interpret to make sure we do not use private implementation details
5 use std::borrow::{Borrow, Cow};
7 use std::collections::hash_map::Entry;
8 use std::convert::TryInto;
10 use rustc::hir::def::DefKind;
11 use rustc::hir::def_id::DefId;
12 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled, ScalarMaybeUndef};
14 use rustc::ty::{self, TyCtxt};
15 use rustc::ty::layout::{self, LayoutOf, VariantIdx};
16 use rustc::ty::subst::Subst;
17 use rustc::traits::Reveal;
18 use rustc_data_structures::fx::FxHashMap;
20 use syntax::source_map::{Span, DUMMY_SP};
22 use crate::interpret::{self,
23 PlaceTy, MPlaceTy, OpTy, ImmTy, Immediate, Scalar, Pointer,
25 InterpResult, InterpErrorInfo, GlobalId, InterpCx, StackPopCleanup,
26 Allocation, AllocId, MemoryKind, Memory,
27 snapshot, RefTracking, intern_const_alloc_recursive,
30 /// Number of steps until the detector even starts doing anything.
31 /// Also, a warning is shown to the user when this number is reached.
32 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
33 /// The number of steps between loop detector snapshots.
34 /// Should be a power of two for performance reasons.
35 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
37 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
38 /// `simd_shuffle` and const patterns in match arms.
40 /// The function containing the `match` that is currently being analyzed may have generic bounds
41 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
42 /// of a function's generic parameter will require knowledge about the bounds on the generic
43 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
44 pub(crate) fn mk_eval_cx<'mir, 'tcx>(
47 param_env: ty::ParamEnv<'tcx>,
48 ) -> CompileTimeEvalContext<'mir, 'tcx> {
49 debug!("mk_eval_cx: {:?}", param_env);
50 InterpCx::new(tcx.at(span), param_env, CompileTimeInterpreter::new(), Default::default())
53 pub(crate) fn eval_promoted<'mir, 'tcx>(
56 body: &'mir mir::Body<'tcx>,
57 param_env: ty::ParamEnv<'tcx>,
58 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
59 let span = tcx.def_span(cid.instance.def_id());
60 let mut ecx = mk_eval_cx(tcx, span, param_env);
61 eval_body_using_ecx(&mut ecx, cid, body, param_env)
65 ecx: &CompileTimeEvalContext<'_, 'tcx>,
67 ) -> &'tcx ty::Const<'tcx> {
68 // We do not have value optmizations for everything.
69 // Only scalars and slices, since they are very common.
70 // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result
71 // from scalar unions that are initialized with one of their zero sized variants. We could
72 // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all
73 // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
75 let try_as_immediate = match op.layout.abi {
76 layout::Abi::Scalar(..) => true,
77 layout::Abi::ScalarPair(..) => match op.layout.ty.sty {
78 ty::Ref(_, inner, _) => match inner.sty {
79 ty::Slice(elem) => elem == ecx.tcx.types.u8,
87 let immediate = if try_as_immediate {
88 Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
90 // It is guaranteed that any non-slice scalar pair is actually ByRef here.
91 // When we come back from raw const eval, we are always by-ref. The only way our op here is
92 // by-val is if we are in const_field, i.e., if this is (a field of) something that we
93 // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
94 // structs containing such.
97 let val = match immediate {
99 let ptr = mplace.ptr.to_ptr().unwrap();
100 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
101 ConstValue::ByRef { offset: ptr.offset, align: mplace.align, alloc }
103 // see comment on `let try_as_immediate` above
104 Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x {
105 ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s),
106 ScalarMaybeUndef::Undef => {
107 // When coming out of "normal CTFE", we'll always have an `Indirect` operand as
108 // argument and we will not need this. The only way we can already have an
109 // `Immediate` is when we are called from `const_field`, and that `Immediate`
110 // comes from a constant so it can happen have `Undef`, because the indirect
111 // memory that was read had undefined bytes.
112 let mplace = op.assert_mem_place();
113 let ptr = mplace.ptr.to_ptr().unwrap();
114 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
115 ConstValue::ByRef { offset: ptr.offset, align: mplace.align, alloc }
118 Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => {
119 let (data, start) = match a.not_undef().unwrap() {
120 Scalar::Ptr(ptr) => (
121 ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
124 Scalar::Raw { .. } => (
125 ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(
131 let len = b.to_usize(&ecx.tcx.tcx).unwrap();
132 let start = start.try_into().unwrap();
133 let len: usize = len.try_into().unwrap();
141 ecx.tcx.mk_const(ty::Const { val, ty: op.layout.ty })
144 // Returns a pointer to where the result lives
145 fn eval_body_using_ecx<'mir, 'tcx>(
146 ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
148 body: &'mir mir::Body<'tcx>,
149 param_env: ty::ParamEnv<'tcx>,
150 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
151 debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
152 let tcx = ecx.tcx.tcx;
153 let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
154 assert!(!layout.is_unsized());
155 let ret = ecx.allocate(layout, MemoryKind::Stack);
157 let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
158 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
159 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
160 assert!(body.arg_count == 0);
161 ecx.push_stack_frame(
166 StackPopCleanup::None { cleanup: false },
169 // The main interpreter loop.
173 intern_const_alloc_recursive(
175 cid.instance.def_id(),
180 debug!("eval_body_using_ecx done: {:?}", *ret);
184 #[derive(Clone, Debug)]
185 enum ConstEvalError {
189 impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalError {
190 fn into(self) -> InterpErrorInfo<'tcx> {
191 err_unsup!(Unsupported(self.to_string())).into()
195 impl fmt::Display for ConstEvalError {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 use self::ConstEvalError::*;
199 NeedsRfc(ref msg) => {
202 "\"{}\" needs an rfc before being allowed inside constants",
210 impl Error for ConstEvalError {
211 fn description(&self) -> &str {
212 use self::ConstEvalError::*;
214 NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
218 fn cause(&self) -> Option<&dyn Error> {
223 // Extra machine state for CTFE, and the Machine instance
224 pub struct CompileTimeInterpreter<'mir, 'tcx> {
225 /// When this value is negative, it indicates the number of interpreter
226 /// steps *until* the loop detector is enabled. When it is positive, it is
227 /// the number of steps after the detector has been enabled modulo the loop
229 pub(super) steps_since_detector_enabled: isize,
231 /// Extra state to detect loops.
232 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>,
235 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
237 CompileTimeInterpreter {
238 loop_detector: Default::default(),
239 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
244 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
246 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
249 FxHashMap::contains_key(self, k)
253 fn insert(&mut self, k: K, v: V) -> Option<V>
255 FxHashMap::insert(self, k, v)
259 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
262 FxHashMap::remove(self, k)
266 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
268 .filter_map(move |(k, v)| f(k, &*v))
276 vacant: impl FnOnce() -> Result<V, E>
283 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
292 vacant: impl FnOnce() -> Result<V, E>
293 ) -> Result<&mut V, E>
295 match self.entry(k) {
296 Entry::Occupied(e) => Ok(e.into_mut()),
297 Entry::Vacant(e) => {
305 crate type CompileTimeEvalContext<'mir, 'tcx> =
306 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
308 impl interpret::MayLeak for ! {
310 fn may_leak(self) -> bool {
311 // `self` is uninhabited
316 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
317 type MemoryKinds = !;
318 type PointerTag = ();
321 type FrameExtra = ();
322 type MemoryExtra = ();
323 type AllocExtra = ();
325 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
327 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
330 fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
331 false // for now, we don't enforce validity
335 ecx: &mut InterpCx<'mir, 'tcx, Self>,
336 instance: ty::Instance<'tcx>,
338 dest: Option<PlaceTy<'tcx>>,
339 ret: Option<mir::BasicBlock>,
340 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
341 debug!("eval_fn_call: {:?}", instance);
342 // Only check non-glue functions
343 if let ty::InstanceDef::Item(def_id) = instance.def {
344 // Execution might have wandered off into other crates, so we cannot do a stability-
345 // sensitive check here. But we can at least rule out functions that are not const
347 if !ecx.tcx.is_const_fn_raw(def_id) {
348 // Some functions we support even if they are non-const -- but avoid testing
349 // that for const fn! We certainly do *not* want to actually call the fn
350 // though, so be sure we return here.
351 return if ecx.hook_fn(instance, args, dest)? {
352 ecx.goto_block(ret)?; // fully evaluated and done
355 throw_unsup_format!("calling non-const function `{}`", instance)
359 // This is a const fn. Call it.
360 Ok(Some(match ecx.load_mir(instance.def) {
363 if let err_unsup!(NoMirFor(ref path)) = err.kind {
365 ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
375 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
377 _args: &[OpTy<'tcx>],
378 _dest: Option<PlaceTy<'tcx>>,
379 _ret: Option<mir::BasicBlock>,
380 ) -> InterpResult<'tcx> {
385 ecx: &mut InterpCx<'mir, 'tcx, Self>,
386 instance: ty::Instance<'tcx>,
389 ) -> InterpResult<'tcx> {
390 if ecx.emulate_intrinsic(instance, args, dest)? {
393 // An intrinsic that we do not support
394 let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
396 ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
401 _mem: &Memory<'mir, 'tcx, Self>,
403 ) -> InterpResult<'tcx, u64> {
405 ConstEvalError::NeedsRfc("pointer-to-integer cast".to_string()).into(),
410 _ecx: &InterpCx<'mir, 'tcx, Self>,
414 ) -> InterpResult<'tcx, (Scalar, bool)> {
416 ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
420 fn find_foreign_static(
423 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
424 throw_unsup!(ReadForeignStatic)
428 fn tag_allocation<'b>(
431 alloc: Cow<'b, Allocation>,
432 _kind: Option<MemoryKind<!>>,
433 ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
434 // We do not use a tag so we can just cheaply forward the allocation
439 fn tag_static_base_pointer(
442 ) -> Self::PointerTag {
447 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
448 _dest: PlaceTy<'tcx>,
449 ) -> InterpResult<'tcx> {
451 ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
455 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
457 let steps = &mut ecx.machine.steps_since_detector_enabled;
464 *steps %= DETECTOR_SNAPSHOT_PERIOD;
470 let span = ecx.frame().span;
471 ecx.machine.loop_detector.observe_and_analyze(
480 fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
484 /// Called immediately before a stack frame gets popped.
486 fn stack_pop(_ecx: &mut InterpCx<'mir, 'tcx, Self>, _extra: ()) -> InterpResult<'tcx> {
491 /// Extracts a field of a (variant of a) const.
492 // this function uses `unwrap` copiously, because an already validated constant must have valid
493 // fields and can thus never fail outside of compiler bugs
494 pub fn const_field<'tcx>(
496 param_env: ty::ParamEnv<'tcx>,
497 variant: Option<VariantIdx>,
499 value: &'tcx ty::Const<'tcx>,
500 ) -> &'tcx ty::Const<'tcx> {
501 trace!("const_field: {:?}, {:?}", field, value);
502 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
503 // get the operand again
504 let op = ecx.eval_const_to_op(value, None).unwrap();
506 let down = match variant {
508 Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
511 let field = ecx.operand_field(down, field.index() as u64).unwrap();
512 // and finally move back to the const world, always normalizing because
513 // this is not called for statics.
514 op_to_const(&ecx, field)
517 // this function uses `unwrap` copiously, because an already validated constant must have valid
518 // fields and can thus never fail outside of compiler bugs
519 pub fn const_variant_index<'tcx>(
521 param_env: ty::ParamEnv<'tcx>,
522 val: &'tcx ty::Const<'tcx>,
524 trace!("const_variant_index: {:?}", val);
525 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
526 let op = ecx.eval_const_to_op(val, None).unwrap();
527 ecx.read_discriminant(op).unwrap().1
530 pub fn error_to_const_error<'mir, 'tcx>(
531 ecx: &InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>,
532 mut error: InterpErrorInfo<'tcx>,
533 ) -> ConstEvalErr<'tcx> {
534 error.print_backtrace();
535 let stacktrace = ecx.generate_stacktrace(None);
536 ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
539 fn validate_and_turn_into_const<'tcx>(
541 constant: RawConst<'tcx>,
542 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
543 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
545 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
547 let mplace = ecx.raw_const_to_mplace(constant)?;
548 let mut ref_tracking = RefTracking::new(mplace);
549 while let Some((mplace, path)) = ref_tracking.todo.pop() {
550 ecx.validate_operand(
553 Some(&mut ref_tracking),
556 // Now that we validated, turn this into a proper constant.
557 // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
558 // whether they become immediates.
559 let def_id = cid.instance.def.def_id();
560 if tcx.is_static(def_id) || cid.promoted.is_some() {
561 let ptr = mplace.ptr.to_ptr()?;
562 Ok(tcx.mk_const(ty::Const {
563 val: ConstValue::ByRef {
566 alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
568 ty: mplace.layout.ty,
571 Ok(op_to_const(&ecx, mplace.into()))
575 val.map_err(|error| {
576 let err = error_to_const_error(&ecx, error);
577 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
579 diag.note("The rules on what exactly is undefined behavior aren't clear, \
580 so this check might be overzealous. Please open an issue on the rust compiler \
581 repository if you believe it should not be considered undefined behavior",
584 ErrorHandled::Reported
591 pub fn const_eval_provider<'tcx>(
593 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
594 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
595 // see comment in const_eval_provider for what we're doing here
596 if key.param_env.reveal == Reveal::All {
597 let mut key = key.clone();
598 key.param_env.reveal = Reveal::UserFacing;
599 match tcx.const_eval(key) {
600 // try again with reveal all as requested
601 Err(ErrorHandled::TooGeneric) => {
602 // Promoteds should never be "too generic" when getting evaluated.
603 // They either don't get evaluated, or we are in a monomorphic context
604 assert!(key.value.promoted.is_none());
607 other => return other,
610 tcx.const_eval_raw(key).and_then(|val| {
611 validate_and_turn_into_const(tcx, val, key)
615 pub fn const_eval_raw_provider<'tcx>(
617 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
618 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
619 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
620 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
621 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
622 // computed. For a large percentage of constants that will already have succeeded. Only
623 // associated constants of generic functions will fail due to not enough monomorphization
624 // information being available.
626 // In case we fail in the `UserFacing` variant, we just do the real computation.
627 if key.param_env.reveal == Reveal::All {
628 let mut key = key.clone();
629 key.param_env.reveal = Reveal::UserFacing;
630 match tcx.const_eval_raw(key) {
631 // try again with reveal all as requested
632 Err(ErrorHandled::TooGeneric) => {},
634 other => return other,
637 if cfg!(debug_assertions) {
638 // Make sure we format the instance even if we do not print it.
639 // This serves as a regression test against an ICE on printing.
640 // The next two lines concatenated contain some discussion:
641 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
642 // subject/anon_const_instance_printing/near/135980032
643 let instance = key.value.instance.to_string();
644 trace!("const eval: {:?} ({})", key, instance);
648 let def_id = cid.instance.def.def_id();
650 if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
651 return Err(ErrorHandled::Reported);
654 let span = tcx.def_span(cid.instance.def_id());
655 let mut ecx = InterpCx::new(
658 CompileTimeInterpreter::new(),
662 let res = ecx.load_mir(cid.instance.def);
664 if let Some(index) = cid.promoted {
665 &body.promoted[index]
670 |body| eval_body_using_ecx(&mut ecx, cid, body, key.param_env)
673 alloc_id: place.ptr.assert_ptr().alloc_id,
677 let err = error_to_const_error(&ecx, error);
678 // errors in statics are always emitted as fatal errors
679 if tcx.is_static(def_id) {
680 // Ensure that if the above error was either `TooGeneric` or `Reported`
681 // an error must be reported.
682 let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer");
683 tcx.sess.delay_span_bug(
685 &format!("static eval failure did not emit an error: {:#?}", v)
688 } else if def_id.is_local() {
689 // constant defined in this crate, we can figure out a lint level!
690 match tcx.def_kind(def_id) {
691 // constants never produce a hard error at the definition site. Anything else is
692 // a backwards compatibility hazard (and will break old versions of winapi for sure)
694 // note that validation may still cause a hard error on this very same constant,
695 // because any code that existed before validation could not have failed validation
696 // thus preventing such a hard error from being a backwards compatibility hazard
697 Some(DefKind::Const) | Some(DefKind::AssocConst) => {
698 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
700 tcx.at(tcx.def_span(def_id)),
701 "any use of this value will cause an error",
706 // promoting runtime code is only allowed to error if it references broken constants
707 // any other kind of error will be reported to the user as a deny-by-default lint
708 _ => if let Some(p) = cid.promoted {
709 let span = tcx.promoted_mir(def_id)[p].span;
710 if let err_inval!(ReferencedConstant) = err.error {
713 "evaluation of constant expression failed",
718 "reaching this expression at runtime will panic or abort",
719 tcx.hir().as_local_hir_id(def_id).unwrap(),
723 // anything else (array lengths, enum initializers, constant patterns) are reported
728 "evaluation of constant value failed",
733 // use of broken constant from other crate
734 err.report_as_error(ecx.tcx, "could not evaluate constant")