1use std::sync::atomic::Ordering::Relaxed;
2
3use either::{Left, Right};
4use rustc_abi::{self as abi, BackendRepr};
5use rustc_hir::def::DefKind;
6use rustc_middle::mir::interpret::{AllocId, ErrorHandled, InterpErrorInfo, ReportedErrorInfo};
7use rustc_middle::mir::{self, ConstAlloc, ConstValue};
8use rustc_middle::query::TyCtxtAt;
9use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
10use rustc_middle::ty::print::with_no_trimmed_paths;
11use rustc_middle::ty::{self, Ty, TyCtxt};
12use rustc_middle::{bug, throw_inval};
13use rustc_span::def_id::LocalDefId;
14use rustc_span::{DUMMY_SP, Span};
15use tracing::{debug, instrument, trace};
16
17use super::{CanAccessMutGlobal, CompileTimeInterpCx, CompileTimeMachine};
18use crate::const_eval::CheckAlignment;
19use crate::interpret::{
20 CtfeValidationMode, GlobalId, Immediate, InternKind, InternResult, InterpCx, InterpErrorKind,
21 InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, StackPopCleanup, create_static_alloc,
22 eval_nullary_intrinsic, intern_const_alloc_recursive, interp_ok, throw_exhaust,
23};
24use crate::{CTRL_C_RECEIVED, errors};
25
26#[instrument(level = "trace", skip(ecx, body))]
28fn eval_body_using_ecx<'tcx, R: InterpretationResult<'tcx>>(
29 ecx: &mut CompileTimeInterpCx<'tcx>,
30 cid: GlobalId<'tcx>,
31 body: &'tcx mir::Body<'tcx>,
32) -> InterpResult<'tcx, R> {
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().instantiate(tcx, cid.instance.args))?;
49 assert!(layout.is_sized());
50
51 let intern_kind = if cid.promoted.is_some() {
52 InternKind::Promoted
53 } else {
54 match tcx.static_mutability(cid.instance.def_id()) {
55 Some(m) => InternKind::Static(m),
56 None => InternKind::Constant,
57 }
58 };
59
60 let ret = if let InternKind::Static(_) = intern_kind {
61 create_static_alloc(ecx, cid.instance.def_id().expect_local(), layout)?
62 } else {
63 ecx.allocate(layout, MemoryKind::Stack)?
64 };
65
66 trace!(
67 "eval_body_using_ecx: pushing stack frame for global: {}{}",
68 with_no_trimmed_paths!(ecx.tcx.def_path_str(cid.instance.def_id())),
69 cid.promoted.map_or_else(String::new, |p| format!("::{p:?}"))
70 );
71
72 ecx.push_stack_frame_raw(cid.instance, body, &ret, StackPopCleanup::Root { cleanup: false })?;
75 ecx.storage_live_for_always_live_locals()?;
76
77 while ecx.step()? {
79 if CTRL_C_RECEIVED.load(Relaxed) {
80 throw_exhaust!(Interrupted);
81 }
82 }
83
84 let intern_result = intern_const_alloc_recursive(ecx, intern_kind, &ret);
86
87 const_validate_mplace(ecx, &ret, cid)?;
89
90 match intern_result {
94 Ok(()) => {}
95 Err(InternResult::FoundDanglingPointer) => {
96 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
97 ecx.tcx
98 .dcx()
99 .emit_err(errors::DanglingPtrInFinal { span: ecx.tcx.span, kind: intern_kind }),
100 )));
101 }
102 Err(InternResult::FoundBadMutablePointer) => {
103 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
104 ecx.tcx
105 .dcx()
106 .emit_err(errors::MutablePtrInFinal { span: ecx.tcx.span, kind: intern_kind }),
107 )));
108 }
109 }
110
111 interp_ok(R::make_result(ret, ecx))
112}
113
114pub(crate) fn mk_eval_cx_to_read_const_val<'tcx>(
125 tcx: TyCtxt<'tcx>,
126 root_span: Span,
127 typing_env: ty::TypingEnv<'tcx>,
128 can_access_mut_global: CanAccessMutGlobal,
129) -> CompileTimeInterpCx<'tcx> {
130 debug!("mk_eval_cx: {:?}", typing_env);
131 InterpCx::new(
132 tcx,
133 root_span,
134 typing_env,
135 CompileTimeMachine::new(can_access_mut_global, CheckAlignment::No),
136 )
137}
138
139pub fn mk_eval_cx_for_const_val<'tcx>(
142 tcx: TyCtxtAt<'tcx>,
143 typing_env: ty::TypingEnv<'tcx>,
144 val: mir::ConstValue<'tcx>,
145 ty: Ty<'tcx>,
146) -> Option<(CompileTimeInterpCx<'tcx>, OpTy<'tcx>)> {
147 let ecx = mk_eval_cx_to_read_const_val(tcx.tcx, tcx.span, typing_env, CanAccessMutGlobal::No);
148 let op = ecx.const_val_to_op(val, ty, None).discard_err()?;
150 Some((ecx, op))
151}
152
153#[instrument(skip(ecx), level = "debug")]
160pub(super) fn op_to_const<'tcx>(
161 ecx: &CompileTimeInterpCx<'tcx>,
162 op: &OpTy<'tcx>,
163 for_diagnostics: bool,
164) -> ConstValue<'tcx> {
165 if op.layout.is_zst() {
167 return ConstValue::ZeroSized;
168 }
169
170 let force_as_immediate = match op.layout.backend_repr {
176 BackendRepr::Scalar(abi::Scalar::Initialized { .. }) => true,
177 _ => false,
185 };
186 let immediate = if force_as_immediate {
187 match ecx.read_immediate(op).report_err() {
188 Ok(imm) => Right(imm),
189 Err(err) => {
190 if for_diagnostics {
191 op.as_mplace_or_imm()
193 } else {
194 panic!("normalization works on validated constants: {err:?}")
195 }
196 }
197 }
198 } else {
199 op.as_mplace_or_imm()
200 };
201
202 debug!(?immediate);
203
204 match immediate {
205 Left(ref mplace) => {
206 let (prov, offset) = mplace.ptr().into_parts();
208 let alloc_id = prov.expect("cannot have `fake` place for non-ZST type").alloc_id();
209 ConstValue::Indirect { alloc_id, offset }
210 }
211 Right(imm) => match *imm {
213 Immediate::Scalar(x) => ConstValue::Scalar(x),
214 Immediate::ScalarPair(a, b) => {
215 debug!("ScalarPair(a: {:?}, b: {:?})", a, b);
216 let pointee_ty = imm.layout.ty.builtin_deref(false).unwrap(); debug_assert!(
221 matches!(
222 ecx.tcx.struct_tail_for_codegen(pointee_ty, ecx.typing_env()).kind(),
223 ty::Str | ty::Slice(..),
224 ),
225 "`ConstValue::Slice` is for slice-tailed types only, but got {}",
226 imm.layout.ty,
227 );
228 let msg = "`op_to_const` on an immediate scalar pair must only be used on slice references to the beginning of an actual allocation";
229 let (prov, offset) = a.to_pointer(ecx).expect(msg).into_parts();
231 let alloc_id = prov.expect(msg).alloc_id();
232 let data = ecx.tcx.global_alloc(alloc_id).unwrap_memory();
233 assert!(offset == abi::Size::ZERO, "{}", msg);
234 let meta = b.to_target_usize(ecx).expect(msg);
235 ConstValue::Slice { data, meta }
236 }
237 Immediate::Uninit => bug!("`Uninit` is not a valid value for {}", op.layout.ty),
238 },
239 }
240}
241
242#[instrument(skip(tcx), level = "debug", ret)]
243pub(crate) fn turn_into_const_value<'tcx>(
244 tcx: TyCtxt<'tcx>,
245 constant: ConstAlloc<'tcx>,
246 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
247) -> ConstValue<'tcx> {
248 let cid = key.value;
249 let def_id = cid.instance.def.def_id();
250 let is_static = tcx.is_static(def_id);
251 let ecx = mk_eval_cx_to_read_const_val(
253 tcx,
254 tcx.def_span(key.value.instance.def_id()),
255 key.typing_env,
256 CanAccessMutGlobal::from(is_static),
257 );
258
259 let mplace = ecx.raw_const_to_mplace(constant).expect(
260 "can only fail if layout computation failed, \
261 which should have given a good error before ever invoking this function",
262 );
263 assert!(
264 !is_static || cid.promoted.is_some(),
265 "the `eval_to_const_value_raw` query should not be used for statics, use `eval_to_allocation` instead"
266 );
267
268 op_to_const(&ecx, &mplace.into(), false)
270}
271
272#[instrument(skip(tcx), level = "debug")]
273pub fn eval_to_const_value_raw_provider<'tcx>(
274 tcx: TyCtxt<'tcx>,
275 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
276) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
277 if let ty::InstanceKind::Intrinsic(def_id) = key.value.instance.def {
280 let ty = key.value.instance.ty(tcx, key.typing_env);
281 let ty::FnDef(_, args) = ty.kind() else {
282 bug!("intrinsic with type {:?}", ty);
283 };
284 return eval_nullary_intrinsic(tcx, key.typing_env, def_id, args).report_err().map_err(
285 |error| {
286 let span = tcx.def_span(def_id);
287
288 super::report(
289 tcx,
290 error.into_kind(),
291 span,
292 || (span, vec![]),
293 |span, _| errors::NullaryIntrinsicError { span },
294 )
295 },
296 );
297 }
298
299 tcx.eval_to_allocation_raw(key).map(|val| turn_into_const_value(tcx, val, key))
300}
301
302#[instrument(skip(tcx), level = "debug")]
303pub fn eval_static_initializer_provider<'tcx>(
304 tcx: TyCtxt<'tcx>,
305 def_id: LocalDefId,
306) -> ::rustc_middle::mir::interpret::EvalStaticInitializerRawResult<'tcx> {
307 assert!(tcx.is_static(def_id.to_def_id()));
308
309 let instance = ty::Instance::mono(tcx, def_id.to_def_id());
310 let cid = rustc_middle::mir::interpret::GlobalId { instance, promoted: None };
311 eval_in_interpreter(tcx, cid, ty::TypingEnv::fully_monomorphized())
312}
313
314pub trait InterpretationResult<'tcx> {
315 fn make_result(
319 mplace: MPlaceTy<'tcx>,
320 ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
321 ) -> Self;
322}
323
324impl<'tcx> InterpretationResult<'tcx> for ConstAlloc<'tcx> {
325 fn make_result(
326 mplace: MPlaceTy<'tcx>,
327 _ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
328 ) -> Self {
329 ConstAlloc { alloc_id: mplace.ptr().provenance.unwrap().alloc_id(), ty: mplace.layout.ty }
330 }
331}
332
333#[instrument(skip(tcx), level = "debug")]
334pub fn eval_to_allocation_raw_provider<'tcx>(
335 tcx: TyCtxt<'tcx>,
336 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
337) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> {
338 assert!(key.value.promoted.is_some() || !tcx.is_static(key.value.instance.def_id()));
341 debug_assert_eq!(key.typing_env.typing_mode, ty::TypingMode::PostAnalysis);
344 if cfg!(debug_assertions) {
345 let instance = with_no_trimmed_paths!(key.value.instance.to_string());
351 trace!("const eval: {:?} ({})", key, instance);
352 }
353
354 eval_in_interpreter(tcx, key.value, key.typing_env)
355}
356
357fn eval_in_interpreter<'tcx, R: InterpretationResult<'tcx>>(
358 tcx: TyCtxt<'tcx>,
359 cid: GlobalId<'tcx>,
360 typing_env: ty::TypingEnv<'tcx>,
361) -> Result<R, ErrorHandled> {
362 let def = cid.instance.def.def_id();
363 let is_static = tcx.is_static(def);
364
365 let mut ecx = InterpCx::new(
366 tcx,
367 tcx.def_span(def),
368 typing_env,
369 CompileTimeMachine::new(CanAccessMutGlobal::from(is_static), CheckAlignment::Error),
374 );
375 let res = ecx.load_mir(cid.instance.def, cid.promoted);
376 res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, body))
377 .report_err()
378 .map_err(|error| report_eval_error(&ecx, cid, error))
379}
380
381#[inline(always)]
382fn const_validate_mplace<'tcx>(
383 ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
384 mplace: &MPlaceTy<'tcx>,
385 cid: GlobalId<'tcx>,
386) -> Result<(), ErrorHandled> {
387 let alloc_id = mplace.ptr().provenance.unwrap().alloc_id();
388 let mut ref_tracking = RefTracking::new(mplace.clone());
389 let mut inner = false;
390 while let Some((mplace, path)) = ref_tracking.next() {
391 let mode = match ecx.tcx.static_mutability(cid.instance.def_id()) {
392 _ if cid.promoted.is_some() => CtfeValidationMode::Promoted,
393 Some(mutbl) => CtfeValidationMode::Static { mutbl }, None => {
395 CtfeValidationMode::Const { allow_immutable_unsafe_cell: !inner }
399 }
400 };
401 ecx.const_validate_operand(&mplace.into(), path, &mut ref_tracking, mode)
402 .report_err()
403 .map_err(|error| report_validation_error(&ecx, cid, error, alloc_id))?;
406 inner = true;
407 }
408
409 Ok(())
410}
411
412#[inline(never)]
413fn report_eval_error<'tcx>(
414 ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
415 cid: GlobalId<'tcx>,
416 error: InterpErrorInfo<'tcx>,
417) -> ErrorHandled {
418 let (error, backtrace) = error.into_parts();
419 backtrace.print_backtrace();
420
421 let (kind, instance) = if ecx.tcx.is_static(cid.instance.def_id()) {
422 ("static", String::new())
423 } else {
424 let instance = &cid.instance;
428 if !instance.args.is_empty() {
429 let instance = with_no_trimmed_paths!(instance.to_string());
430 ("const_with_path", instance)
431 } else {
432 ("const", String::new())
433 }
434 };
435
436 super::report(
437 *ecx.tcx,
438 error,
439 DUMMY_SP,
440 || super::get_span_and_frames(ecx.tcx, ecx.stack()),
441 |span, frames| errors::ConstEvalError {
442 span,
443 error_kind: kind,
444 instance,
445 frame_notes: frames,
446 },
447 )
448}
449
450#[inline(never)]
451fn report_validation_error<'tcx>(
452 ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
453 cid: GlobalId<'tcx>,
454 error: InterpErrorInfo<'tcx>,
455 alloc_id: AllocId,
456) -> ErrorHandled {
457 if !matches!(error.kind(), InterpErrorKind::UndefinedBehavior(_)) {
458 return report_eval_error(ecx, cid, error);
460 }
461
462 let (error, backtrace) = error.into_parts();
463 backtrace.print_backtrace();
464
465 let bytes = ecx.print_alloc_bytes_for_diagnostics(alloc_id);
466 let info = ecx.get_alloc_info(alloc_id);
467 let raw_bytes =
468 errors::RawBytesNote { size: info.size.bytes(), align: info.align.bytes(), bytes };
469
470 crate::const_eval::report(
471 *ecx.tcx,
472 error,
473 DUMMY_SP,
474 || crate::const_eval::get_span_and_frames(ecx.tcx, ecx.stack()),
475 move |span, frames| errors::ValidationFailure { span, ub_note: (), frames, raw_bytes },
476 )
477}