1 use super::{CompileTimeEvalContext, CompileTimeInterpreter, ConstEvalErr, MemoryExtra};
2 use crate::interpret::eval_nullary_intrinsic;
3 use crate::interpret::{
4 intern_const_alloc_recursive, Allocation, ConstValue, GlobalId, Immediate, InternKind,
5 InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RawConst, RefTracking, Scalar,
6 ScalarMaybeUninit, StackPopCleanup,
9 use rustc_hir::def::DefKind;
10 use rustc_middle::mir;
11 use rustc_middle::mir::interpret::ErrorHandled;
12 use rustc_middle::traits::Reveal;
13 use rustc_middle::ty::{self, subst::Subst, TyCtxt};
14 use rustc_span::source_map::Span;
15 use rustc_target::abi::{Abi, LayoutOf};
16 use std::convert::TryInto;
18 pub fn note_on_undefined_behavior_error() -> &'static str {
19 "The rules on what exactly is undefined behavior aren't clear, \
20 so this check might be overzealous. Please open an issue on the rustc \
21 repository if you believe it should not be considered undefined behavior."
24 // Returns a pointer to where the result lives
25 fn eval_body_using_ecx<'mir, 'tcx>(
26 ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
28 body: &'mir mir::Body<'tcx>,
29 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
30 debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
32 let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
33 assert!(!layout.is_unsized());
34 let ret = ecx.allocate(layout, MemoryKind::Stack);
36 let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
37 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
38 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
40 // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
41 // make sense if the body is expecting nontrivial arguments.
42 // (The alternative would be to use `eval_fn_call` with an args slice.)
43 for arg in body.args_iter() {
44 let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
45 let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
46 assert!(layout.is_zst())
53 StackPopCleanup::None { cleanup: false },
56 // The main interpreter loop.
60 // FIXME: since the DefId of a promoted is the DefId of its owner, this
61 // means that promoteds in statics are actually interned like statics!
62 // However, this is also currently crucial because we promote mutable
63 // non-empty slices in statics to extend their lifetime, and this
64 // ensures that they are put into a mutable allocation.
65 // For other kinds of promoteds in statics (like array initializers), this is rather silly.
66 let intern_kind = match tcx.static_mutability(cid.instance.def_id()) {
67 Some(m) => InternKind::Static(m),
68 None if cid.promoted.is_some() => InternKind::Promoted,
69 _ => InternKind::Constant,
71 intern_const_alloc_recursive(
75 body.ignore_interior_mut_in_const_validation,
78 debug!("eval_body_using_ecx done: {:?}", *ret);
82 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
83 /// `simd_shuffle` and const patterns in match arms.
85 /// The function containing the `match` that is currently being analyzed may have generic bounds
86 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
87 /// of a function's generic parameter will require knowledge about the bounds on the generic
88 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
89 pub(super) fn mk_eval_cx<'mir, 'tcx>(
92 param_env: ty::ParamEnv<'tcx>,
93 can_access_statics: bool,
94 ) -> CompileTimeEvalContext<'mir, 'tcx> {
95 debug!("mk_eval_cx: {:?}", param_env);
100 CompileTimeInterpreter::new(tcx.sess.const_eval_limit()),
101 MemoryExtra { can_access_statics },
105 pub(super) fn op_to_const<'tcx>(
106 ecx: &CompileTimeEvalContext<'_, 'tcx>,
108 ) -> ConstValue<'tcx> {
109 // We do not have value optimizations for everything.
110 // Only scalars and slices, since they are very common.
111 // Note that further down we turn scalars of uninitialized bits back to `ByRef`. These can result
112 // from scalar unions that are initialized with one of their zero sized variants. We could
113 // instead allow `ConstValue::Scalar` to store `ScalarMaybeUninit`, but that would affect all
114 // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
115 // `Undef` situation.
116 let try_as_immediate = match op.layout.abi {
117 Abi::Scalar(..) => true,
118 Abi::ScalarPair(..) => match op.layout.ty.kind {
119 ty::Ref(_, inner, _) => match inner.kind {
120 ty::Slice(elem) => elem == ecx.tcx.types.u8,
128 let immediate = if try_as_immediate {
129 Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
131 // It is guaranteed that any non-slice scalar pair is actually ByRef here.
132 // When we come back from raw const eval, we are always by-ref. The only way our op here is
133 // by-val is if we are in destructure_const, i.e., if this is (a field of) something that we
134 // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
135 // structs containing such.
136 op.try_as_mplace(ecx)
139 let to_const_value = |mplace: MPlaceTy<'_>| match mplace.ptr {
140 Scalar::Ptr(ptr) => {
141 let alloc = ecx.tcx.global_alloc(ptr.alloc_id).unwrap_memory();
142 ConstValue::ByRef { alloc, offset: ptr.offset }
144 Scalar::Raw { data, .. } => {
145 assert!(mplace.layout.is_zst());
148 mplace.layout.align.abi.bytes().into(),
149 "this MPlaceTy must come from `try_as_mplace` being used on a zst, so we know what
150 value this integer address must have",
152 ConstValue::Scalar(Scalar::zst())
156 Ok(mplace) => to_const_value(mplace),
157 // see comment on `let try_as_immediate` above
158 Err(imm) => match *imm {
159 Immediate::Scalar(x) => match x {
160 ScalarMaybeUninit::Scalar(s) => ConstValue::Scalar(s),
161 ScalarMaybeUninit::Uninit => to_const_value(op.assert_mem_place(ecx)),
163 Immediate::ScalarPair(a, b) => {
164 let (data, start) = match a.check_init().unwrap() {
165 Scalar::Ptr(ptr) => {
166 (ecx.tcx.global_alloc(ptr.alloc_id).unwrap_memory(), ptr.offset.bytes())
168 Scalar::Raw { .. } => (
170 .intern_const_alloc(Allocation::from_byte_aligned_bytes(b"" as &[u8])),
174 let len = b.to_machine_usize(ecx).unwrap();
175 let start = start.try_into().unwrap();
176 let len: usize = len.try_into().unwrap();
177 ConstValue::Slice { data, start, end: start + len }
183 fn validate_and_turn_into_const<'tcx>(
185 constant: RawConst<'tcx>,
186 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
187 ) -> ::rustc_middle::mir::interpret::ConstEvalResult<'tcx> {
189 let def_id = cid.instance.def.def_id();
190 let is_static = tcx.is_static(def_id);
191 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
193 let mplace = ecx.raw_const_to_mplace(constant)?;
195 // FIXME do not validate promoteds until a decision on
196 // https://github.com/rust-lang/rust/issues/67465 is made
197 if cid.promoted.is_none() {
198 let mut ref_tracking = RefTracking::new(mplace);
199 while let Some((mplace, path)) = ref_tracking.todo.pop() {
200 ecx.const_validate_operand(
204 /*may_ref_to_static*/ ecx.memory.extra.can_access_statics,
208 // Now that we validated, turn this into a proper constant.
209 // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
210 // whether they become immediates.
211 if is_static || cid.promoted.is_some() {
212 let ptr = mplace.ptr.assert_ptr();
213 Ok(ConstValue::ByRef {
214 alloc: ecx.tcx.global_alloc(ptr.alloc_id).unwrap_memory(),
218 Ok(op_to_const(&ecx, mplace.into()))
222 val.map_err(|error| {
223 let err = ConstEvalErr::new(&ecx, error, None);
224 err.struct_error(ecx.tcx, "it is undefined behavior to use this value", |mut diag| {
225 diag.note(note_on_undefined_behavior_error());
231 pub fn const_eval_validated_provider<'tcx>(
233 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
234 ) -> ::rustc_middle::mir::interpret::ConstEvalResult<'tcx> {
235 // see comment in const_eval_raw_provider for what we're doing here
236 if key.param_env.reveal() == Reveal::All {
238 key.param_env = key.param_env.with_user_facing();
239 match tcx.const_eval_validated(key) {
240 // try again with reveal all as requested
241 Err(ErrorHandled::TooGeneric) => {}
243 other => return other,
247 // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
248 // Catch such calls and evaluate them instead of trying to load a constant's MIR.
249 if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
250 let ty = key.value.instance.ty(tcx, key.param_env);
251 let substs = match ty.kind {
252 ty::FnDef(_, substs) => substs,
253 _ => bug!("intrinsic with type {:?}", ty),
255 return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
256 let span = tcx.def_span(def_id);
257 let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
258 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
262 tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key))
265 pub fn const_eval_raw_provider<'tcx>(
267 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
268 ) -> ::rustc_middle::mir::interpret::ConstEvalRawResult<'tcx> {
269 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
270 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
271 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
272 // computed. For a large percentage of constants that will already have succeeded. Only
273 // associated constants of generic functions will fail due to not enough monomorphization
274 // information being available.
276 // In case we fail in the `UserFacing` variant, we just do the real computation.
277 if key.param_env.reveal() == Reveal::All {
279 key.param_env = key.param_env.with_user_facing();
280 match tcx.const_eval_raw(key) {
281 // try again with reveal all as requested
282 Err(ErrorHandled::TooGeneric) => {}
284 other => return other,
287 if cfg!(debug_assertions) {
288 // Make sure we format the instance even if we do not print it.
289 // This serves as a regression test against an ICE on printing.
290 // The next two lines concatenated contain some discussion:
291 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
292 // subject/anon_const_instance_printing/near/135980032
293 let instance = key.value.instance.to_string();
294 trace!("const eval: {:?} ({})", key, instance);
298 let def = cid.instance.def.with_opt_param();
300 if let Some(def) = def.as_local() {
301 if tcx.has_typeck_results(def.did) {
302 if let Some(error_reported) = tcx.typeck_opt_const_arg(def).tainted_by_errors {
303 return Err(ErrorHandled::Reported(error_reported));
308 let is_static = tcx.is_static(def.did);
310 let mut ecx = InterpCx::new(
312 tcx.def_span(def.did),
314 CompileTimeInterpreter::new(tcx.sess.const_eval_limit()),
315 MemoryExtra { can_access_statics: is_static },
318 let res = ecx.load_mir(cid.instance.def, cid.promoted);
319 res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body))
320 .map(|place| RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty })
322 let err = ConstEvalErr::new(&ecx, error, None);
323 // errors in statics are always emitted as fatal errors
325 // Ensure that if the above error was either `TooGeneric` or `Reported`
326 // an error must be reported.
327 let v = err.report_as_error(
328 ecx.tcx.at(ecx.cur_span()),
329 "could not evaluate static initializer",
332 // If this is `Reveal:All`, then we need to make sure an error is reported but if
333 // this is `Reveal::UserFacing`, then it's expected that we could get a
334 // `TooGeneric` error. When we fall back to `Reveal::All`, then it will either
335 // succeed or we'll report this error then.
336 if key.param_env.reveal() == Reveal::All {
337 tcx.sess.delay_span_bug(
339 &format!("static eval failure did not emit an error: {:#?}", v),
344 } else if let Some(def) = def.as_local() {
345 // constant defined in this crate, we can figure out a lint level!
346 match tcx.def_kind(def.did.to_def_id()) {
347 // constants never produce a hard error at the definition site. Anything else is
348 // a backwards compatibility hazard (and will break old versions of winapi for
351 // note that validation may still cause a hard error on this very same constant,
352 // because any code that existed before validation could not have failed
353 // validation thus preventing such a hard error from being a backwards
354 // compatibility hazard
355 DefKind::Const | DefKind::AssocConst => {
356 let hir_id = tcx.hir().as_local_hir_id(def.did);
358 tcx.at(tcx.def_span(def.did)),
359 "any use of this value will cause an error",
364 // promoting runtime code is only allowed to error if it references broken
365 // constants any other kind of error will be reported to the user as a
366 // deny-by-default lint
368 if let Some(p) = cid.promoted {
369 let span = tcx.promoted_mir_of_opt_const_arg(def.to_global())[p].span;
370 if let err_inval!(ReferencedConstant) = err.error {
373 "evaluation of constant expression failed",
378 "reaching this expression at runtime will panic or abort",
379 tcx.hir().as_local_hir_id(def.did),
383 // anything else (array lengths, enum initializers, constant patterns) are
384 // reported as hard errors
387 ecx.tcx.at(ecx.cur_span()),
388 "evaluation of constant value failed",
394 // use of broken constant from other crate
395 err.report_as_error(ecx.tcx.at(ecx.cur_span()), "could not evaluate constant")