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;
9 use rustc::hir::def::DefKind;
10 use rustc::hir::def_id::DefId;
11 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
13 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
14 use rustc::ty::layout::{self, LayoutOf, VariantIdx, Size};
15 use rustc::ty::subst::Subst;
16 use rustc::traits::Reveal;
17 use rustc::util::common::ErrorReported;
18 use rustc_data_structures::fx::FxHashMap;
20 use syntax::ast::Mutability;
21 use syntax::source_map::{Span, DUMMY_SP};
23 use crate::interpret::{self,
24 PlaceTy, MPlaceTy, MemPlace, OpTy, ImmTy, Immediate, Scalar,
26 EvalResult, EvalError, InterpError, GlobalId, InterpretCx, StackPopCleanup,
27 Allocation, AllocId, MemoryKind,
28 snapshot, RefTracking,
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;
38 /// The `InterpretCx` is only meant to be used to do field and index projections into constants for
39 /// `simd_shuffle` and const patterns in match arms.
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 pub(crate) fn mk_eval_cx<'a, 'mir, 'tcx>(
46 tcx: TyCtxt<'a, 'tcx, 'tcx>,
48 param_env: ty::ParamEnv<'tcx>,
49 ) -> CompileTimeEvalContext<'a, 'mir, 'tcx> {
50 debug!("mk_eval_cx: {:?}", param_env);
51 InterpretCx::new(tcx.at(span), param_env, CompileTimeInterpreter::new())
54 pub(crate) fn eval_promoted<'a, 'mir, 'tcx>(
55 tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 mir: &'mir mir::Mir<'tcx>,
58 param_env: ty::ParamEnv<'tcx>,
59 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
60 let span = tcx.def_span(cid.instance.def_id());
61 let mut ecx = mk_eval_cx(tcx, span, param_env);
62 eval_body_using_ecx(&mut ecx, cid, mir, param_env)
65 fn mplace_to_const<'tcx>(
66 ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
67 mplace: MPlaceTy<'tcx>,
68 ) -> ty::Const<'tcx> {
69 let MemPlace { ptr, align, meta } = *mplace;
70 // extract alloc-offset pair
71 assert!(meta.is_none());
72 let ptr = ptr.to_ptr().unwrap();
73 let alloc = ecx.memory.get(ptr.alloc_id).unwrap();
74 assert!(alloc.align >= align);
75 assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= mplace.layout.size.bytes());
76 let mut alloc = alloc.clone();
78 // FIXME shouldn't it be the case that `mark_static_initialized` has already
79 // interned this? I thought that is the entire point of that `FinishStatic` stuff?
80 let alloc = ecx.tcx.intern_const_alloc(alloc);
81 let val = ConstValue::ByRef(ptr, alloc);
82 ty::Const { val, ty: mplace.layout.ty }
86 ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
88 ) -> ty::Const<'tcx> {
89 // We do not normalize just any data. Only non-union scalars and slices.
90 let normalize = match op.layout.abi {
91 layout::Abi::Scalar(..) => op.layout.ty.ty_adt_def().map_or(true, |adt| !adt.is_union()),
92 layout::Abi::ScalarPair(..) => op.layout.ty.is_slice(),
95 let normalized_op = if normalize {
96 Err(*ecx.read_immediate(op).expect("normalization works on validated constants"))
100 let val = match normalized_op {
101 Ok(mplace) => return mplace_to_const(ecx, mplace),
102 Err(Immediate::Scalar(x)) =>
103 ConstValue::Scalar(x.not_undef().unwrap()),
104 Err(Immediate::ScalarPair(a, b)) =>
105 ConstValue::Slice(a.not_undef().unwrap(), b.to_usize(ecx).unwrap()),
107 ty::Const { val, ty: op.layout.ty }
110 // Returns a pointer to where the result lives
111 fn eval_body_using_ecx<'mir, 'tcx>(
112 ecx: &mut CompileTimeEvalContext<'_, 'mir, 'tcx>,
114 mir: &'mir mir::Mir<'tcx>,
115 param_env: ty::ParamEnv<'tcx>,
116 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
117 debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
118 let tcx = ecx.tcx.tcx;
119 let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
120 assert!(!layout.is_unsized());
121 let ret = ecx.allocate(layout, MemoryKind::Stack);
123 let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
124 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
125 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
126 assert!(mir.arg_count == 0);
127 ecx.push_stack_frame(
132 StackPopCleanup::None { cleanup: false },
135 // The main interpreter loop.
139 let mutability = if tcx.is_mutable_static(cid.instance.def_id()) ||
140 !layout.ty.is_freeze(tcx, param_env, mir.span) {
143 Mutability::Immutable
145 ecx.memory.intern_static(ret.ptr.to_ptr()?.alloc_id, mutability)?;
147 debug!("eval_body_using_ecx done: {:?}", *ret);
151 impl<'tcx> Into<EvalError<'tcx>> for ConstEvalError {
152 fn into(self) -> EvalError<'tcx> {
153 InterpError::MachineError(self.to_string()).into()
157 #[derive(Clone, Debug)]
158 enum ConstEvalError {
162 impl fmt::Display for ConstEvalError {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 use self::ConstEvalError::*;
166 NeedsRfc(ref msg) => {
169 "\"{}\" needs an rfc before being allowed inside constants",
177 impl Error for ConstEvalError {
178 fn description(&self) -> &str {
179 use self::ConstEvalError::*;
181 NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
185 fn cause(&self) -> Option<&dyn Error> {
190 // Extra machine state for CTFE, and the Machine instance
191 pub struct CompileTimeInterpreter<'a, 'mir, 'tcx: 'a+'mir> {
192 /// When this value is negative, it indicates the number of interpreter
193 /// steps *until* the loop detector is enabled. When it is positive, it is
194 /// the number of steps after the detector has been enabled modulo the loop
196 pub(super) steps_since_detector_enabled: isize,
198 /// Extra state to detect loops.
199 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'a, 'mir, 'tcx>,
202 impl<'a, 'mir, 'tcx> CompileTimeInterpreter<'a, 'mir, 'tcx> {
204 CompileTimeInterpreter {
205 loop_detector: Default::default(),
206 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
211 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
213 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
216 FxHashMap::contains_key(self, k)
220 fn insert(&mut self, k: K, v: V) -> Option<V>
222 FxHashMap::insert(self, k, v)
226 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
229 FxHashMap::remove(self, k)
233 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
235 .filter_map(move |(k, v)| f(k, &*v))
243 vacant: impl FnOnce() -> Result<V, E>
250 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
259 vacant: impl FnOnce() -> Result<V, E>
260 ) -> Result<&mut V, E>
262 match self.entry(k) {
263 Entry::Occupied(e) => Ok(e.into_mut()),
264 Entry::Vacant(e) => {
272 type CompileTimeEvalContext<'a, 'mir, 'tcx> =
273 InterpretCx<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>;
275 impl interpret::MayLeak for ! {
277 fn may_leak(self) -> bool {
278 // `self` is uninhabited
283 impl<'a, 'mir, 'tcx> interpret::Machine<'a, 'mir, 'tcx>
284 for CompileTimeInterpreter<'a, 'mir, 'tcx>
286 type MemoryKinds = !;
287 type PointerTag = ();
289 type FrameExtra = ();
290 type MemoryExtra = ();
291 type AllocExtra = ();
293 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
295 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
298 fn enforce_validity(_ecx: &InterpretCx<'a, 'mir, 'tcx, Self>) -> bool {
299 false // for now, we don't enforce validity
303 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
304 instance: ty::Instance<'tcx>,
306 dest: Option<PlaceTy<'tcx>>,
307 ret: Option<mir::BasicBlock>,
308 ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
309 debug!("eval_fn_call: {:?}", instance);
310 // Only check non-glue functions
311 if let ty::InstanceDef::Item(def_id) = instance.def {
312 // Execution might have wandered off into other crates, so we cannot to a stability-
313 // sensitive check here. But we can at least rule out functions that are not const
315 if !ecx.tcx.is_const_fn_raw(def_id) {
316 // Some functions we support even if they are non-const -- but avoid testing
317 // that for const fn! We certainly do *not* want to actually call the fn
318 // though, so be sure we return here.
319 return if ecx.hook_fn(instance, args, dest)? {
320 ecx.goto_block(ret)?; // fully evaluated and done
323 err!(MachineError(format!("calling non-const function `{}`", instance)))
327 // This is a const fn. Call it.
328 Ok(Some(match ecx.load_mir(instance.def) {
331 if let InterpError::NoMirFor(ref path) = err.kind {
333 ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
343 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
344 instance: ty::Instance<'tcx>,
347 ) -> EvalResult<'tcx> {
348 if ecx.emulate_intrinsic(instance, args, dest)? {
351 // An intrinsic that we do not support
352 let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
354 ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
359 _ecx: &InterpretCx<'a, 'mir, 'tcx, Self>,
363 ) -> EvalResult<'tcx, (Scalar, bool)> {
365 ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
369 fn find_foreign_static(
371 _tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
373 ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
374 err!(ReadForeignStatic)
378 fn adjust_static_allocation<'b>(
379 alloc: &'b Allocation,
381 ) -> Cow<'b, Allocation<Self::PointerTag>> {
382 // We do not use a tag so we can just cheaply forward the reference
389 _extra: &Self::MemoryExtra,
390 _kind: MemoryKind<!>,
391 ) -> (Self::AllocExtra, Self::PointerTag) {
396 _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
397 _dest: PlaceTy<'tcx>,
398 ) -> EvalResult<'tcx> {
400 ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
404 fn before_terminator(ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx> {
406 let steps = &mut ecx.machine.steps_since_detector_enabled;
413 *steps %= DETECTOR_SNAPSHOT_PERIOD;
419 let span = ecx.frame().span;
420 ecx.machine.loop_detector.observe_and_analyze(
430 _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
431 ) -> EvalResult<'tcx> {
435 /// Called immediately before a stack frame gets popped.
438 _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
440 ) -> EvalResult<'tcx> {
445 /// Projects to a field of a (variant of a) const.
446 // this function uses `unwrap` copiously, because an already validated constant must have valid
447 // fields and can thus never fail outside of compiler bugs
448 pub fn const_field<'a, 'tcx>(
449 tcx: TyCtxt<'a, 'tcx, 'tcx>,
450 param_env: ty::ParamEnv<'tcx>,
451 variant: Option<VariantIdx>,
453 value: ty::Const<'tcx>,
454 ) -> ty::Const<'tcx> {
455 trace!("const_field: {:?}, {:?}", field, value);
456 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
457 // get the operand again
458 let op = ecx.eval_const_to_op(value, None).unwrap();
460 let down = match variant {
462 Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
465 let field = ecx.operand_field(down, field.index() as u64).unwrap();
466 // and finally move back to the const world, always normalizing because
467 // this is not called for statics.
468 op_to_const(&ecx, field)
471 // this function uses `unwrap` copiously, because an already validated constant must have valid
472 // fields and can thus never fail outside of compiler bugs
473 pub fn const_variant_index<'a, 'tcx>(
474 tcx: TyCtxt<'a, 'tcx, 'tcx>,
475 param_env: ty::ParamEnv<'tcx>,
476 val: ty::Const<'tcx>,
478 trace!("const_variant_index: {:?}", val);
479 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
480 let op = ecx.eval_const_to_op(val, None).unwrap();
481 ecx.read_discriminant(op).unwrap().1
484 pub fn error_to_const_error<'a, 'mir, 'tcx>(
485 ecx: &InterpretCx<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
486 mut error: EvalError<'tcx>
487 ) -> ConstEvalErr<'tcx> {
488 error.print_backtrace();
489 let stacktrace = ecx.generate_stacktrace(None);
490 ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
493 fn validate_and_turn_into_const<'a, 'tcx>(
494 tcx: TyCtxt<'a, 'tcx, 'tcx>,
495 constant: RawConst<'tcx>,
496 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
497 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
499 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
501 let mplace = ecx.raw_const_to_mplace(constant)?;
502 let mut ref_tracking = RefTracking::new(mplace);
503 while let Some((mplace, path)) = ref_tracking.todo.pop() {
504 ecx.validate_operand(
507 Some(&mut ref_tracking),
511 // Now that we validated, turn this into a proper constant.
512 let def_id = cid.instance.def.def_id();
513 if tcx.is_static(def_id) || cid.promoted.is_some() {
514 Ok(mplace_to_const(&ecx, mplace))
516 Ok(op_to_const(&ecx, mplace.into()))
520 val.map_err(|error| {
521 let err = error_to_const_error(&ecx, error);
522 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
524 diag.note("The rules on what exactly is undefined behavior aren't clear, \
525 so this check might be overzealous. Please open an issue on the rust compiler \
526 repository if you believe it should not be considered undefined behavior",
529 ErrorHandled::Reported
536 pub fn const_eval_provider<'a, 'tcx>(
537 tcx: TyCtxt<'a, 'tcx, 'tcx>,
538 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
539 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
540 // see comment in const_eval_provider for what we're doing here
541 if key.param_env.reveal == Reveal::All {
542 let mut key = key.clone();
543 key.param_env.reveal = Reveal::UserFacing;
544 match tcx.const_eval(key) {
545 // try again with reveal all as requested
546 Err(ErrorHandled::TooGeneric) => {
547 // Promoteds should never be "too generic" when getting evaluated.
548 // They either don't get evaluated, or we are in a monomorphic context
549 assert!(key.value.promoted.is_none());
552 other => return other,
555 tcx.const_eval_raw(key).and_then(|val| {
556 validate_and_turn_into_const(tcx, val, key)
560 pub fn const_eval_raw_provider<'a, 'tcx>(
561 tcx: TyCtxt<'a, 'tcx, 'tcx>,
562 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
563 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
564 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
565 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
566 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
567 // computed. For a large percentage of constants that will already have succeeded. Only
568 // associated constants of generic functions will fail due to not enough monomorphization
569 // information being available.
571 // In case we fail in the `UserFacing` variant, we just do the real computation.
572 if key.param_env.reveal == Reveal::All {
573 let mut key = key.clone();
574 key.param_env.reveal = Reveal::UserFacing;
575 match tcx.const_eval_raw(key) {
576 // try again with reveal all as requested
577 Err(ErrorHandled::TooGeneric) => {},
579 other => return other,
582 if cfg!(debug_assertions) {
583 // Make sure we format the instance even if we do not print it.
584 // This serves as a regression test against an ICE on printing.
585 // The next two lines concatenated contain some discussion:
586 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
587 // subject/anon_const_instance_printing/near/135980032
588 let instance = key.value.instance.to_string();
589 trace!("const eval: {:?} ({})", key, instance);
593 let def_id = cid.instance.def.def_id();
595 if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
596 return Err(ErrorHandled::Reported);
599 let span = tcx.def_span(cid.instance.def_id());
600 let mut ecx = InterpretCx::new(tcx.at(span), key.param_env, CompileTimeInterpreter::new());
602 let res = ecx.load_mir(cid.instance.def);
604 if let Some(index) = cid.promoted {
610 |mir| eval_body_using_ecx(&mut ecx, cid, mir, key.param_env)
613 alloc_id: place.to_ptr().expect("we allocated this ptr!").alloc_id,
617 let err = error_to_const_error(&ecx, error);
618 // errors in statics are always emitted as fatal errors
619 if tcx.is_static(def_id) {
620 // Ensure that if the above error was either `TooGeneric` or `Reported`
621 // an error must be reported.
622 let reported_err = tcx.sess.track_errors(|| {
623 err.report_as_error(ecx.tcx,
624 "could not evaluate static initializer")
628 tcx.sess.delay_span_bug(err.span,
629 &format!("static eval failure did not emit an error: {:#?}",
633 Err(ErrorReported) => ErrorHandled::Reported,
635 } else if def_id.is_local() {
636 // constant defined in this crate, we can figure out a lint level!
637 match tcx.def_kind(def_id) {
638 // constants never produce a hard error at the definition site. Anything else is
639 // a backwards compatibility hazard (and will break old versions of winapi for sure)
641 // note that validation may still cause a hard error on this very same constant,
642 // because any code that existed before validation could not have failed validation
643 // thus preventing such a hard error from being a backwards compatibility hazard
644 Some(DefKind::Const) | Some(DefKind::AssociatedConst) => {
645 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
647 tcx.at(tcx.def_span(def_id)),
648 "any use of this value will cause an error",
653 // promoting runtime code is only allowed to error if it references broken constants
654 // any other kind of error will be reported to the user as a deny-by-default lint
655 _ => if let Some(p) = cid.promoted {
656 let span = tcx.optimized_mir(def_id).promoted[p].span;
657 if let InterpError::ReferencedConstant = err.error {
660 "evaluation of constant expression failed",
665 "reaching this expression at runtime will panic or abort",
666 tcx.hir().as_local_hir_id(def_id).unwrap(),
670 // anything else (array lengths, enum initializers, constant patterns) are reported
675 "evaluation of constant value failed",
680 // use of broken constant from other crate
681 err.report_as_error(ecx.tcx, "could not evaluate constant")