1use std::borrow::{Borrow, Cow};
2use std::fmt;
3use std::hash::Hash;
4
5use rustc_abi::{Align, Size};
6use rustc_ast::Mutability;
7use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::{self as hir, CRATE_HIR_ID, LangItem};
10use rustc_middle::mir::AssertMessage;
11use rustc_middle::mir::interpret::{Pointer, ReportedErrorInfo};
12use rustc_middle::query::TyCtxtAt;
13use rustc_middle::ty::layout::{HasTypingEnv, TyAndLayout, ValidityRequirement};
14use rustc_middle::ty::{self, Ty, TyCtxt};
15use rustc_middle::{bug, mir};
16use rustc_span::{Span, Symbol, sym};
17use rustc_target::callconv::FnAbi;
18use tracing::debug;
19
20use super::error::*;
21use crate::errors::{LongRunning, LongRunningWarn};
22use crate::fluent_generated as fluent;
23use crate::interpret::{
24 self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
25 GlobalAlloc, ImmTy, InterpCx, InterpResult, OpTy, PlaceTy, RangeSet, Scalar,
26 compile_time_machine, err_inval, interp_ok, throw_exhaust, throw_inval, throw_ub,
27 throw_ub_custom, throw_unsup, throw_unsup_format,
28};
29
30const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
34const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
37const PROGRESS_INDICATOR_START: usize = 4_000_000;
40
41pub struct CompileTimeMachine<'tcx> {
46 pub(super) num_evaluated_steps: usize,
51
52 pub(super) stack: Vec<Frame<'tcx>>,
54
55 pub(super) can_access_mut_global: CanAccessMutGlobal,
59
60 pub(super) check_alignment: CheckAlignment,
62
63 pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
67
68 union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
70}
71
72#[derive(Copy, Clone)]
73pub enum CheckAlignment {
74 No,
77 Error,
79}
80
81#[derive(Copy, Clone, PartialEq)]
82pub(crate) enum CanAccessMutGlobal {
83 No,
84 Yes,
85}
86
87impl From<bool> for CanAccessMutGlobal {
88 fn from(value: bool) -> Self {
89 if value { Self::Yes } else { Self::No }
90 }
91}
92
93impl<'tcx> CompileTimeMachine<'tcx> {
94 pub(crate) fn new(
95 can_access_mut_global: CanAccessMutGlobal,
96 check_alignment: CheckAlignment,
97 ) -> Self {
98 CompileTimeMachine {
99 num_evaluated_steps: 0,
100 stack: Vec::new(),
101 can_access_mut_global,
102 check_alignment,
103 static_root_ids: None,
104 union_data_ranges: FxHashMap::default(),
105 }
106 }
107}
108
109impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
110 #[inline(always)]
111 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
112 where
113 K: Borrow<Q>,
114 {
115 FxIndexMap::contains_key(self, k)
116 }
117
118 #[inline(always)]
119 fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
120 where
121 K: Borrow<Q>,
122 {
123 FxIndexMap::contains_key(self, k)
124 }
125
126 #[inline(always)]
127 fn insert(&mut self, k: K, v: V) -> Option<V> {
128 FxIndexMap::insert(self, k, v)
129 }
130
131 #[inline(always)]
132 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
133 where
134 K: Borrow<Q>,
135 {
136 FxIndexMap::swap_remove(self, k)
138 }
139
140 #[inline(always)]
141 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
142 self.iter().filter_map(move |(k, v)| f(k, v)).collect()
143 }
144
145 #[inline(always)]
146 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
147 match self.get(&k) {
148 Some(v) => Ok(v),
149 None => {
150 vacant()?;
151 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
152 }
153 }
154 }
155
156 #[inline(always)]
157 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
158 match self.entry(k) {
159 IndexEntry::Occupied(e) => Ok(e.into_mut()),
160 IndexEntry::Vacant(e) => {
161 let v = vacant()?;
162 Ok(e.insert(v))
163 }
164 }
165 }
166}
167
168pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
169
170#[derive(Debug, PartialEq, Eq, Copy, Clone)]
171pub enum MemoryKind {
172 Heap {
173 was_made_global: bool,
176 },
177}
178
179impl fmt::Display for MemoryKind {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 match self {
182 MemoryKind::Heap { was_made_global } => {
183 write!(f, "heap allocation{}", if *was_made_global { " (made global)" } else { "" })
184 }
185 }
186 }
187}
188
189impl interpret::MayLeak for MemoryKind {
190 #[inline(always)]
191 fn may_leak(self) -> bool {
192 match self {
193 MemoryKind::Heap { was_made_global } => was_made_global,
194 }
195 }
196}
197
198impl interpret::MayLeak for ! {
199 #[inline(always)]
200 fn may_leak(self) -> bool {
201 self
203 }
204}
205
206impl<'tcx> CompileTimeInterpCx<'tcx> {
207 fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
208 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
209 let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
210
211 use rustc_span::RemapPathScopeComponents;
212 (
213 Symbol::intern(
214 &caller.file.name.display(RemapPathScopeComponents::DIAGNOSTICS).to_string_lossy(),
215 ),
216 u32::try_from(caller.line).unwrap(),
217 u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
218 )
219 }
220
221 fn hook_special_const_fn(
227 &mut self,
228 instance: ty::Instance<'tcx>,
229 args: &[FnArg<'tcx>],
230 _dest: &PlaceTy<'tcx>,
231 _ret: Option<mir::BasicBlock>,
232 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
233 let def_id = instance.def_id();
234
235 if self.tcx.is_lang_item(def_id, LangItem::PanicDisplay)
236 || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
237 {
238 let args = self.copy_fn_args(args);
239 assert!(args.len() == 1);
241
242 let mut msg_place = self.deref_pointer(&args[0])?;
243 while msg_place.layout.ty.is_ref() {
244 msg_place = self.deref_pointer(&msg_place)?;
245 }
246
247 let msg = Symbol::intern(self.read_str(&msg_place)?);
248 let span = self.find_closest_untracked_caller_location();
249 let (file, line, col) = self.location_triple_for_span(span);
250 return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
251 } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
252 let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
254 let new_instance = ty::Instance::expect_resolve(
255 *self.tcx,
256 self.typing_env(),
257 const_def_id,
258 instance.args,
259 self.cur_span(),
260 );
261
262 return interp_ok(Some(new_instance));
263 }
264 interp_ok(Some(instance))
265 }
266
267 fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
275 interp_ok(match (a, b) {
276 (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
278 (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
281 let int = int.to_target_usize(*self.tcx);
282 let offset_ptr = ptr.wrapping_offset(Size::from_bytes(int.wrapping_neg()), self);
285 if !self.scalar_may_be_null(Scalar::from_pointer(offset_ptr, self))? {
286 0
288 } else {
289 2
292 }
293 }
294 (Scalar::Ptr(a, _), Scalar::Ptr(b, _)) => {
295 let (a_prov, a_offset) = a.prov_and_relative_offset();
296 let (b_prov, b_offset) = b.prov_and_relative_offset();
297 let a_allocid = a_prov.alloc_id();
298 let b_allocid = b_prov.alloc_id();
299 let a_info = self.get_alloc_info(a_allocid);
300 let b_info = self.get_alloc_info(b_allocid);
301
302 if a_info.align > Align::ONE && b_info.align > Align::ONE {
304 let min_align = Ord::min(a_info.align.bytes(), b_info.align.bytes());
305 let a_residue = a_offset.bytes() % min_align;
306 let b_residue = b_offset.bytes() % min_align;
307 if a_residue != b_residue {
308 return interp_ok(0);
311 }
312 }
315
316 if let (Some(GlobalAlloc::Static(a_did)), Some(GlobalAlloc::Static(b_did))) = (
317 self.tcx.try_get_global_alloc(a_allocid),
318 self.tcx.try_get_global_alloc(b_allocid),
319 ) {
320 if a_allocid == b_allocid {
321 debug_assert_eq!(
322 a_did, b_did,
323 "different static item DefIds had same AllocId? {a_allocid:?} == {b_allocid:?}, {a_did:?} != {b_did:?}"
324 );
325 (a_offset == b_offset) as u8
330 } else {
331 debug_assert_ne!(
332 a_did, b_did,
333 "same static item DefId had two different AllocIds? {a_allocid:?} != {b_allocid:?}, {a_did:?} == {b_did:?}"
334 );
335 if a_offset < a_info.size && b_offset < b_info.size {
346 0
347 } else {
348 2
354 }
355 }
356 } else {
357 2
380 }
381 }
382 })
383 }
384}
385
386impl<'tcx> CompileTimeMachine<'tcx> {
387 #[inline(always)]
388 pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> hir::HirId {
391 self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
392 }
393}
394
395impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
396 compile_time_machine!(<'tcx>);
397
398 const PANIC_ON_ALLOC_FAIL: bool = false; #[inline(always)]
401 fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool {
402 matches!(ecx.machine.check_alignment, CheckAlignment::Error)
403 }
404
405 #[inline(always)]
406 fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
407 ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
408 }
409
410 fn load_mir(
411 ecx: &InterpCx<'tcx, Self>,
412 instance: ty::InstanceKind<'tcx>,
413 ) -> &'tcx mir::Body<'tcx> {
414 match instance {
415 ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
416 _ => ecx.tcx.instance_mir(instance),
417 }
418 }
419
420 fn find_mir_or_eval_fn(
421 ecx: &mut InterpCx<'tcx, Self>,
422 orig_instance: ty::Instance<'tcx>,
423 _abi: &FnAbi<'tcx, Ty<'tcx>>,
424 args: &[FnArg<'tcx>],
425 dest: &PlaceTy<'tcx>,
426 ret: Option<mir::BasicBlock>,
427 _unwind: mir::UnwindAction, ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
429 debug!("find_mir_or_eval_fn: {:?}", orig_instance);
430
431 let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
433 return interp_ok(None);
435 };
436
437 if let ty::InstanceKind::Item(def) = instance.def {
439 if !ecx.tcx.is_const_fn(def) || ecx.tcx.has_attr(def, sym::rustc_do_not_const_check) {
444 throw_unsup_format!("calling non-const function `{}`", instance)
447 }
448 }
449
450 interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
454 }
455
456 fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
457 let msg = Symbol::intern(msg);
458 let span = ecx.find_closest_untracked_caller_location();
459 let (file, line, col) = ecx.location_triple_for_span(span);
460 Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
461 }
462
463 fn call_intrinsic(
464 ecx: &mut InterpCx<'tcx, Self>,
465 instance: ty::Instance<'tcx>,
466 args: &[OpTy<'tcx>],
467 dest: &PlaceTy<'tcx, Self::Provenance>,
468 target: Option<mir::BasicBlock>,
469 _unwind: mir::UnwindAction,
470 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
471 if ecx.eval_intrinsic(instance, args, dest, target)? {
473 return interp_ok(None);
474 }
475 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
476
477 match intrinsic_name {
479 sym::ptr_guaranteed_cmp => {
480 let a = ecx.read_scalar(&args[0])?;
481 let b = ecx.read_scalar(&args[1])?;
482 let cmp = ecx.guaranteed_cmp(a, b)?;
483 ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
484 }
485 sym::const_allocate => {
486 let size = ecx.read_scalar(&args[0])?.to_target_usize(ecx)?;
487 let align = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
488
489 let align = match Align::from_bytes(align) {
490 Ok(a) => a,
491 Err(err) => throw_ub_custom!(
492 fluent::const_eval_invalid_align_details,
493 name = "const_allocate",
494 err_kind = err.diag_ident(),
495 align = err.align()
496 ),
497 };
498
499 let ptr = ecx.allocate_ptr(
500 Size::from_bytes(size),
501 align,
502 interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
503 AllocInit::Uninit,
504 )?;
505 ecx.write_pointer(ptr, dest)?;
506 }
507 sym::const_deallocate => {
508 let ptr = ecx.read_pointer(&args[0])?;
509 let size = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
510 let align = ecx.read_scalar(&args[2])?.to_target_usize(ecx)?;
511
512 let size = Size::from_bytes(size);
513 let align = match Align::from_bytes(align) {
514 Ok(a) => a,
515 Err(err) => throw_ub_custom!(
516 fluent::const_eval_invalid_align_details,
517 name = "const_deallocate",
518 err_kind = err.diag_ident(),
519 align = err.align()
520 ),
521 };
522
523 let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?;
526 let is_allocated_in_another_const = matches!(
527 ecx.tcx.try_get_global_alloc(alloc_id),
528 Some(interpret::GlobalAlloc::Memory(_))
529 );
530
531 if !is_allocated_in_another_const {
532 ecx.deallocate_ptr(
533 ptr,
534 Some((size, align)),
535 interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
536 )?;
537 }
538 }
539
540 sym::const_make_global => {
541 let ptr = ecx.read_pointer(&args[0])?;
542 ecx.make_const_heap_ptr_global(ptr)?;
543 ecx.write_pointer(ptr, dest)?;
544 }
545
546 sym::is_val_statically_known => ecx.write_scalar(Scalar::from_bool(false), dest)?,
551
552 sym::assert_inhabited
554 | sym::assert_zero_valid
555 | sym::assert_mem_uninitialized_valid => {
556 let ty = instance.args.type_at(0);
557 let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap();
558
559 let should_panic = !ecx
560 .tcx
561 .check_validity_requirement((requirement, ecx.typing_env().as_query_input(ty)))
562 .map_err(|_| err_inval!(TooGeneric))?;
563
564 if should_panic {
565 let layout = ecx.layout_of(ty)?;
566
567 let msg = match requirement {
568 _ if layout.is_uninhabited() => format!(
571 "aborted execution: attempted to instantiate uninhabited type `{ty}`"
572 ),
573 ValidityRequirement::Inhabited => bug!("handled earlier"),
574 ValidityRequirement::Zero => format!(
575 "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
576 ),
577 ValidityRequirement::UninitMitigated0x01Fill => format!(
578 "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
579 ),
580 ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"),
581 };
582
583 Self::panic_nounwind(ecx, &msg)?;
584 return interp_ok(None);
586 }
587 }
588
589 sym::type_of => {
590 let ty = ecx.read_type_id(&args[0])?;
591 ecx.write_type_info(ty, dest)?;
592 }
593
594 _ => {
595 if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
597 throw_unsup_format!(
598 "intrinsic `{intrinsic_name}` is not supported at compile-time"
599 );
600 }
601 return interp_ok(Some(ty::Instance {
602 def: ty::InstanceKind::Item(instance.def_id()),
603 args: instance.args,
604 }));
605 }
606 }
607
608 ecx.return_to_block(target)?;
610 interp_ok(None)
611 }
612
613 fn assert_panic(
614 ecx: &mut InterpCx<'tcx, Self>,
615 msg: &AssertMessage<'tcx>,
616 _unwind: mir::UnwindAction,
617 ) -> InterpResult<'tcx> {
618 use rustc_middle::mir::AssertKind::*;
619 let eval_to_int =
621 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
622 let err = match msg {
623 BoundsCheck { len, index } => {
624 let len = eval_to_int(len)?;
625 let index = eval_to_int(index)?;
626 BoundsCheck { len, index }
627 }
628 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
629 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
630 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
631 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
632 ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
633 ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
634 ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
635 MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
636 required: eval_to_int(required)?,
637 found: eval_to_int(found)?,
638 },
639 NullPointerDereference => NullPointerDereference,
640 InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
641 };
642 Err(ConstEvalErrKind::AssertFailure(err)).into()
643 }
644
645 #[inline(always)]
646 fn runtime_checks(
647 _ecx: &InterpCx<'tcx, Self>,
648 _r: mir::RuntimeChecks,
649 ) -> InterpResult<'tcx, bool> {
650 interp_ok(true)
653 }
654
655 fn binary_ptr_op(
656 _ecx: &InterpCx<'tcx, Self>,
657 _bin_op: mir::BinOp,
658 _left: &ImmTy<'tcx>,
659 _right: &ImmTy<'tcx>,
660 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
661 throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
662 }
663
664 fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
665 if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
668 let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
669 (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
670 } else {
671 (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
672 };
673
674 ecx.machine.num_evaluated_steps = new_steps;
675 if new_steps == limit {
680 let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
684 let is_error = ecx
685 .tcx
686 .lint_level_at_node(
687 rustc_session::lint::builtin::LONG_RUNNING_CONST_EVAL,
688 hir_id,
689 )
690 .level
691 .is_error();
692 let span = ecx.cur_span();
693 ecx.tcx.emit_node_span_lint(
694 rustc_session::lint::builtin::LONG_RUNNING_CONST_EVAL,
695 hir_id,
696 span,
697 LongRunning { item_span: ecx.tcx.span },
698 );
699 if is_error {
701 let guard = ecx
702 .tcx
703 .dcx()
704 .span_delayed_bug(span, "The deny lint should have already errored");
705 throw_inval!(AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));
706 }
707 } else if new_steps > start && new_steps.is_power_of_two() {
708 let span = ecx.cur_span();
712 ecx.tcx.dcx().emit_warn(LongRunningWarn {
716 span,
717 item_span: ecx.tcx.span,
718 force_duplicate: new_steps,
719 });
720 }
721 }
722
723 interp_ok(())
724 }
725
726 #[inline(always)]
727 fn expose_provenance(
728 _ecx: &InterpCx<'tcx, Self>,
729 _provenance: Self::Provenance,
730 ) -> InterpResult<'tcx> {
731 throw_unsup_format!("exposing pointers is not possible at compile-time")
733 }
734
735 #[inline(always)]
736 fn init_frame(
737 ecx: &mut InterpCx<'tcx, Self>,
738 frame: Frame<'tcx>,
739 ) -> InterpResult<'tcx, Frame<'tcx>> {
740 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
742 throw_exhaust!(StackFrameLimitReached)
743 } else {
744 interp_ok(frame)
745 }
746 }
747
748 #[inline(always)]
749 fn stack<'a>(
750 ecx: &'a InterpCx<'tcx, Self>,
751 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
752 &ecx.machine.stack
753 }
754
755 #[inline(always)]
756 fn stack_mut<'a>(
757 ecx: &'a mut InterpCx<'tcx, Self>,
758 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
759 &mut ecx.machine.stack
760 }
761
762 fn before_access_global(
763 _tcx: TyCtxtAt<'tcx>,
764 machine: &Self,
765 alloc_id: AllocId,
766 alloc: ConstAllocation<'tcx>,
767 _static_def_id: Option<DefId>,
768 is_write: bool,
769 ) -> InterpResult<'tcx> {
770 let alloc = alloc.inner();
771 if is_write {
772 match alloc.mutability {
774 Mutability::Not => throw_ub!(WriteToReadOnly(alloc_id)),
775 Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
776 }
777 } else {
778 if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
780 interp_ok(())
782 } else if alloc.mutability == Mutability::Mut {
783 Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
786 } else {
787 assert_eq!(alloc.mutability, Mutability::Not);
789 interp_ok(())
790 }
791 }
792 }
793
794 fn retag_ptr_value(
795 ecx: &mut InterpCx<'tcx, Self>,
796 _kind: mir::RetagKind,
797 val: &ImmTy<'tcx, CtfeProvenance>,
798 ) -> InterpResult<'tcx, ImmTy<'tcx, CtfeProvenance>> {
799 if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
802 && *mutbl == Mutability::Not
803 && val
804 .to_scalar_and_meta()
805 .0
806 .to_pointer(ecx)?
807 .provenance
808 .is_some_and(|p| !p.immutable())
809 {
810 let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
812 let place = ecx.ref_to_mplace(val)?;
813 let new_place = if is_immutable {
814 place.map_provenance(CtfeProvenance::as_immutable)
815 } else {
816 place.map_provenance(CtfeProvenance::as_shared_ref)
821 };
822 interp_ok(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout))
823 } else {
824 interp_ok(val.clone())
825 }
826 }
827
828 fn before_memory_write(
829 _tcx: TyCtxtAt<'tcx>,
830 _machine: &mut Self,
831 _alloc_extra: &mut Self::AllocExtra,
832 _ptr: Pointer<Option<Self::Provenance>>,
833 (_alloc_id, immutable): (AllocId, bool),
834 range: AllocRange,
835 ) -> InterpResult<'tcx> {
836 if range.size == Size::ZERO {
837 return interp_ok(());
839 }
840 if immutable {
842 return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
843 }
844 interp_ok(())
846 }
847
848 fn before_alloc_access(
849 tcx: TyCtxtAt<'tcx>,
850 machine: &Self,
851 alloc_id: AllocId,
852 ) -> InterpResult<'tcx> {
853 if machine.stack.is_empty() {
854 return interp_ok(());
856 }
857 if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
859 return Err(ConstEvalErrKind::RecursiveStatic).into();
860 }
861 if machine.static_root_ids.is_some() {
864 if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
865 if tcx.is_foreign_item(def_id) {
866 throw_unsup!(ExternStatic(def_id));
867 }
868 tcx.eval_static_initializer(def_id)?;
869 }
870 }
871 interp_ok(())
872 }
873
874 fn cached_union_data_range<'e>(
875 ecx: &'e mut InterpCx<'tcx, Self>,
876 ty: Ty<'tcx>,
877 compute_range: impl FnOnce() -> RangeSet,
878 ) -> Cow<'e, RangeSet> {
879 if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
880 Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
881 } else {
882 Cow::Owned(compute_range())
884 }
885 }
886
887 fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
888 }
889}
890
891