1use std::sync::atomic::Ordering::Relaxed;
2
3use either::{Left, Right};
4use rustc_abi::{self as abi, BackendRepr};
5use rustc_errors::E0080;
6use rustc_hir::def::DefKind;
7use rustc_middle::mir::interpret::{AllocId, ErrorHandled, InterpErrorInfo, ReportedErrorInfo};
8use rustc_middle::mir::{self, ConstAlloc, ConstValue};
9use rustc_middle::query::TyCtxtAt;
10use rustc_middle::ty::layout::HasTypingEnv;
11use rustc_middle::ty::print::with_no_trimmed_paths;
12use rustc_middle::ty::{self, Ty, TyCtxt};
13use rustc_middle::{bug, throw_inval};
14use rustc_span::def_id::LocalDefId;
15use rustc_span::{DUMMY_SP, Span};
16use tracing::{debug, instrument, trace};
17
18use super::{CanAccessMutGlobal, CompileTimeInterpCx, CompileTimeMachine};
19use crate::const_eval::CheckAlignment;
20use crate::interpret::{
21 CtfeValidationMode, GlobalId, Immediate, InternError, InternKind, InterpCx, InterpErrorKind,
22 InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, ReturnContinuation, create_static_alloc,
23 intern_const_alloc_recursive, interp_ok, throw_exhaust,
24};
25use crate::{CTRL_C_RECEIVED, errors};
26
27#[instrument(level = "trace", skip(ecx, body))]
29fn eval_body_using_ecx<'tcx, R: InterpretationResult<'tcx>>(
30 ecx: &mut CompileTimeInterpCx<'tcx>,
31 cid: GlobalId<'tcx>,
32 body: &'tcx mir::Body<'tcx>,
33) -> InterpResult<'tcx, R> {
34 let tcx = *ecx.tcx;
35 assert!(
36 cid.promoted.is_some()
37 || matches!(
38 ecx.tcx.def_kind(cid.instance.def_id()),
39 DefKind::Const
40 | DefKind::Static { .. }
41 | DefKind::ConstParam
42 | DefKind::AnonConst
43 | DefKind::InlineConst
44 | DefKind::AssocConst
45 ),
46 "Unexpected DefKind: {:?}",
47 ecx.tcx.def_kind(cid.instance.def_id())
48 );
49 let layout = ecx.layout_of(body.bound_return_ty().instantiate(tcx, cid.instance.args))?;
50 assert!(layout.is_sized());
51
52 let intern_kind = if cid.promoted.is_some() {
53 InternKind::Promoted
54 } else {
55 match tcx.static_mutability(cid.instance.def_id()) {
56 Some(m) => InternKind::Static(m),
57 None => InternKind::Constant,
58 }
59 };
60
61 let ret = if let InternKind::Static(_) = intern_kind {
62 create_static_alloc(ecx, cid.instance.def_id().expect_local(), layout)?
63 } else {
64 ecx.allocate(layout, MemoryKind::Stack)?
65 };
66
67 trace!(
68 "eval_body_using_ecx: pushing stack frame for global: {}{}",
69 with_no_trimmed_paths!(ecx.tcx.def_path_str(cid.instance.def_id())),
70 cid.promoted.map_or_else(String::new, |p| format!("::{p:?}"))
71 );
72
73 ecx.push_stack_frame_raw(
76 cid.instance,
77 body,
78 &ret.clone().into(),
79 ReturnContinuation::Stop { cleanup: false },
80 )?;
81 ecx.storage_live_for_always_live_locals()?;
82
83 while ecx.step()? {
85 if CTRL_C_RECEIVED.load(Relaxed) {
86 throw_exhaust!(Interrupted);
87 }
88 }
89
90 let intern_result = intern_const_alloc_recursive(ecx, intern_kind, &ret);
92
93 const_validate_mplace(ecx, &ret, cid)?;
95
96 match intern_result {
100 Ok(()) => {}
101 Err(InternError::DanglingPointer) => {
102 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
103 ecx.tcx
104 .dcx()
105 .emit_err(errors::DanglingPtrInFinal { span: ecx.tcx.span, kind: intern_kind }),
106 )));
107 }
108 Err(InternError::BadMutablePointer) => {
109 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
110 ecx.tcx
111 .dcx()
112 .emit_err(errors::MutablePtrInFinal { span: ecx.tcx.span, kind: intern_kind }),
113 )));
114 }
115 Err(InternError::ConstAllocNotGlobal) => {
116 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
117 ecx.tcx.dcx().emit_err(errors::ConstHeapPtrInFinal { span: ecx.tcx.span }),
118 )));
119 }
120 }
121
122 interp_ok(R::make_result(ret, ecx))
123}
124
125pub(crate) fn mk_eval_cx_to_read_const_val<'tcx>(
136 tcx: TyCtxt<'tcx>,
137 root_span: Span,
138 typing_env: ty::TypingEnv<'tcx>,
139 can_access_mut_global: CanAccessMutGlobal,
140) -> CompileTimeInterpCx<'tcx> {
141 debug!("mk_eval_cx: {:?}", typing_env);
142 InterpCx::new(
143 tcx,
144 root_span,
145 typing_env,
146 CompileTimeMachine::new(can_access_mut_global, CheckAlignment::No),
147 )
148}
149
150pub fn mk_eval_cx_for_const_val<'tcx>(
153 tcx: TyCtxtAt<'tcx>,
154 typing_env: ty::TypingEnv<'tcx>,
155 val: mir::ConstValue<'tcx>,
156 ty: Ty<'tcx>,
157) -> Option<(CompileTimeInterpCx<'tcx>, OpTy<'tcx>)> {
158 let ecx = mk_eval_cx_to_read_const_val(tcx.tcx, tcx.span, typing_env, CanAccessMutGlobal::No);
159 let op = ecx.const_val_to_op(val, ty, None).discard_err()?;
161 Some((ecx, op))
162}
163
164#[instrument(skip(ecx), level = "debug")]
171pub(super) fn op_to_const<'tcx>(
172 ecx: &CompileTimeInterpCx<'tcx>,
173 op: &OpTy<'tcx>,
174 for_diagnostics: bool,
175) -> ConstValue<'tcx> {
176 if op.layout.is_zst() {
178 return ConstValue::ZeroSized;
179 }
180
181 let force_as_immediate = match op.layout.backend_repr {
187 BackendRepr::Scalar(abi::Scalar::Initialized { .. }) => true,
188 _ => false,
196 };
197 let immediate = if force_as_immediate {
198 match ecx.read_immediate(op).report_err() {
199 Ok(imm) => Right(imm),
200 Err(err) => {
201 if for_diagnostics {
202 op.as_mplace_or_imm()
204 } else {
205 panic!("normalization works on validated constants: {err:?}")
206 }
207 }
208 }
209 } else {
210 op.as_mplace_or_imm()
211 };
212
213 debug!(?immediate);
214
215 match immediate {
216 Left(ref mplace) => {
217 let (prov, offset) =
218 mplace.ptr().into_pointer_or_addr().unwrap().prov_and_relative_offset();
219 let alloc_id = prov.alloc_id();
220 ConstValue::Indirect { alloc_id, offset }
221 }
222 Right(imm) => match *imm {
224 Immediate::Scalar(x) => ConstValue::Scalar(x),
225 Immediate::ScalarPair(a, b) => {
226 debug!("ScalarPair(a: {:?}, b: {:?})", a, b);
227 let pointee_ty = imm.layout.ty.builtin_deref(false).unwrap(); debug_assert!(
232 matches!(
233 ecx.tcx.struct_tail_for_codegen(pointee_ty, ecx.typing_env()).kind(),
234 ty::Str | ty::Slice(..),
235 ),
236 "`ConstValue::Slice` is for slice-tailed types only, but got {}",
237 imm.layout.ty,
238 );
239 let msg = "`op_to_const` on an immediate scalar pair must only be used on slice references to the beginning of an actual allocation";
240 let ptr = a.to_pointer(ecx).expect(msg);
241 let (prov, offset) =
242 ptr.into_pointer_or_addr().expect(msg).prov_and_relative_offset();
243 let alloc_id = prov.alloc_id();
244 let data = ecx.tcx.global_alloc(alloc_id).unwrap_memory();
245 assert!(offset == abi::Size::ZERO, "{}", msg);
246 let meta = b.to_target_usize(ecx).expect(msg);
247 ConstValue::Slice { data, meta }
248 }
249 Immediate::Uninit => bug!("`Uninit` is not a valid value for {}", op.layout.ty),
250 },
251 }
252}
253
254#[instrument(skip(tcx), level = "debug", ret)]
255pub(crate) fn turn_into_const_value<'tcx>(
256 tcx: TyCtxt<'tcx>,
257 constant: ConstAlloc<'tcx>,
258 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
259) -> ConstValue<'tcx> {
260 let cid = key.value;
261 let def_id = cid.instance.def.def_id();
262 let is_static = tcx.is_static(def_id);
263 let ecx = mk_eval_cx_to_read_const_val(
265 tcx,
266 tcx.def_span(key.value.instance.def_id()),
267 key.typing_env,
268 CanAccessMutGlobal::from(is_static),
269 );
270
271 let mplace = ecx.raw_const_to_mplace(constant).expect(
272 "can only fail if layout computation failed, \
273 which should have given a good error before ever invoking this function",
274 );
275 assert!(
276 !is_static || cid.promoted.is_some(),
277 "the `eval_to_const_value_raw` query should not be used for statics, use `eval_to_allocation` instead"
278 );
279
280 op_to_const(&ecx, &mplace.into(), false)
282}
283
284#[instrument(skip(tcx), level = "debug")]
285pub fn eval_to_const_value_raw_provider<'tcx>(
286 tcx: TyCtxt<'tcx>,
287 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
288) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
289 tcx.eval_to_allocation_raw(key).map(|val| turn_into_const_value(tcx, val, key))
290}
291
292#[instrument(skip(tcx), level = "debug")]
293pub fn eval_static_initializer_provider<'tcx>(
294 tcx: TyCtxt<'tcx>,
295 def_id: LocalDefId,
296) -> ::rustc_middle::mir::interpret::EvalStaticInitializerRawResult<'tcx> {
297 assert!(tcx.is_static(def_id.to_def_id()));
298
299 let instance = ty::Instance::mono(tcx, def_id.to_def_id());
300 let cid = rustc_middle::mir::interpret::GlobalId { instance, promoted: None };
301 eval_in_interpreter(tcx, cid, ty::TypingEnv::fully_monomorphized())
302}
303
304pub trait InterpretationResult<'tcx> {
305 fn make_result(
309 mplace: MPlaceTy<'tcx>,
310 ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
311 ) -> Self;
312}
313
314impl<'tcx> InterpretationResult<'tcx> for ConstAlloc<'tcx> {
315 fn make_result(
316 mplace: MPlaceTy<'tcx>,
317 _ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
318 ) -> Self {
319 ConstAlloc { alloc_id: mplace.ptr().provenance.unwrap().alloc_id(), ty: mplace.layout.ty }
320 }
321}
322
323#[instrument(skip(tcx), level = "debug")]
324pub fn eval_to_allocation_raw_provider<'tcx>(
325 tcx: TyCtxt<'tcx>,
326 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
327) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> {
328 assert!(key.value.promoted.is_some() || !tcx.is_static(key.value.instance.def_id()));
331 debug_assert_eq!(key.typing_env.typing_mode, ty::TypingMode::PostAnalysis);
334 if cfg!(debug_assertions) {
335 let instance = with_no_trimmed_paths!(key.value.instance.to_string());
341 trace!("const eval: {:?} ({})", key, instance);
342 }
343
344 eval_in_interpreter(tcx, key.value, key.typing_env)
345}
346
347fn eval_in_interpreter<'tcx, R: InterpretationResult<'tcx>>(
348 tcx: TyCtxt<'tcx>,
349 cid: GlobalId<'tcx>,
350 typing_env: ty::TypingEnv<'tcx>,
351) -> Result<R, ErrorHandled> {
352 let def = cid.instance.def.def_id();
353 let is_static = tcx.is_static(def);
354
355 let mut ecx = InterpCx::new(
356 tcx,
357 tcx.def_span(def),
358 typing_env,
359 CompileTimeMachine::new(CanAccessMutGlobal::from(is_static), CheckAlignment::Error),
364 );
365 let res = ecx.load_mir(cid.instance.def, cid.promoted);
366 res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, body))
367 .report_err()
368 .map_err(|error| report_eval_error(&ecx, cid, error))
369}
370
371#[inline(always)]
372fn const_validate_mplace<'tcx>(
373 ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
374 mplace: &MPlaceTy<'tcx>,
375 cid: GlobalId<'tcx>,
376) -> Result<(), ErrorHandled> {
377 let alloc_id = mplace.ptr().provenance.unwrap().alloc_id();
378 let mut ref_tracking = RefTracking::new(mplace.clone());
379 let mut inner = false;
380 while let Some((mplace, path)) = ref_tracking.next() {
381 let mode = match ecx.tcx.static_mutability(cid.instance.def_id()) {
382 _ if cid.promoted.is_some() => CtfeValidationMode::Promoted,
383 Some(mutbl) => CtfeValidationMode::Static { mutbl }, None => {
385 CtfeValidationMode::Const { allow_immutable_unsafe_cell: !inner }
389 }
390 };
391 ecx.const_validate_operand(&mplace.into(), path, &mut ref_tracking, mode)
392 .report_err()
393 .map_err(|error| report_validation_error(&ecx, cid, error, alloc_id))?;
396 inner = true;
397 }
398
399 Ok(())
400}
401
402#[inline(never)]
403fn report_eval_error<'tcx>(
404 ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
405 cid: GlobalId<'tcx>,
406 error: InterpErrorInfo<'tcx>,
407) -> ErrorHandled {
408 let (error, backtrace) = error.into_parts();
409 backtrace.print_backtrace();
410
411 let instance = with_no_trimmed_paths!(cid.instance.to_string());
412
413 super::report(
414 ecx,
415 error,
416 DUMMY_SP,
417 || super::get_span_and_frames(ecx.tcx, ecx.stack()),
418 |diag, span, frames| {
419 let num_frames = frames.len();
420 diag.code(E0080);
422 diag.span_label(span, crate::fluent_generated::const_eval_error);
423 for frame in frames {
424 diag.subdiagnostic(frame);
425 }
426 diag.arg("instance", instance);
428 diag.arg("num_frames", num_frames);
429 },
430 )
431}
432
433#[inline(never)]
434fn report_validation_error<'tcx>(
435 ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
436 cid: GlobalId<'tcx>,
437 error: InterpErrorInfo<'tcx>,
438 alloc_id: AllocId,
439) -> ErrorHandled {
440 if !matches!(error.kind(), InterpErrorKind::UndefinedBehavior(_)) {
441 return report_eval_error(ecx, cid, error);
443 }
444
445 let (error, backtrace) = error.into_parts();
446 backtrace.print_backtrace();
447
448 let bytes = ecx.print_alloc_bytes_for_diagnostics(alloc_id);
449 let info = ecx.get_alloc_info(alloc_id);
450 let raw_bytes =
451 errors::RawBytesNote { size: info.size.bytes(), align: info.align.bytes(), bytes };
452
453 crate::const_eval::report(
454 ecx,
455 error,
456 DUMMY_SP,
457 || crate::const_eval::get_span_and_frames(ecx.tcx, ecx.stack()),
458 move |diag, span, frames| {
459 diag.code(E0080);
461 diag.span_label(span, crate::fluent_generated::const_eval_validation_failure);
462 diag.note(crate::fluent_generated::const_eval_validation_failure_note);
463 for frame in frames {
464 diag.subdiagnostic(frame);
465 }
466 diag.subdiagnostic(raw_bytes);
467 },
468 )
469}