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