1 use super::{CompileTimeEvalContext, CompileTimeInterpreter, ConstEvalErr, MemoryExtra};
2 use crate::interpret::eval_nullary_intrinsic;
3 use crate::interpret::{
4     intern_const_alloc_recursive, Allocation, ConstAlloc, ConstValue, CtfeValidationMode, GlobalId,
5     Immediate, InternKind, InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, Scalar,
6     ScalarMaybeUninit, StackPopCleanup,
7 };
8 
9 use rustc_errors::ErrorReported;
10 use rustc_hir::def::DefKind;
11 use rustc_middle::mir;
12 use rustc_middle::mir::interpret::ErrorHandled;
13 use rustc_middle::mir::pretty::display_allocation;
14 use rustc_middle::traits::Reveal;
15 use rustc_middle::ty::layout::LayoutOf;
16 use rustc_middle::ty::print::with_no_trimmed_paths;
17 use rustc_middle::ty::{self, subst::Subst, TyCtxt};
18 use rustc_span::source_map::Span;
19 use rustc_target::abi::Abi;
20 use std::borrow::Cow;
21 use std::convert::TryInto;
22 
note_on_undefined_behavior_error() -> &'static str23 pub fn note_on_undefined_behavior_error() -> &'static str {
24     "The rules on what exactly is undefined behavior aren't clear, \
25      so this check might be overzealous. Please open an issue on the rustc \
26      repository if you believe it should not be considered undefined behavior."
27 }
28 
29 // Returns a pointer to where the result lives
eval_body_using_ecx<'mir, 'tcx>( ecx: &mut CompileTimeEvalContext<'mir, 'tcx>, cid: GlobalId<'tcx>, body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>>30 fn eval_body_using_ecx<'mir, 'tcx>(
31     ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
32     cid: GlobalId<'tcx>,
33     body: &'mir mir::Body<'tcx>,
34 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
35     debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
36     let tcx = *ecx.tcx;
37     assert!(
38         cid.promoted.is_some()
39             || matches!(
40                 ecx.tcx.def_kind(cid.instance.def_id()),
41                 DefKind::Const
42                     | DefKind::Static
43                     | DefKind::ConstParam
44                     | DefKind::AnonConst
45                     | DefKind::InlineConst
46                     | DefKind::AssocConst
47             ),
48         "Unexpected DefKind: {:?}",
49         ecx.tcx.def_kind(cid.instance.def_id())
50     );
51     let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
52     assert!(!layout.is_unsized());
53     let ret = ecx.allocate(layout, MemoryKind::Stack)?;
54 
55     trace!(
56         "eval_body_using_ecx: pushing stack frame for global: {}{}",
57         with_no_trimmed_paths(|| ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
58         cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p))
59     );
60 
61     ecx.push_stack_frame(
62         cid.instance,
63         body,
64         Some(&ret.into()),
65         StackPopCleanup::None { cleanup: false },
66     )?;
67 
68     // The main interpreter loop.
69     ecx.run()?;
70 
71     // Intern the result
72     let intern_kind = if cid.promoted.is_some() {
73         InternKind::Promoted
74     } else {
75         match tcx.static_mutability(cid.instance.def_id()) {
76             Some(m) => InternKind::Static(m),
77             None => InternKind::Constant,
78         }
79     };
80     intern_const_alloc_recursive(ecx, intern_kind, &ret)?;
81 
82     debug!("eval_body_using_ecx done: {:?}", *ret);
83     Ok(ret)
84 }
85 
86 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
87 /// `simd_shuffle` and const patterns in match arms.
88 ///
89 /// The function containing the `match` that is currently being analyzed may have generic bounds
90 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
91 /// of a function's generic parameter will require knowledge about the bounds on the generic
92 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
mk_eval_cx<'mir, 'tcx>( tcx: TyCtxt<'tcx>, root_span: Span, param_env: ty::ParamEnv<'tcx>, can_access_statics: bool, ) -> CompileTimeEvalContext<'mir, 'tcx>93 pub(super) fn mk_eval_cx<'mir, 'tcx>(
94     tcx: TyCtxt<'tcx>,
95     root_span: Span,
96     param_env: ty::ParamEnv<'tcx>,
97     can_access_statics: bool,
98 ) -> CompileTimeEvalContext<'mir, 'tcx> {
99     debug!("mk_eval_cx: {:?}", param_env);
100     InterpCx::new(
101         tcx,
102         root_span,
103         param_env,
104         CompileTimeInterpreter::new(tcx.const_eval_limit()),
105         MemoryExtra { can_access_statics },
106     )
107 }
108 
109 /// This function converts an interpreter value into a constant that is meant for use in the
110 /// type system.
op_to_const<'tcx>( ecx: &CompileTimeEvalContext<'_, 'tcx>, op: &OpTy<'tcx>, ) -> ConstValue<'tcx>111 pub(super) fn op_to_const<'tcx>(
112     ecx: &CompileTimeEvalContext<'_, 'tcx>,
113     op: &OpTy<'tcx>,
114 ) -> ConstValue<'tcx> {
115     // We do not have value optimizations for everything.
116     // Only scalars and slices, since they are very common.
117     // Note that further down we turn scalars of uninitialized bits back to `ByRef`. These can result
118     // from scalar unions that are initialized with one of their zero sized variants. We could
119     // instead allow `ConstValue::Scalar` to store `ScalarMaybeUninit`, but that would affect all
120     // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
121     // `Undef` situation.
122     let try_as_immediate = match op.layout.abi {
123         Abi::Scalar(..) => true,
124         Abi::ScalarPair(..) => match op.layout.ty.kind() {
125             ty::Ref(_, inner, _) => match *inner.kind() {
126                 ty::Slice(elem) => elem == ecx.tcx.types.u8,
127                 ty::Str => true,
128                 _ => false,
129             },
130             _ => false,
131         },
132         _ => false,
133     };
134     let immediate = if try_as_immediate {
135         Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
136     } else {
137         // It is guaranteed that any non-slice scalar pair is actually ByRef here.
138         // When we come back from raw const eval, we are always by-ref. The only way our op here is
139         // by-val is if we are in destructure_const, i.e., if this is (a field of) something that we
140         // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
141         // structs containing such.
142         op.try_as_mplace()
143     };
144 
145     // We know `offset` is relative to the allocation, so we can use `into_parts`.
146     let to_const_value = |mplace: &MPlaceTy<'_>| match mplace.ptr.into_parts() {
147         (Some(alloc_id), offset) => {
148             let alloc = ecx.tcx.global_alloc(alloc_id).unwrap_memory();
149             ConstValue::ByRef { alloc, offset }
150         }
151         (None, offset) => {
152             assert!(mplace.layout.is_zst());
153             assert_eq!(
154                 offset.bytes() % mplace.layout.align.abi.bytes(),
155                 0,
156                 "this MPlaceTy must come from a validated constant, thus we can assume the \
157                 alignment is correct",
158             );
159             ConstValue::Scalar(Scalar::ZST)
160         }
161     };
162     match immediate {
163         Ok(ref mplace) => to_const_value(mplace),
164         // see comment on `let try_as_immediate` above
165         Err(imm) => match *imm {
166             Immediate::Scalar(x) => match x {
167                 ScalarMaybeUninit::Scalar(s) => ConstValue::Scalar(s),
168                 ScalarMaybeUninit::Uninit => to_const_value(&op.assert_mem_place()),
169             },
170             Immediate::ScalarPair(a, b) => {
171                 // We know `offset` is relative to the allocation, so we can use `into_parts`.
172                 let (data, start) = match ecx.scalar_to_ptr(a.check_init().unwrap()).into_parts() {
173                     (Some(alloc_id), offset) => {
174                         (ecx.tcx.global_alloc(alloc_id).unwrap_memory(), offset.bytes())
175                     }
176                     (None, _offset) => (
177                         ecx.tcx.intern_const_alloc(Allocation::from_bytes_byte_aligned_immutable(
178                             b"" as &[u8],
179                         )),
180                         0,
181                     ),
182                 };
183                 let len = b.to_machine_usize(ecx).unwrap();
184                 let start = start.try_into().unwrap();
185                 let len: usize = len.try_into().unwrap();
186                 ConstValue::Slice { data, start, end: start + len }
187             }
188         },
189     }
190 }
191 
turn_into_const_value<'tcx>( tcx: TyCtxt<'tcx>, constant: ConstAlloc<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ConstValue<'tcx>192 fn turn_into_const_value<'tcx>(
193     tcx: TyCtxt<'tcx>,
194     constant: ConstAlloc<'tcx>,
195     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
196 ) -> ConstValue<'tcx> {
197     let cid = key.value;
198     let def_id = cid.instance.def.def_id();
199     let is_static = tcx.is_static(def_id);
200     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
201 
202     let mplace = ecx.raw_const_to_mplace(constant).expect(
203         "can only fail if layout computation failed, \
204         which should have given a good error before ever invoking this function",
205     );
206     assert!(
207         !is_static || cid.promoted.is_some(),
208         "the `eval_to_const_value_raw` query should not be used for statics, use `eval_to_allocation` instead"
209     );
210     // Turn this into a proper constant.
211     op_to_const(&ecx, &mplace.into())
212 }
213 
eval_to_const_value_raw_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx>214 pub fn eval_to_const_value_raw_provider<'tcx>(
215     tcx: TyCtxt<'tcx>,
216     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
217 ) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
218     // see comment in eval_to_allocation_raw_provider for what we're doing here
219     if key.param_env.reveal() == Reveal::All {
220         let mut key = key;
221         key.param_env = key.param_env.with_user_facing();
222         match tcx.eval_to_const_value_raw(key) {
223             // try again with reveal all as requested
224             Err(ErrorHandled::TooGeneric) => {}
225             // deduplicate calls
226             other => return other,
227         }
228     }
229 
230     // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
231     // Catch such calls and evaluate them instead of trying to load a constant's MIR.
232     if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
233         let ty = key.value.instance.ty(tcx, key.param_env);
234         let substs = match ty.kind() {
235             ty::FnDef(_, substs) => substs,
236             _ => bug!("intrinsic with type {:?}", ty),
237         };
238         return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
239             let span = tcx.def_span(def_id);
240             let error = ConstEvalErr { error: error.into_kind(), stacktrace: vec![], span };
241             error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
242         });
243     }
244 
245     tcx.eval_to_allocation_raw(key).map(|val| turn_into_const_value(tcx, val, key))
246 }
247 
eval_to_allocation_raw_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx>248 pub fn eval_to_allocation_raw_provider<'tcx>(
249     tcx: TyCtxt<'tcx>,
250     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
251 ) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> {
252     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
253     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
254     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
255     // computed. For a large percentage of constants that will already have succeeded. Only
256     // associated constants of generic functions will fail due to not enough monomorphization
257     // information being available.
258 
259     // In case we fail in the `UserFacing` variant, we just do the real computation.
260     if key.param_env.reveal() == Reveal::All {
261         let mut key = key;
262         key.param_env = key.param_env.with_user_facing();
263         match tcx.eval_to_allocation_raw(key) {
264             // try again with reveal all as requested
265             Err(ErrorHandled::TooGeneric) => {}
266             // deduplicate calls
267             other => return other,
268         }
269     }
270     if cfg!(debug_assertions) {
271         // Make sure we format the instance even if we do not print it.
272         // This serves as a regression test against an ICE on printing.
273         // The next two lines concatenated contain some discussion:
274         // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
275         // subject/anon_const_instance_printing/near/135980032
276         let instance = with_no_trimmed_paths(|| key.value.instance.to_string());
277         trace!("const eval: {:?} ({})", key, instance);
278     }
279 
280     let cid = key.value;
281     let def = cid.instance.def.with_opt_param();
282 
283     if let Some(def) = def.as_local() {
284         if tcx.has_typeck_results(def.did) {
285             if let Some(error_reported) = tcx.typeck_opt_const_arg(def).tainted_by_errors {
286                 return Err(ErrorHandled::Reported(error_reported));
287             }
288         }
289         if !tcx.is_mir_available(def.did) {
290             tcx.sess.delay_span_bug(
291                 tcx.def_span(def.did),
292                 &format!("no MIR body is available for {:?}", def.did),
293             );
294             return Err(ErrorHandled::Reported(ErrorReported {}));
295         }
296         if let Some(error_reported) = tcx.mir_const_qualif_opt_const_arg(def).error_occured {
297             return Err(ErrorHandled::Reported(error_reported));
298         }
299     }
300 
301     let is_static = tcx.is_static(def.did);
302 
303     let mut ecx = InterpCx::new(
304         tcx,
305         tcx.def_span(def.did),
306         key.param_env,
307         CompileTimeInterpreter::new(tcx.const_eval_limit()),
308         // Statics (and promoteds inside statics) may access other statics, because unlike consts
309         // they do not have to behave "as if" they were evaluated at runtime.
310         MemoryExtra { can_access_statics: is_static },
311     );
312 
313     let res = ecx.load_mir(cid.instance.def, cid.promoted);
314     match res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body)) {
315         Err(error) => {
316             let err = ConstEvalErr::new(&ecx, error, None);
317             // Some CTFE errors raise just a lint, not a hard error; see
318             // <https://github.com/rust-lang/rust/issues/71800>.
319             let is_hard_err = if let Some(def) = def.as_local() {
320                 // (Associated) consts only emit a lint, since they might be unused.
321                 !matches!(tcx.def_kind(def.did.to_def_id()), DefKind::Const | DefKind::AssocConst)
322                     // check if the inner InterpError is hard
323                     || err.error.is_hard_err()
324             } else {
325                 // use of broken constant from other crate: always an error
326                 true
327             };
328 
329             if is_hard_err {
330                 let msg = if is_static {
331                     Cow::from("could not evaluate static initializer")
332                 } else {
333                     // If the current item has generics, we'd like to enrich the message with the
334                     // instance and its substs: to show the actual compile-time values, in addition to
335                     // the expression, leading to the const eval error.
336                     let instance = &key.value.instance;
337                     if !instance.substs.is_empty() {
338                         let instance = with_no_trimmed_paths(|| instance.to_string());
339                         let msg = format!("evaluation of `{}` failed", instance);
340                         Cow::from(msg)
341                     } else {
342                         Cow::from("evaluation of constant value failed")
343                     }
344                 };
345 
346                 Err(err.report_as_error(ecx.tcx.at(ecx.cur_span()), &msg))
347             } else {
348                 let hir_id = tcx.hir().local_def_id_to_hir_id(def.as_local().unwrap().did);
349                 Err(err.report_as_lint(
350                     tcx.at(tcx.def_span(def.did)),
351                     "any use of this value will cause an error",
352                     hir_id,
353                     Some(err.span),
354                 ))
355             }
356         }
357         Ok(mplace) => {
358             // Since evaluation had no errors, validate the resulting constant.
359             // This is a separate `try` block to provide more targeted error reporting.
360             let validation = try {
361                 let mut ref_tracking = RefTracking::new(mplace);
362                 let mut inner = false;
363                 while let Some((mplace, path)) = ref_tracking.todo.pop() {
364                     let mode = match tcx.static_mutability(cid.instance.def_id()) {
365                         Some(_) if cid.promoted.is_some() => {
366                             // Promoteds in statics are allowed to point to statics.
367                             CtfeValidationMode::Const { inner, allow_static_ptrs: true }
368                         }
369                         Some(_) => CtfeValidationMode::Regular, // a `static`
370                         None => CtfeValidationMode::Const { inner, allow_static_ptrs: false },
371                     };
372                     ecx.const_validate_operand(&mplace.into(), path, &mut ref_tracking, mode)?;
373                     inner = true;
374                 }
375             };
376             let alloc_id = mplace.ptr.provenance.unwrap();
377             if let Err(error) = validation {
378                 // Validation failed, report an error. This is always a hard error.
379                 let err = ConstEvalErr::new(&ecx, error, None);
380                 Err(err.struct_error(
381                     ecx.tcx,
382                     "it is undefined behavior to use this value",
383                     |mut diag| {
384                         diag.note(note_on_undefined_behavior_error());
385                         diag.note(&format!(
386                             "the raw bytes of the constant ({}",
387                             display_allocation(
388                                 *ecx.tcx,
389                                 ecx.tcx.global_alloc(alloc_id).unwrap_memory()
390                             )
391                         ));
392                         diag.emit();
393                     },
394                 ))
395             } else {
396                 // Convert to raw constant
397                 Ok(ConstAlloc { alloc_id, ty: mplace.layout.ty })
398             }
399         }
400     }
401 }
402