1use std::borrow::{Borrow, Cow};
2use std::hash::Hash;
3use std::{fmt, mem};
45use rustc_abi::{Align, Size};
6use rustc_ast::Mutability;
7use rustc_attr_ir::find_attr;
8use rustc_attr_ir::lang_items::LangItem;
9use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::{CRATE_HIR_ID, HirId};
12use rustc_lint_defs::builtin::LONG_RUNNING_CONST_EVAL;
13use rustc_middle::mir;
14use rustc_middle::mir::AssertMessage;
15use rustc_middle::mir::interpret::ReportedErrorInfo;
16use rustc_middle::query::TyCtxtAt;
17use rustc_middle::ty::layout::{HasTypingEnv, TyAndLayout};
18use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt};
19use rustc_span::{Span, Symbol, bug, span_bug};
20use rustc_target::callconv::FnAbi;
21use tracing::debug;
2223use super::error::*;
24use crate::diagnostics::{LongRunning, LongRunningWarn};
25use crate::interpret::{
26self, AllocId, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame, GlobalAlloc, ImmTy,
27InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet, RetagMode, Scalar,
28compile_time_machine, interp_ok, throw_exhaust, throw_inval, throw_ub, throw_unsup,
29throw_unsup_format,
30};
3132/// When hitting this many interpreted terminators we emit a deny by default lint
33/// that notfies the user that their constant takes a long time to evaluate. If that's
34/// what they intended, they can just allow the lint.
35const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
36/// The limit used by `-Z tiny-const-eval-limit`. This smaller limit is useful for internal
37/// tests not needing to run 30s or more to show some behaviour.
38const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
39/// After this many interpreted terminators, we start emitting progress indicators at every
40/// power of two of interpreted terminators.
41const PROGRESS_INDICATOR_START: usize = 4_000_000;
4243/// Extra machine state for CTFE, and the Machine instance.
44//
45// Should be public because out-of-tree rustc consumers need this
46// if they want to interact with constant values.
47pub struct CompileTimeMachine<'tcx> {
48/// The number of terminators that have been evaluated.
49 ///
50 /// This is used to produce lints informing the user that the compiler is not stuck.
51 /// Set to `usize::MAX` to never report anything.
52pub(super) num_evaluated_steps: usize,
5354/// The virtual call stack.
55pub(super) stack: Vec<Frame<'tcx>>,
5657/// Pattern matching on consts with references would be unsound if those references
58 /// could point to anything mutable. Therefore, when evaluating consts and when constructing valtrees,
59 /// we ensure that only immutable global memory can be accessed.
60pub(super) can_access_mut_global: CanAccessMutGlobal,
6162/// Whether to check alignment during evaluation.
63pub(super) check_alignment: CheckAlignment,
6465/// If `Some`, we are evaluating the initializer of the static with the given `LocalDefId`,
66 /// storing the result in the given `AllocId`.
67 /// Used to prevent accesses to a static's base allocation, as that may allow for self-initialization loops.
68pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
6970/// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
71union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
7273/// The current retag mode.
74retag_mode: RetagMode,
75}
7677#[derive(#[automatically_derived]impl ::core::marker::Copy for CheckAlignment { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CheckAlignment {
}
#[automatically_derived]impl ::core::clone::Clone for CheckAlignment {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone)]
78pub enum CheckAlignment {
79/// Ignore all alignment requirements.
80 /// This is mainly used in interning.
81No,
82/// Hard error when dereferencing a misaligned pointer.
83Error,
84}
8586#[derive(#[automatically_derived]impl ::core::marker::Copy for CanAccessMutGlobal { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for CanAccessMutGlobal {
}
#[automatically_derived]impl ::core::clone::Clone for CanAccessMutGlobal {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
CanAccessMutGlobal {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CanAccessMutGlobal {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
87pub(crate) enum CanAccessMutGlobal {
88 No,
89 Yes,
90}
9192impl From<bool> for CanAccessMutGlobal {
93fn from(value: bool) -> Self {
94if value { Self::Yes } else { Self::No }
95 }
96}
9798impl<'tcx> CompileTimeMachine<'tcx> {
99pub(crate) fn new(
100 can_access_mut_global: CanAccessMutGlobal,
101 check_alignment: CheckAlignment,
102 ) -> Self {
103CompileTimeMachine {
104 num_evaluated_steps: 0,
105 stack: Vec::new(),
106can_access_mut_global,
107check_alignment,
108 static_root_ids: None,
109 union_data_ranges: FxHashMap::default(),
110 retag_mode: RetagMode::Default,
111 }
112 }
113}
114115impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
116#[inline(always)]
117fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool118where
119K: Borrow<Q>,
120 {
121FxIndexMap::contains_key(self, k)
122 }
123124#[inline(always)]
125fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool126where
127K: Borrow<Q>,
128 {
129FxIndexMap::contains_key(self, k)
130 }
131132#[inline(always)]
133fn insert(&mut self, k: K, v: V) -> Option<V> {
134FxIndexMap::insert(self, k, v)
135 }
136137#[inline(always)]
138fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
139where
140K: Borrow<Q>,
141 {
142// FIXME(#120456) - is `swap_remove` correct?
143FxIndexMap::swap_remove(self, k)
144 }
145146#[inline(always)]
147fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
148self.iter().filter_map(move |(k, v)| f(k, v)).collect()
149 }
150151#[inline(always)]
152fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
153match self.get(&k) {
154Some(v) => Ok(v),
155None => {
156 vacant()?;
157::rustc_span::macros::bug_impl(None,
format_args!("The CTFE machine shouldn\'t ever need to extend the alloc_map when reading"),
Location::caller())bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")158 }
159 }
160 }
161162#[inline(always)]
163fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
164match self.entry(k) {
165IndexEntry::Occupied(e) => Ok(e.into_mut()),
166IndexEntry::Vacant(e) => {
167let v = vacant()?;
168Ok(e.insert(v))
169 }
170 }
171 }
172}
173174pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
175176#[derive(#[automatically_derived]impl ::core::fmt::Debug for MemoryKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Heap { was_made_global: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Heap was_made_global", &__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
MemoryKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MemoryKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Heap { was_made_global: __self_0 }, Self::Heap {
was_made_global: __arg1_0 }) => __self_0 == __arg1_0,
}
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for MemoryKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, #[automatically_derived]impl ::core::marker::Copy for MemoryKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for MemoryKind {
}
#[automatically_derived]impl ::core::clone::Clone for MemoryKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone)]
177pub enum MemoryKind {
178 Heap {
179/// Indicates whether `make_global` was called on this allocation.
180 /// If this is `true`, the allocation must be immutable.
181was_made_global: bool,
182 },
183}
184185impl fmt::Displayfor MemoryKind {
186fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187match self {
188 MemoryKind::Heap { was_made_global } => {
189f.write_fmt(format_args!("heap allocation{0}",
if *was_made_global { " (made global)" } else { "" }))write!(f, "heap allocation{}", if *was_made_global { " (made global)" } else { "" })190 }
191 }
192 }
193}
194195impl interpret::MayLeakfor MemoryKind {
196#[inline(always)]
197fn may_leak(self) -> bool {
198match self {
199 MemoryKind::Heap { was_made_global } => was_made_global,
200 }
201 }
202}
203204impl interpret::MayLeakfor ! {
205#[inline(always)]
206fn may_leak(self) -> bool {
207// `self` is uninhabited
208self209 }
210}
211212impl<'tcx> CompileTimeInterpCx<'tcx> {
213pub(crate) fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
214let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
215let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
216217use rustc_span::RemapPathScopeComponents;
218 (
219Symbol::intern(
220&caller.file.name.display(RemapPathScopeComponents::DIAGNOSTICS).to_string_lossy(),
221 ),
222u32::try_from(caller.line).unwrap(),
223u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
224 )
225 }
226227/// "Intercept" a function call, because we have something special to do for it.
228 /// All `#[rustc_do_not_const_check]` functions MUST be hooked here.
229 /// If this returns `Some` function, which may be `instance` or a different function with
230 /// compatible arguments, then evaluation should continue with that function.
231 /// If this returns `None`, the function call has been handled and the function has returned.
232fn hook_special_const_fn(
233&mut self,
234 instance: ty::Instance<'tcx>,
235 args: &[FnArg<'tcx>],
236 _dest: &PlaceTy<'tcx>,
237 _ret: Option<mir::BasicBlock>,
238 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
239let def_id = instance.def_id();
240241if self.tcx.is_lang_item(def_id, LangItem::PanicDisplay)
242 || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
243 {
244let args = Self::copy_fn_args(args);
245// &str or &&str
246if !(args.len() == 1) {
::core::panicking::panic("assertion failed: args.len() == 1")
};assert!(args.len() == 1);
247248let mut msg_place = self.deref_pointer(&args[0])?;
249while msg_place.layout.ty.is_ref() {
250 msg_place = self.deref_pointer(&msg_place)?;
251 }
252253let msg = Symbol::intern(self.read_str(&msg_place)?);
254let span = self.caller_location();
255let (file, line, col) = self.location_triple_for_span(span);
256return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
257 } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
258// For panic_fmt, call const_panic_fmt instead.
259let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
260let new_instance = ty::Instance::expect_resolve(
261*self.tcx,
262self.typing_env(),
263const_def_id,
264instance.args,
265self.cur_span(),
266 );
267268return interp_ok(Some(new_instance));
269 }
270interp_ok(Some(instance))
271 }
272273/// See documentation on the `ptr_guaranteed_cmp` intrinsic.
274 /// Returns `2` if the result is unknown.
275 /// Returns `1` if the pointers are guaranteed equal.
276 /// Returns `0` if the pointers are guaranteed inequal.
277 ///
278 /// Note that this intrinsic is exposed on stable for comparison with null. In other words, any
279 /// change to this function that affects comparison with null is insta-stable!
280pub(crate) fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
281interp_ok(match (a, b) {
282// Comparisons between integers are always known.
283(Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
284// Comparing a pointer `ptr` with an integer `int` is equivalent to comparing
285 // `ptr-int` with null, so we can reduce this case to a `scalar_may_be_null` test.
286(Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
287let int = int.to_target_usize(*self.tcx);
288// The `wrapping_neg` here may produce a value that is not
289 // a valid target usize any more... but `wrapping_offset` handles that correctly.
290let offset_ptr = ptr.wrapping_offset(Size::from_bytes(int.wrapping_neg()), self);
291if !self.scalar_may_be_null(Scalar::from_pointer(offset_ptr, self))? {
292// `ptr.wrapping_sub(int)` is definitely not equal to `0`, so `ptr != int`
2930
294} else {
295// `ptr.wrapping_sub(int)` could be equal to `0`, but might not be,
296 // so we cannot know for sure if `ptr == int` or not
2972
298}
299 }
300 (Scalar::Ptr(a, _), Scalar::Ptr(b, _)) => {
301let (a_prov, a_offset) = a.prov_and_relative_offset();
302let (b_prov, b_offset) = b.prov_and_relative_offset();
303let a_allocid = a_prov.alloc_id();
304let b_allocid = b_prov.alloc_id();
305let a_info = self.get_alloc_info(a_allocid);
306let b_info = self.get_alloc_info(b_allocid);
307308// Check if the pointers cannot be equal due to alignment
309if a_info.align > Align::ONE && b_info.align > Align::ONE {
310let min_align = Ord::min(a_info.align.bytes(), b_info.align.bytes());
311let a_residue = a_offset.bytes() % min_align;
312let b_residue = b_offset.bytes() % min_align;
313if a_residue != b_residue {
314// If the two pointers have a different residue modulo their
315 // common alignment, they cannot be equal.
316return interp_ok(0);
317 }
318// The pointers have the same residue modulo their common alignment,
319 // so they could be equal. Try the other checks.
320}
321322if let (Some(GlobalAlloc::Static(a_did)), Some(GlobalAlloc::Static(b_did))) = (
323self.tcx.try_get_global_alloc(a_allocid),
324self.tcx.try_get_global_alloc(b_allocid),
325 ) {
326if a_allocid == b_allocid {
327if true {
{
match (&a_did, &b_did) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("different static item DefIds had same AllocId? {0:?} == {1:?}, {2:?} != {3:?}",
a_allocid, b_allocid, a_did, b_did)));
}
}
}
};
};debug_assert_eq!(
328 a_did, b_did,
329"different static item DefIds had same AllocId? {a_allocid:?} == {b_allocid:?}, {a_did:?} != {b_did:?}"
330);
331// Comparing two pointers into the same static. As per
332 // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
333 // a static cannot be duplicated, so if two pointers are into the same
334 // static, they are equal if and only if their offsets are equal.
335(a_offset == b_offset) as u8336 } else {
337if true {
{
match (&(a_did), &(b_did)) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("same static item DefId had two different AllocIds? {0:?} != {1:?}, {2:?} == {3:?}",
a_allocid, b_allocid, a_did, b_did)));
}
}
}
};
};debug_assert_ne!(
338 a_did, b_did,
339"same static item DefId had two different AllocIds? {a_allocid:?} != {b_allocid:?}, {a_did:?} == {b_did:?}"
340);
341// Comparing two pointers into the different statics.
342 // We can never determine for sure that two pointers into different statics
343 // are *equal*, but we can know that they are *inequal* if they are both
344 // strictly in-bounds (i.e. in-bounds and not one-past-the-end) of
345 // their respective static, as different non-zero-sized statics cannot
346 // overlap or be deduplicated as per
347 // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.intro
348 // (non-deduplication), and
349 // https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
350 // (non-overlapping).
351if a_offset < a_info.size && b_offset < b_info.size {
3520
353} else {
354// Otherwise, conservatively say we don't know.
355 // There are some cases we could still return `0` for, e.g.
356 // if the pointers being equal would require their statics to overlap
357 // one or more bytes, but for simplicity we currently only check
358 // strictly in-bounds pointers.
3592
360}
361 }
362 } else {
363// All other cases we conservatively say we don't know.
364 //
365 // For comparing statics to non-statics, as per https://doc.rust-lang.org/nightly/reference/items/static-items.html#r-items.static.storage-disjointness
366 // immutable statics can overlap with other kinds of allocations sometimes.
367 //
368 // FIXME: We could be more decisive for (non-zero-sized) mutable statics,
369 // which cannot overlap with other kinds of allocations.
370 //
371 // Functions and vtables can be duplicated and deduplicated, so we
372 // cannot be sure of runtime equality of pointers to the same one, or the
373 // runtime inequality of pointers to different ones (see e.g. #73722),
374 // so comparing those should return 2, whether they are the same allocation
375 // or not.
376 //
377 // `GlobalAlloc::TypeId` exists mostly to prevent consteval from comparing
378 // `TypeId`s, so comparing those should always return 2, whether they are the
379 // same allocation or not.
380 //
381 // FIXME: We could revisit comparing pointers into the same
382 // `GlobalAlloc::Memory` once https://github.com/rust-lang/rust/issues/128775
383 // is fixed (but they can be deduplicated, so comparing pointers into different
384 // ones should return 2).
3852
386}
387 }
388 })
389 }
390}
391392impl<'tcx> CompileTimeMachine<'tcx> {
393#[inline(always)]
394/// Find the first stack frame that is within the current crate, if any.
395 /// Otherwise, return the crate's HirId
396pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> HirId {
397self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
398 }
399}
400401impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
402type Provenance = CtfeProvenance;
type ProvenanceExtra = bool;
type ExtraFnVal = !;
type MemoryKind = crate::const_eval::MemoryKind;
type MemoryMap =
rustc_data_structures::fx::FxIndexMap<AllocId,
(MemoryKind<Self::MemoryKind>, Allocation)>;
const GLOBAL_KIND: Option<Self::MemoryKind> = None;
type AllocExtra = ();
type FrameExtra = ();
type Bytes = Box<[u8]>;
#[inline(always)]
fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool {
false
}
#[inline(always)]
fn unwind_terminate(_ecx: &mut InterpCx<'tcx, Self>,
_reason: mir::UnwindTerminateReason) -> InterpResult<'tcx> {
{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unwinding cannot happen during compile-time evaluation")));
}
}
#[inline(always)]
fn check_fn_target_features(_ecx: &InterpCx<'tcx, Self>,
_instance: ty::Instance<'tcx>) -> InterpResult<'tcx> {
interp_ok(())
}
#[inline(always)]
fn call_extra_fn(_ecx: &mut InterpCx<'tcx, Self>, fn_val: !,
_abi: &FnAbi<'tcx, Ty<'tcx>>, _args: &[FnArg<'tcx>],
_destination: &PlaceTy<'tcx, Self::Provenance>,
_target: Option<mir::BasicBlock>, _unwind: mir::UnwindAction)
-> InterpResult<'tcx> {
match fn_val {}
}
#[inline(always)]
fn float_fuse_mul_add(_ecx: &InterpCx<'tcx, Self>) -> bool { true }
#[inline(always)]
fn atomic_load(ecx: &InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
-> InterpResult<'tcx, Scalar<Self::Provenance>> {
ecx.read_scalar(place)
}
#[inline(always)]
fn atomic_store(ecx: &mut InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>,
val: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
-> InterpResult<'tcx> {
ecx.write_scalar(val.to_scalar(), place)
}
fn atomic_rmw(ecx: &mut InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>, op: AtomicRmwOp,
operand: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
-> InterpResult<'tcx, Scalar<Self::Provenance>> {
let old_val = ecx.read_immediate(place)?;
let new_val = ecx.atomic_rmw_op(op, &old_val, operand)?;
ecx.write_immediate(*new_val, place)?;
interp_ok(old_val.to_scalar())
}
fn atomic_compare_exchange(ecx: &mut InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>,
expected_old: &ImmTy<'tcx, Self::Provenance>,
new: &ImmTy<'tcx, Self::Provenance>, _can_fail_spuriously: bool,
_success_ordering: AtomicOrdering, _failure_ordering: AtomicOrdering)
-> InterpResult<'tcx, (Scalar<Self::Provenance>, bool)> {
let actual_old = ecx.read_immediate(place)?;
let eq =
ecx.binary_op(mir::BinOp::Eq, &actual_old,
expected_old)?.to_scalar().to_bool()?;
if eq { ecx.write_immediate(**new, place)?; }
interp_ok((actual_old.to_scalar(), eq))
}
#[inline(always)]
fn atomic_fence(_ecx: &InterpCx<'tcx, Self>, _ordering: AtomicOrdering,
_singlethread: bool) -> InterpResult<'tcx> {
interp_ok(())
}
#[inline(always)]
fn adjust_global_allocation<'b>(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
alloc: &'b Allocation)
-> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance>>> {
interp_ok(Cow::Borrowed(alloc))
}
fn init_local_allocation(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
_kind: MemoryKind<Self::MemoryKind>, _size: Size, _align: Align)
-> InterpResult<'tcx, Self::AllocExtra> {
interp_ok(())
}
fn extern_static_pointer(ecx: &InterpCx<'tcx, Self>, def_id: DefId)
-> InterpResult<'tcx, Pointer> {
interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(),
Size::ZERO))
}
#[inline(always)]
fn adjust_alloc_root_pointer(_ecx: &InterpCx<'tcx, Self>,
ptr: Pointer<CtfeProvenance>, _kind: Option<MemoryKind<Self::MemoryKind>>)
-> InterpResult<'tcx, Pointer<CtfeProvenance>> {
interp_ok(ptr)
}
#[inline(always)]
fn ptr_from_addr_cast(_ecx: &InterpCx<'tcx, Self>, addr: u64)
-> InterpResult<'tcx, Pointer<Option<CtfeProvenance>>> {
interp_ok(Pointer::without_provenance(addr))
}
#[inline(always)]
fn ptr_get_alloc(_ecx: &InterpCx<'tcx, Self>, ptr: Pointer<CtfeProvenance>,
_size: i64) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
let (prov, offset) = ptr.prov_and_relative_offset();
Some((prov.alloc_id(), offset, prov.immutable()))
}
#[inline(always)]
fn get_global_alloc_salt(_ecx: &InterpCx<'tcx, Self>,
_instance: Option<ty::Instance<'tcx>>) -> usize {
CTFE_ALLOC_SALT
}compile_time_machine!(<'tcx>);
403404const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
405406#[inline(always)]
407fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool {
408#[allow(non_exhaustive_omitted_patterns)] match ecx.machine.check_alignment {
CheckAlignment::Error => true,
_ => false,
}matches!(ecx.machine.check_alignment, CheckAlignment::Error)409 }
410411#[inline(always)]
412fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
413ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
414 }
415416fn load_mir(
417 ecx: &InterpCx<'tcx, Self>,
418 instance: ty::InstanceKind<'tcx>,
419 ) -> &'tcx mir::Body<'tcx> {
420match instance {
421 ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
422_ => ecx.tcx.instance_mir(instance),
423 }
424 }
425426fn find_mir_or_eval_fn(
427 ecx: &mut InterpCx<'tcx, Self>,
428 orig_instance: ty::Instance<'tcx>,
429 _abi: &FnAbi<'tcx, Ty<'tcx>>,
430 args: &[FnArg<'tcx>],
431 dest: &PlaceTy<'tcx>,
432 ret: Option<mir::BasicBlock>,
433 _unwind: mir::UnwindAction, // unwinding is not supported in consts
434) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
435{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/const_eval/machine.rs:435",
"rustc_const_eval::const_eval::machine",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_const_eval/src/const_eval/machine.rs"),
::tracing_core::__macro_support::Option::Some(435u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::machine"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_mir_or_eval_fn: {0:?}",
orig_instance) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("find_mir_or_eval_fn: {:?}", orig_instance);
436437// Replace some functions.
438let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
439// Call has already been handled.
440return interp_ok(None);
441 };
442443// Only check non-glue functions
444if let ty::InstanceKind::Item(def) = instance.def {
445// Execution might have wandered off into other crates, so we cannot do a stability-
446 // sensitive check here. But we can at least rule out functions that are not const at
447 // all. That said, we have to allow calling functions inside a `const trait`. These
448 // *are* const-checked!
449if !ecx.tcx.is_const_fn(def) || {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def, &ecx.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDoNotConstCheck) =>
{
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(ecx.tcx, def, RustcDoNotConstCheck) {
450// We certainly do *not* want to actually call this fn. const-checking should have
451 // prevented this, but this can be reached with unleashed-miri, so make testing
452 // simpler by avoiding ICEs there. (Technically this can still ICE if miri-unleash
453 // was set in a dependency rather than the current crate. That's okay, it's an
454 // internal unstable feature.)
455if ecx.tcx.sess.opts.unstable_opts.unleash_the_miri_inside_of_you {
456do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("calling non-const function `{0}`",
instance))
})))throw_unsup_format!("calling non-const function `{}`", instance)457 } else {
458::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("calling non-const function `{0}`", instance),
Location::caller())span_bug!(ecx.cur_span(), "calling non-const function `{}`", instance)459 }
460 }
461 }
462463// This is a const fn. Call it.
464 // In case of replacement, we return the *original* instance to make backtraces work out
465 // (and we hope this does not confuse the FnAbi checks too much).
466interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
467 }
468469fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
470let msg = Symbol::intern(msg);
471let span = ecx.caller_location();
472let (file, line, col) = ecx.location_triple_for_span(span);
473Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
474 }
475476fn call_intrinsic(
477 ecx: &mut InterpCx<'tcx, Self>,
478 instance: ty::Instance<'tcx>,
479 args: &[OpTy<'tcx>],
480 dest: &PlaceTy<'tcx, Self::Provenance>,
481 target: Option<mir::BasicBlock>,
482 _unwind: mir::UnwindAction,
483 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
484// Shared intrinsics.
485if ecx.eval_intrinsic(instance, args, dest, target)? {
486return interp_ok(None);
487 }
488let intrinsic_name = ecx.tcx.intrinsic(instance.def_id()).unwrap().name;
489490let do_fallback = |ecx: &mut InterpCx<'tcx, Self>| {
491// We haven't handled the intrinsic, let's see if we can use a fallback body.
492if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
493do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("intrinsic `{0}` is not supported at compile-time",
intrinsic_name))
})));throw_unsup_format!(
494"intrinsic `{intrinsic_name}` is not supported at compile-time"
495);
496 }
497return interp_ok(Some(ty::Instance {
498 def: ty::InstanceKind::Item(instance.def_id()),
499 args: instance.args,
500 }));
501 };
502503// Backend intrinsics are not supported in const eval except with their fallback
504 // bodies.
505let Intrinsic::Rustc(intrinsic_name) = intrinsic_nameelse {
506return do_fallback(ecx);
507 };
508509if !ecx.call_type_info_intrinsic(intrinsic_name, instance, args, dest, target)?
510&& !ecx.call_ctfe_intrinsic(intrinsic_name, instance, args, dest, target)?
511{
512return do_fallback(ecx);
513 }
514515interp_ok(None)
516 }
517518fn call_llvm_intrinsic(
519 ecx: &mut InterpCx<'tcx, Self>,
520 instance: ty::Instance<'tcx>,
521 _args: &[OpTy<'tcx>],
522 _dest: &PlaceTy<'tcx, Self::Provenance>,
523 _target: Option<mir::BasicBlock>,
524 ) -> InterpResult<'tcx> {
525let intrinsic_name = ecx.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap();
526527do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("LLVM intrinsic `{0}` is not supported at compile-time",
intrinsic_name))
})));throw_unsup_format!("LLVM intrinsic `{intrinsic_name}` is not supported at compile-time");
528 }
529530fn assert_panic(
531 ecx: &mut InterpCx<'tcx, Self>,
532 msg: &AssertMessage<'tcx>,
533 _unwind: mir::UnwindAction,
534 ) -> InterpResult<'tcx> {
535use rustc_middle::mir::AssertKind::*;
536// Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
537let eval_to_int =
538 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
539let err = match msg {
540BoundsCheck { len, index } => {
541let len = eval_to_int(len)?;
542let index = eval_to_int(index)?;
543BoundsCheck { len, index }
544 }
545Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
546OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
547DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
548RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
549ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
550ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
551ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
552MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
553 required: eval_to_int(required)?,
554 found: eval_to_int(found)?,
555 },
556NullPointerDereference => NullPointerDereference,
557NullReferenceConstructed => NullReferenceConstructed,
558InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
559 };
560Err(ConstEvalErrKind::AssertFailure(err)).into()
561 }
562563#[inline(always)]
564fn runtime_checks(
565 _ecx: &InterpCx<'tcx, Self>,
566 _r: mir::RuntimeChecks,
567 ) -> InterpResult<'tcx, bool> {
568// We can't look at `tcx.sess` here as that can differ across crates, which can lead to
569 // unsound differences in evaluating the same constant at different instantiation sites.
570interp_ok(true)
571 }
572573fn binary_ptr_op(
574 _ecx: &InterpCx<'tcx, Self>,
575 _bin_op: mir::BinOp,
576 _left: &ImmTy<'tcx>,
577 _right: &ImmTy<'tcx>,
578 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
579do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pointer arithmetic or comparison is not supported at compile-time"))
})));throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
580 }
581582fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
583// The step limit has already been hit in a previous call to `increment_const_eval_counter`.
584585if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
586let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
587 (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
588 } else {
589 (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
590 };
591592ecx.machine.num_evaluated_steps = new_steps;
593// By default, we have a *deny* lint kicking in after some time
594 // to ensure `loop {}` doesn't just go forever.
595 // In case that lint got reduced, in particular for `--cap-lint` situations, we also
596 // have a hard warning shown every now and then for really long executions.
597if new_steps == limit {
598// By default, we stop after a million steps, but the user can disable this lint
599 // to be able to run until the heat death of the universe or power loss, whichever
600 // comes first.
601let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
602let is_error = ecx603 .tcx
604 .lint_level_spec_at_node(LONG_RUNNING_CONST_EVAL, hir_id)
605 .level()
606 .is_error();
607let span = ecx.cur_span();
608ecx.tcx.emit_node_span_lint(
609LONG_RUNNING_CONST_EVAL,
610hir_id,
611span,
612LongRunning { item_span: ecx.tcx.span },
613 );
614// If this was a hard error, don't bother continuing evaluation.
615if is_error {
616let guard = ecx617 .tcx
618 .dcx()
619 .span_delayed_bug(span, "The deny lint should have already errored");
620do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));throw_inval!(AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));
621 }
622 } else if new_steps > start && new_steps.is_power_of_two() {
623// Only report after a certain number of terminators have been evaluated and the
624 // current number of evaluated terminators is a power of 2. The latter gives us a cheap
625 // way to implement exponential backoff.
626let span = ecx.cur_span();
627let mut warn =
628ecx.tcx.dcx().create_warn(LongRunningWarn { span, item_span: ecx.tcx.span });
629// We store a unique number in `force_duplicate` to evade `-Z deduplicate-diagnostics`.
630 // `new_steps` is guaranteed to be unique because `ecx.machine.num_evaluated_steps` is
631 // always increasing.
632warn.arg("force_duplicate", new_steps);
633warn.emit();
634 }
635 }
636637interp_ok(())
638 }
639640#[inline(always)]
641fn expose_provenance(
642 _ecx: &InterpCx<'tcx, Self>,
643 _provenance: Self::Provenance,
644 ) -> InterpResult<'tcx> {
645// This is only reachable with -Zunleash-the-miri-inside-of-you.
646do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("exposing pointers is not possible at compile-time"))
})))throw_unsup_format!("exposing pointers is not possible at compile-time")647 }
648649#[inline(always)]
650fn init_frame(
651 ecx: &mut InterpCx<'tcx, Self>,
652 frame: Frame<'tcx>,
653 ) -> InterpResult<'tcx, Frame<'tcx>> {
654// Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
655if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
656do yeet ::rustc_middle::mir::interpret::InterpErrorKind::ResourceExhaustion(::rustc_middle::mir::interpret::ResourceExhaustionInfo::StackFrameLimitReached)throw_exhaust!(StackFrameLimitReached)657 } else {
658interp_ok(frame)
659 }
660 }
661662#[inline(always)]
663fn stack<'a>(
664 ecx: &'a InterpCx<'tcx, Self>,
665 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
666&ecx.machine.stack
667 }
668669#[inline(always)]
670fn stack_mut<'a>(
671 ecx: &'a mut InterpCx<'tcx, Self>,
672 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
673&mut ecx.machine.stack
674 }
675676fn before_access_global(
677 _tcx: TyCtxtAt<'tcx>,
678 machine: &Self,
679 alloc_id: AllocId,
680 alloc: ConstAllocation<'tcx>,
681 _static_def_id: Option<DefId>,
682 is_write: bool,
683 ) -> InterpResult<'tcx> {
684let alloc = alloc.inner();
685if is_write {
686// Write access. These are never allowed, but we give a targeted error message.
687match alloc.mutability {
688 Mutability::Not => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(alloc_id))throw_ub!(WriteToReadOnly(alloc_id)),
689 Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
690 }
691 } else {
692// Read access. These are usually allowed, with some exceptions.
693if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
694// Machine configuration allows us read from anything (e.g., `static` initializer).
695interp_ok(())
696 } else if alloc.mutability == Mutability::Mut {
697// Machine configuration does not allow us to read statics (e.g., `const`
698 // initializer).
699Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
700 } else {
701// Immutable global, this read is fine.
702{
match (&alloc.mutability, &Mutability::Not) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(alloc.mutability, Mutability::Not);
703interp_ok(())
704 }
705 }
706 }
707708fn retag_ptr_value(
709 ecx: &mut InterpCx<'tcx, Self>,
710 val: &ImmTy<'tcx, CtfeProvenance>,
711 _ty: Ty<'tcx>,
712 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, CtfeProvenance>>> {
713if #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.retag_mode {
RetagMode::None | RetagMode::Raw => true,
_ => false,
}matches!(ecx.machine.retag_mode, RetagMode::None | RetagMode::Raw) {
714return interp_ok(None);
715 }
716// If it's a frozen shared reference that's not already immutable, potentially make it immutable.
717 // (Do nothing on `None` provenance, that cannot be used to perform mutation anyway.)
718 // Note that const-checking relies on the UB detection we are implementing here! Specifically,
719 // the analysis for which destructors may be invoked relies on `&impl Freeze` references not
720 // being able to change what gets dropped.
721if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
722 && *mutbl == Mutability::Not723 && val.to_scalar_and_meta().0.to_pointer(ecx).provenance.is_some_and(|p| !p.immutable())
724 {
725// That next check is expensive, that's why we have all the guards above.
726let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
727let place = ecx.imm_ptr_to_mplace(val)?;
728let new_place = if is_immutable {
729place.map_provenance(CtfeProvenance::as_immutable)
730 } else {
731// Even if it is not immutable, remember that it is a shared reference.
732 // This allows it to become part of the final value of the constant.
733 // (See <https://github.com/rust-lang/rust/pull/128543> for why we allow this
734 // even when there is interior mutability.)
735place.map_provenance(CtfeProvenance::as_shared_ref)
736 };
737interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout)))
738 } else {
739interp_ok(None)
740 }
741 }
742743fn with_retag_mode<T>(
744 ecx: &mut InterpCx<'tcx, Self>,
745 mode: RetagMode,
746 f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
747 ) -> InterpResult<'tcx, T> {
748let old_mode = mem::replace(&mut ecx.machine.retag_mode, mode);
749let ret = f(ecx);
750ecx.machine.retag_mode = old_mode;
751ret752 }
753754fn before_memory_write(
755 _tcx: TyCtxtAt<'tcx>,
756 _machine: &mut Self,
757 _alloc_extra: &mut Self::AllocExtra,
758 _ptr: Pointer<Option<Self::Provenance>>,
759 (_alloc_id, immutable): (AllocId, bool),
760 range: AllocRange,
761 ) -> InterpResult<'tcx> {
762if range.size == Size::ZERO {
763// Nothing to check.
764return interp_ok(());
765 }
766// Reject writes through immutable pointers.
767if immutable {
768return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
769 }
770// Everything else is fine.
771interp_ok(())
772 }
773774fn before_alloc_access(
775 tcx: TyCtxtAt<'tcx>,
776 machine: &Self,
777 alloc_id: AllocId,
778 ) -> InterpResult<'tcx> {
779if machine.stack.is_empty() {
780// Get out of the way for the final copy.
781return interp_ok(());
782 }
783// Check if this is the currently evaluated static.
784if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
785return Err(ConstEvalErrKind::RecursiveStatic).into();
786 }
787// If this is another static, make sure we fire off the query to detect cycles.
788 // But only do that when checks for static recursion are enabled.
789if machine.static_root_ids.is_some() {
790if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
791if tcx.is_foreign_item(def_id) {
792do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
793 }
794 tcx.eval_static_initializer(def_id)?;
795 }
796 }
797interp_ok(())
798 }
799800fn cached_union_data_range<'e>(
801 ecx: &'e mut InterpCx<'tcx, Self>,
802 ty: Ty<'tcx>,
803 compute_range: impl FnOnce() -> RangeSet,
804 ) -> Cow<'e, RangeSet> {
805if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
806 Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
807 } else {
808// Don't bother caching, we're only doing one validation at the end anyway.
809Cow::Owned(compute_range())
810 }
811 }
812813fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
814 }
815}
816817// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
818// so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
819// at the bottom of this file.