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