1use std::borrow::{Borrow, Cow};
2use std::hash::Hash;
3use std::{fmt, mem};
4
5use rustc_abi::{Align, FIRST_VARIANT, FieldIdx, Size, VariantIdx};
6use rustc_ast::Mutability;
7use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
8use rustc_hir::attrs::lang_items::LangItem;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_hir::{self as hir, CRATE_HIR_ID, find_attr};
11use rustc_lint_defs::builtin::LONG_RUNNING_CONST_EVAL;
12use rustc_middle::mir;
13use rustc_middle::mir::AssertMessage;
14use rustc_middle::mir::interpret::ReportedErrorInfo;
15use rustc_middle::query::TyCtxtAt;
16use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout, ValidityRequirement};
17use rustc_middle::ty::{self, FieldInfo, ScalarInt, Ty, TyCtxt};
18use rustc_span::{Span, Symbol, bug, span_bug, sym};
19use rustc_target::callconv::FnAbi;
20use tracing::debug;
21
22use super::error::*;
23use crate::diagnostics::{LongRunning, LongRunningWarn};
24use crate::interpret::{
25 self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
26 GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet,
27 RetagMode, Scalar, compile_time_machine, ensure_monomorphic_enough, err_inval, interp_ok,
28 throw_exhaust, throw_inval, throw_ub, throw_ub_format, throw_unsup, throw_unsup_format,
29 type_implements_dyn_trait,
30};
31
32const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
36const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
39const PROGRESS_INDICATOR_START: usize = 4_000_000;
42
43pub struct CompileTimeMachine<'tcx> {
48 pub(super) num_evaluated_steps: usize,
53
54 pub(super) stack: Vec<Frame<'tcx>>,
56
57 pub(super) can_access_mut_global: CanAccessMutGlobal,
61
62 pub(super) check_alignment: CheckAlignment,
64
65 pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
69
70 union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
72
73 retag_mode: RetagMode,
75}
76
77#[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]
fn clone(&self) -> CheckAlignment { *self }
}Clone)]
78pub enum CheckAlignment {
79 No,
82 Error,
84}
85
86#[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]
fn clone(&self) -> CanAccessMutGlobal { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CanAccessMutGlobal { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CanAccessMutGlobal {
#[inline]
fn eq(&self, other: &CanAccessMutGlobal) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
87pub(crate) enum CanAccessMutGlobal {
88 No,
89 Yes,
90}
91
92impl From<bool> for CanAccessMutGlobal {
93 fn from(value: bool) -> Self {
94 if value { Self::Yes } else { Self::No }
95 }
96}
97
98impl<'tcx> CompileTimeMachine<'tcx> {
99 pub(crate) fn new(
100 can_access_mut_global: CanAccessMutGlobal,
101 check_alignment: CheckAlignment,
102 ) -> Self {
103 CompileTimeMachine {
104 num_evaluated_steps: 0,
105 stack: Vec::new(),
106 can_access_mut_global,
107 check_alignment,
108 static_root_ids: None,
109 union_data_ranges: FxHashMap::default(),
110 retag_mode: RetagMode::Default,
111 }
112 }
113}
114
115impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
116 #[inline(always)]
117 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
118 where
119 K: Borrow<Q>,
120 {
121 FxIndexMap::contains_key(self, k)
122 }
123
124 #[inline(always)]
125 fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
126 where
127 K: Borrow<Q>,
128 {
129 FxIndexMap::contains_key(self, k)
130 }
131
132 #[inline(always)]
133 fn insert(&mut self, k: K, v: V) -> Option<V> {
134 FxIndexMap::insert(self, k, v)
135 }
136
137 #[inline(always)]
138 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
139 where
140 K: Borrow<Q>,
141 {
142 FxIndexMap::swap_remove(self, k)
144 }
145
146 #[inline(always)]
147 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
148 self.iter().filter_map(move |(k, v)| f(k, v)).collect()
149 }
150
151 #[inline(always)]
152 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
153 match self.get(&k) {
154 Some(v) => Ok(v),
155 None => {
156 vacant()?;
157 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 }
161
162 #[inline(always)]
163 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
164 match self.entry(k) {
165 IndexEntry::Occupied(e) => Ok(e.into_mut()),
166 IndexEntry::Vacant(e) => {
167 let v = vacant()?;
168 Ok(e.insert(v))
169 }
170 }
171 }
172}
173
174pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
175
176#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MemoryKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MemoryKind::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: &MemoryKind) -> bool {
match (self, other) {
(MemoryKind::Heap { was_made_global: __self_0 },
MemoryKind::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]
fn clone(&self) -> MemoryKind {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone)]
177pub enum MemoryKind {
178 Heap {
179 was_made_global: bool,
182 },
183}
184
185impl fmt::Display for MemoryKind {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 match self {
188 MemoryKind::Heap { was_made_global } => {
189 f.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}
194
195impl interpret::MayLeak for MemoryKind {
196 #[inline(always)]
197 fn may_leak(self) -> bool {
198 match self {
199 MemoryKind::Heap { was_made_global } => was_made_global,
200 }
201 }
202}
203
204impl interpret::MayLeak for ! {
205 #[inline(always)]
206 fn may_leak(self) -> bool {
207 self
209 }
210}
211
212impl<'tcx> CompileTimeInterpCx<'tcx> {
213 fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
214 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
215 let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
216
217 use rustc_span::RemapPathScopeComponents;
218 (
219 Symbol::intern(
220 &caller.file.name.display(RemapPathScopeComponents::DIAGNOSTICS).to_string_lossy(),
221 ),
222 u32::try_from(caller.line).unwrap(),
223 u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
224 )
225 }
226
227 fn 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>>> {
239 let def_id = instance.def_id();
240
241 if self.tcx.is_lang_item(def_id, LangItem::PanicDisplay)
242 || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
243 {
244 let args = Self::copy_fn_args(args);
245 if !(args.len() == 1) {
::core::panicking::panic("assertion failed: args.len() == 1")
};assert!(args.len() == 1);
247
248 let mut msg_place = self.deref_pointer(&args[0])?;
249 while msg_place.layout.ty.is_ref() {
250 msg_place = self.deref_pointer(&msg_place)?;
251 }
252
253 let msg = Symbol::intern(self.read_str(&msg_place)?);
254 let span = self.find_closest_untracked_caller_location();
255 let (file, line, col) = self.location_triple_for_span(span);
256 return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
257 } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
258 let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
260 let new_instance = ty::Instance::expect_resolve(
261 *self.tcx,
262 self.typing_env(),
263 const_def_id,
264 instance.args,
265 self.cur_span(),
266 );
267
268 return interp_ok(Some(new_instance));
269 }
270 interp_ok(Some(instance))
271 }
272
273 fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
281 interp_ok(match (a, b) {
282 (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
284 (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
287 let int = int.to_target_usize(*self.tcx);
288 let offset_ptr = ptr.wrapping_offset(Size::from_bytes(int.wrapping_neg()), self);
291 if !self.scalar_may_be_null(Scalar::from_pointer(offset_ptr, self))? {
292 0
294 } else {
295 2
298 }
299 }
300 (Scalar::Ptr(a, _), Scalar::Ptr(b, _)) => {
301 let (a_prov, a_offset) = a.prov_and_relative_offset();
302 let (b_prov, b_offset) = b.prov_and_relative_offset();
303 let a_allocid = a_prov.alloc_id();
304 let b_allocid = b_prov.alloc_id();
305 let a_info = self.get_alloc_info(a_allocid);
306 let b_info = self.get_alloc_info(b_allocid);
307
308 if a_info.align > Align::ONE && b_info.align > Align::ONE {
310 let min_align = Ord::min(a_info.align.bytes(), b_info.align.bytes());
311 let a_residue = a_offset.bytes() % min_align;
312 let b_residue = b_offset.bytes() % min_align;
313 if a_residue != b_residue {
314 return interp_ok(0);
317 }
318 }
321
322 if let (Some(GlobalAlloc::Static(a_did)), Some(GlobalAlloc::Static(b_did))) = (
323 self.tcx.try_get_global_alloc(a_allocid),
324 self.tcx.try_get_global_alloc(b_allocid),
325 ) {
326 if a_allocid == b_allocid {
327 if 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 (a_offset == b_offset) as u8
336 } else {
337 if 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 if a_offset < a_info.size && b_offset < b_info.size {
352 0
353 } else {
354 2
360 }
361 }
362 } else {
363 2
386 }
387 }
388 })
389 }
390}
391
392impl<'tcx> CompileTimeMachine<'tcx> {
393 #[inline(always)]
394 pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> hir::HirId {
397 self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
398 }
399}
400
401impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
402 type 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>);
403
404 const PANIC_ON_ALLOC_FAIL: bool = false; #[inline(always)]
407 fn 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 }
410
411 #[inline(always)]
412 fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
413 ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
414 }
415
416 fn load_mir(
417 ecx: &InterpCx<'tcx, Self>,
418 instance: ty::InstanceKind<'tcx>,
419 ) -> &'tcx mir::Body<'tcx> {
420 match instance {
421 ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
422 _ => ecx.tcx.instance_mir(instance),
423 }
424 }
425
426 fn 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, ) -> 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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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);
436
437 let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
439 return interp_ok(None);
441 };
442
443 if let ty::InstanceKind::Item(def) = instance.def {
445 if !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::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(ecx.tcx, def, RustcDoNotConstCheck) {
450 do 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)
453 }
454 }
455
456 interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
460 }
461
462 fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
463 let msg = Symbol::intern(msg);
464 let span = ecx.find_closest_untracked_caller_location();
465 let (file, line, col) = ecx.location_triple_for_span(span);
466 Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
467 }
468
469 fn call_intrinsic(
470 ecx: &mut InterpCx<'tcx, Self>,
471 instance: ty::Instance<'tcx>,
472 args: &[OpTy<'tcx>],
473 dest: &PlaceTy<'tcx, Self::Provenance>,
474 target: Option<mir::BasicBlock>,
475 _unwind: mir::UnwindAction,
476 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
477 if ecx.eval_intrinsic(instance, args, dest, target)? {
479 return interp_ok(None);
480 }
481 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
482
483 match intrinsic_name {
485 sym::ptr_guaranteed_cmp => {
486 let a = ecx.read_scalar(&args[0])?;
487 let b = ecx.read_scalar(&args[1])?;
488 let cmp = ecx.guaranteed_cmp(a, b)?;
489 ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
490 }
491 sym::const_allocate => {
492 let size = ecx.read_scalar(&args[0])?.to_target_usize(ecx)?;
493 let align = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
494
495 let align = match Align::from_bytes(align) {
496 Ok(a) => a,
497 Err(err) => {
498 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid align passed to `const_allocate`: {0}",
err))
})))throw_ub_format!("invalid align passed to `const_allocate`: {err}")
499 }
500 };
501
502 let ptr = ecx.allocate_ptr(
503 Size::from_bytes(size),
504 align,
505 interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
506 AllocInit::Uninit,
507 )?;
508 ecx.write_pointer(ptr, dest)?;
509 }
510 sym::const_deallocate => {
511 let ptr = ecx.read_pointer(&args[0])?;
512 let size = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
513 let align = ecx.read_scalar(&args[2])?.to_target_usize(ecx)?;
514
515 let size = Size::from_bytes(size);
516 let align = match Align::from_bytes(align) {
517 Ok(a) => a,
518 Err(err) => {
519 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid align passed to `const_deallocate`: {0}",
err))
})))throw_ub_format!("invalid align passed to `const_deallocate`: {err}")
520 }
521 };
522
523 let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?;
526 let is_allocated_in_another_const = #[allow(non_exhaustive_omitted_patterns)] match ecx.tcx.try_get_global_alloc(alloc_id)
{
Some(interpret::GlobalAlloc::Memory(_)) => true,
_ => false,
}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(|_| ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)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() => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to instantiate uninhabited type `{0}`",
ty))
})format!(
571 "aborted execution: attempted to instantiate uninhabited type `{ty}`"
572 ),
573 ValidityRequirement::Inhabited => bug_impl(None, format_args!("handled earlier"), Location::caller())bug!("handled earlier"),
574 ValidityRequirement::Zero => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to zero-initialize type `{0}`, which is invalid",
ty))
})format!(
575 "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
576 ),
577 ValidityRequirement::UninitMitigated0x01Fill => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to leave type `{0}` uninitialized, which is invalid",
ty))
})format!(
578 "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
579 ),
580 ValidityRequirement::Uninit => bug_impl(None, format_args!("assert_uninit_valid doesn\'t exist"),
Location::caller())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_id_vtable => {
590 let tp_ty = ecx.read_type_id(&args[0])?;
591 let result_ty = ecx.read_type_id(&args[1])?;
592
593 let (implements_trait, preds) = type_implements_dyn_trait(ecx, tp_ty, result_ty)?;
594
595 if implements_trait {
596 let vtable_ptr = ecx.get_vtable_ptr(tp_ty, preds)?;
597 ecx.write_pointer(vtable_ptr, dest)?;
599 } else {
600 ecx.write_discriminant(FIRST_VARIANT, dest)?;
602 }
603 }
604
605 sym::type_of => {
606 let ty = ecx.read_type_id(&args[0])?;
607 ecx.write_type_info(ty, dest)?;
608 }
609
610 sym::type_id_is_signed => {
611 let ty = ecx.read_type_id(&args[0])?;
612 ecx.write_scalar(Scalar::from_bool(ty.is_signed()), dest)?;
613 }
614
615 sym::type_id_points_mutably => {
616 let ty = ecx.read_type_id(&args[0])?;
617 let is_mutable = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut) => true,
_ => false,
}matches!(
618 ty.kind(),
619 ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut)
620 );
621 ecx.write_scalar(Scalar::from_bool(is_mutable), dest)?;
622 }
623
624 sym::size_of_type_id => {
625 let ty = ecx.read_type_id(&args[0])?;
626 let layout = ecx.layout_of(ty)?;
627 let variant_index = if layout.is_sized() {
628 let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
629 let size_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
630 ecx.write_scalar(
631 ScalarInt::try_from_target_usize(layout.size.bytes(), ecx.tcx.tcx).unwrap(),
632 &size_field_place,
633 )?;
634 variant
635 } else {
636 ecx.project_downcast_named(dest, sym::None)?.0
637 };
638 ecx.write_discriminant(variant_index, dest)?;
639 }
640
641 sym::type_id_element_ty => {
642 let ty = ecx.read_type_id(&args[0])?;
643 let variant_index = if let ty::Array(ty, _) | ty::Slice(ty) = ty.kind() {
644 let (variant_idx, variant_place) =
645 ecx.project_downcast_named(dest, sym::Some)?;
646 let type_id_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
647 ecx.write_type_id(*ty, &type_id_field_place)?;
648 variant_idx
649 } else {
650 ecx.project_downcast_named(dest, sym::None)?.0
651 };
652 ecx.write_discriminant(variant_index, dest)?;
653 }
654
655 sym::type_id_array_len => {
656 let ty = ecx.read_type_id(&args[0])?;
657 let len = if let ty::Array(_, len) = ty.kind() {
658 len.to_leaf().to_target_usize(ecx.tcx.tcx())
659 } else {
660 0
661 };
662 ecx.write_scalar(Scalar::from_target_usize(len, ecx), dest)?;
663 }
664
665 sym::type_id_fields => {
666 let ty = ecx.read_type_id(&args[0])?;
667 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
668
669 let variants_num =
670 ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1);
671 if variant_idx >= variants_num {
672 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: variants_num as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
673 len: variants_num as u64,
674 index: variant_idx as u64
675 });
676 }
677
678 let fields_num = match ty.kind() {
679 ty::Adt(adt_def, _) => {
680 let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)];
681 variant_def.fields.len()
682 }
683 ty::Tuple(fields) => fields.len(),
684 _ => 0, };
686
687 ecx.write_scalar(Scalar::from_target_usize(fields_num as u64, ecx), dest)?;
688 }
689
690 sym::type_id_field_representing_type => {
691 let ty = ecx.read_type_id(&args[0])?;
692 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
693 let field_idx = ecx.read_target_usize(&args[2])? as usize;
694
695 let variants_num =
696 ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1);
697 if variant_idx >= variants_num {
698 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: variants_num as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
699 len: variants_num as u64,
700 index: variant_idx as u64
701 });
702 }
703
704 let fields_num = match ty.kind() {
705 ty::Adt(adt_def, _) => {
706 let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)];
707 variant_def.fields.len()
708 }
709 ty::Tuple(fields) => fields.len(),
710 _ => 0, };
712 if field_idx >= fields_num {
713 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: fields_num as u64,
index: field_idx as u64,
});throw_ub!(BoundsCheckFailed {
714 len: fields_num as u64,
715 index: field_idx as u64
716 });
717 }
718
719 let frt = Ty::new_field_representing_type(
720 *ecx.tcx,
721 ty,
722 VariantIdx::from_usize(variant_idx),
723 FieldIdx::from_usize(field_idx),
724 );
725 ecx.write_type_id(frt, dest)?;
726 }
727 sym::type_id_function_ptr => {
728 let ty = ecx.read_type_id(&args[0])?;
729 let variant_index = if let ty::FnPtr(sig, fn_header) = ty.kind() {
730 let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
731 let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
732 let sig = sig.skip_binder(); ecx.write_fn_ptr_type_info(field_place, &sig, fn_header)?;
734 variant
735 } else {
736 ecx.project_downcast_named(dest, sym::None)?.0
737 };
738 ecx.write_discriminant(variant_index, dest)?;
739 }
740 sym::type_id_points_to => {
741 let ty = ecx.read_type_id(&args[0])?;
742 let variant_index = if let ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) =
743 ty.kind()
744 {
745 let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
746 let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
747 ecx.write_type_id(*pointee_ty, &field_place)?;
748 variant
749 } else {
750 ecx.project_downcast_named(dest, sym::None)?.0
751 };
752 ecx.write_discriminant(variant_index, dest)?;
753 }
754
755 sym::type_id_variants => {
756 let ty = ecx.read_type_id(&args[0])?;
757 let variants_num = ty.ty_adt_def().map(|def| def.variants().len()).unwrap_or(1);
758 ecx.write_scalar(Scalar::from_target_usize(variants_num as u64, ecx), dest)?;
759 }
760
761 sym::variant_name => {
762 let base = ecx.read_type_id(&args[0])?;
763
764 let field_name = if let ty::Adt(def, _) = base.kind() {
765 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
766 if variant_idx >= def.variants().len() {
767 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: def.variants().len() as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
768 len: def.variants().len() as u64,
769 index: variant_idx as u64
770 });
771 }
772 let variant_idx = VariantIdx::from_usize(variant_idx);
773 def.variant(variant_idx).name
774 } else {
775 bug_impl(Some(ecx.cur_span()),
format_args!("expected enum type, got {0}", base), Location::caller())span_bug!(ecx.cur_span(), "expected enum type, got {base}")
776 };
777 let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?;
778 ecx.write_immediate(
779 Immediate::ScalarPair(
780 Scalar::from_pointer(ptr, ecx),
781 Scalar::from_target_usize(field_name.as_str().len() as u64, ecx),
782 ),
783 dest,
784 )?;
785 }
786
787 sym::variant_non_exhaustive => {
788 let base = ecx.read_type_id(&args[0])?;
789
790 let non_exhaustive = if let ty::Adt(def, _) = base.kind() {
791 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
792 if variant_idx >= def.variants().len() {
793 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: def.variants().len() as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
794 len: def.variants().len() as u64,
795 index: variant_idx as u64
796 });
797 }
798 let variant_idx = VariantIdx::from_usize(variant_idx);
799 def.variant(variant_idx).is_field_list_non_exhaustive()
800 } else {
801 bug_impl(Some(ecx.cur_span()),
format_args!("expected enum type, got {0}", base), Location::caller())span_bug!(ecx.cur_span(), "expected enum type, got {base}")
802 };
803 ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?;
804 }
805
806 sym::field_offset => {
807 let frt_ty = instance.args.type_at(0);
808 ensure_monomorphic_enough(frt_ty)?;
809
810 let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
811 && let Some(FieldInfo { base, variant_idx, field_idx, .. }) =
812 def.field_representing_type_info(ecx.tcx.tcx, args)
813 {
814 (base, variant_idx, field_idx)
815 } else {
816 bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
817 };
818 let layout = ecx.layout_of(ty)?;
819 let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env());
820
821 let layout = layout.for_variant(&cx, variant);
822 let offset = layout.fields.offset(field.index()).bytes();
823
824 ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
825 }
826
827 sym::field_representing_type_name => {
828 let frt_ty = ecx.read_type_id(&args[0])?;
829
830 let field_name = if let ty::Adt(def, args) = frt_ty.kind()
831 && let Some(FieldInfo { name, .. }) =
832 def.field_representing_type_info(ecx.tcx.tcx, args)
833 {
834 name
835 } else {
836 bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
837 };
838 let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?;
839 ecx.write_immediate(
840 Immediate::ScalarPair(
841 Scalar::from_pointer(ptr, ecx),
842 Scalar::from_target_usize(field_name.as_str().len() as u64, ecx),
843 ),
844 dest,
845 )?;
846 }
847
848 sym::field_representing_type_offset => {
849 let frt_ty = ecx.read_type_id(&args[0])?;
850
851 let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
852 && let Some(FieldInfo { base, variant_idx, field_idx, .. }) =
853 def.field_representing_type_info(ecx.tcx.tcx, args)
854 {
855 (base, variant_idx, field_idx)
856 } else {
857 bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
858 };
859 let layout = ecx.layout_of(ty)?;
860 let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env());
861
862 let layout = layout.for_variant(&cx, variant);
863 let offset = layout.fields.offset(field.index()).bytes();
864
865 ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
866 }
867
868 sym::field_representing_type_actual_type_id => {
869 let frt_ty = ecx.read_type_id(&args[0])?;
870
871 let field_ty = if let ty::Adt(def, args) = frt_ty.kind()
872 && let Some(FieldInfo { ty, .. }) =
873 def.field_representing_type_info(ecx.tcx.tcx, args)
874 {
875 ecx.tcx.erase_and_anonymize_regions(ty)
876 } else {
877 bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
878 };
879 ecx.write_type_id(field_ty, dest)?;
880 }
881
882 sym::type_id_generics => {
883 let ty = ecx.read_type_id(&args[0])?;
884 ecx.write_type_id_generics(dest, ty)?;
885 }
886
887 sym::non_exhaustive => {
888 let ty = ecx.read_type_id(&args[0])?;
889
890 let non_exhaustive = if let ty::Adt(def, _) = ty.kind() {
892 if def.is_enum() {
893 def.is_variant_list_non_exhaustive()
894 } else {
895 def.non_enum_variant().is_field_list_non_exhaustive()
896 }
897 } else {
898 false
899 };
900
901 ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?;
902 }
903
904 _ => {
905 if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
907 do 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!(
908 "intrinsic `{intrinsic_name}` is not supported at compile-time"
909 );
910 }
911 return interp_ok(Some(ty::Instance {
912 def: ty::InstanceKind::Item(instance.def_id()),
913 args: instance.args,
914 }));
915 }
916 }
917
918 ecx.return_to_block(target)?;
920 interp_ok(None)
921 }
922
923 fn call_llvm_intrinsic(
924 ecx: &mut InterpCx<'tcx, Self>,
925 instance: ty::Instance<'tcx>,
926 _args: &[OpTy<'tcx>],
927 _dest: &PlaceTy<'tcx, Self::Provenance>,
928 _target: Option<mir::BasicBlock>,
929 ) -> InterpResult<'tcx> {
930 let intrinsic_name = ecx.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap();
931
932 do 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");
933 }
934
935 fn assert_panic(
936 ecx: &mut InterpCx<'tcx, Self>,
937 msg: &AssertMessage<'tcx>,
938 _unwind: mir::UnwindAction,
939 ) -> InterpResult<'tcx> {
940 use rustc_middle::mir::AssertKind::*;
941 let eval_to_int =
943 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
944 let err = match msg {
945 BoundsCheck { len, index } => {
946 let len = eval_to_int(len)?;
947 let index = eval_to_int(index)?;
948 BoundsCheck { len, index }
949 }
950 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
951 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
952 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
953 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
954 ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
955 ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
956 ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
957 MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
958 required: eval_to_int(required)?,
959 found: eval_to_int(found)?,
960 },
961 NullPointerDereference => NullPointerDereference,
962 NullReferenceConstructed => NullReferenceConstructed,
963 InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
964 };
965 Err(ConstEvalErrKind::AssertFailure(err)).into()
966 }
967
968 #[inline(always)]
969 fn runtime_checks(
970 _ecx: &InterpCx<'tcx, Self>,
971 _r: mir::RuntimeChecks,
972 ) -> InterpResult<'tcx, bool> {
973 interp_ok(true)
976 }
977
978 fn binary_ptr_op(
979 _ecx: &InterpCx<'tcx, Self>,
980 _bin_op: mir::BinOp,
981 _left: &ImmTy<'tcx>,
982 _right: &ImmTy<'tcx>,
983 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
984 do 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");
985 }
986
987 fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
988 if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
991 let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
992 (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
993 } else {
994 (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
995 };
996
997 ecx.machine.num_evaluated_steps = new_steps;
998 if new_steps == limit {
1003 let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
1007 let is_error = ecx
1008 .tcx
1009 .lint_level_spec_at_node(LONG_RUNNING_CONST_EVAL, hir_id)
1010 .level()
1011 .is_error();
1012 let span = ecx.cur_span();
1013 ecx.tcx.emit_node_span_lint(
1014 LONG_RUNNING_CONST_EVAL,
1015 hir_id,
1016 span,
1017 LongRunning { item_span: ecx.tcx.span },
1018 );
1019 if is_error {
1021 let guard = ecx
1022 .tcx
1023 .dcx()
1024 .span_delayed_bug(span, "The deny lint should have already errored");
1025 do 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)));
1026 }
1027 } else if new_steps > start && new_steps.is_power_of_two() {
1028 let span = ecx.cur_span();
1032 let mut warn =
1033 ecx.tcx.dcx().create_warn(LongRunningWarn { span, item_span: ecx.tcx.span });
1034 warn.arg("force_duplicate", new_steps);
1038 warn.emit();
1039 }
1040 }
1041
1042 interp_ok(())
1043 }
1044
1045 #[inline(always)]
1046 fn expose_provenance(
1047 _ecx: &InterpCx<'tcx, Self>,
1048 _provenance: Self::Provenance,
1049 ) -> InterpResult<'tcx> {
1050 do 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")
1052 }
1053
1054 #[inline(always)]
1055 fn init_frame(
1056 ecx: &mut InterpCx<'tcx, Self>,
1057 frame: Frame<'tcx>,
1058 ) -> InterpResult<'tcx, Frame<'tcx>> {
1059 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
1061 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::ResourceExhaustion(::rustc_middle::mir::interpret::ResourceExhaustionInfo::StackFrameLimitReached)throw_exhaust!(StackFrameLimitReached)
1062 } else {
1063 interp_ok(frame)
1064 }
1065 }
1066
1067 #[inline(always)]
1068 fn stack<'a>(
1069 ecx: &'a InterpCx<'tcx, Self>,
1070 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
1071 &ecx.machine.stack
1072 }
1073
1074 #[inline(always)]
1075 fn stack_mut<'a>(
1076 ecx: &'a mut InterpCx<'tcx, Self>,
1077 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
1078 &mut ecx.machine.stack
1079 }
1080
1081 fn before_access_global(
1082 _tcx: TyCtxtAt<'tcx>,
1083 machine: &Self,
1084 alloc_id: AllocId,
1085 alloc: ConstAllocation<'tcx>,
1086 _static_def_id: Option<DefId>,
1087 is_write: bool,
1088 ) -> InterpResult<'tcx> {
1089 let alloc = alloc.inner();
1090 if is_write {
1091 match alloc.mutability {
1093 Mutability::Not => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(alloc_id))throw_ub!(WriteToReadOnly(alloc_id)),
1094 Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
1095 }
1096 } else {
1097 if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
1099 interp_ok(())
1101 } else if alloc.mutability == Mutability::Mut {
1102 Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
1105 } else {
1106 {
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);
1108 interp_ok(())
1109 }
1110 }
1111 }
1112
1113 fn retag_ptr_value(
1114 ecx: &mut InterpCx<'tcx, Self>,
1115 val: &ImmTy<'tcx, CtfeProvenance>,
1116 _ty: Ty<'tcx>,
1117 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, CtfeProvenance>>> {
1118 if #[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) {
1119 return interp_ok(None);
1120 }
1121 if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
1124 && *mutbl == Mutability::Not
1125 && val.to_scalar_and_meta().0.to_pointer(ecx).provenance.is_some_and(|p| !p.immutable())
1126 {
1127 let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
1129 let place = ecx.imm_ptr_to_mplace(val)?;
1130 let new_place = if is_immutable {
1131 place.map_provenance(CtfeProvenance::as_immutable)
1132 } else {
1133 place.map_provenance(CtfeProvenance::as_shared_ref)
1138 };
1139 interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout)))
1140 } else {
1141 interp_ok(None)
1142 }
1143 }
1144
1145 fn with_retag_mode<T>(
1146 ecx: &mut InterpCx<'tcx, Self>,
1147 mode: RetagMode,
1148 f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
1149 ) -> InterpResult<'tcx, T> {
1150 let old_mode = mem::replace(&mut ecx.machine.retag_mode, mode);
1151 let ret = f(ecx);
1152 ecx.machine.retag_mode = old_mode;
1153 ret
1154 }
1155
1156 fn before_memory_write(
1157 _tcx: TyCtxtAt<'tcx>,
1158 _machine: &mut Self,
1159 _alloc_extra: &mut Self::AllocExtra,
1160 _ptr: Pointer<Option<Self::Provenance>>,
1161 (_alloc_id, immutable): (AllocId, bool),
1162 range: AllocRange,
1163 ) -> InterpResult<'tcx> {
1164 if range.size == Size::ZERO {
1165 return interp_ok(());
1167 }
1168 if immutable {
1170 return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
1171 }
1172 interp_ok(())
1174 }
1175
1176 fn before_alloc_access(
1177 tcx: TyCtxtAt<'tcx>,
1178 machine: &Self,
1179 alloc_id: AllocId,
1180 ) -> InterpResult<'tcx> {
1181 if machine.stack.is_empty() {
1182 return interp_ok(());
1184 }
1185 if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
1187 return Err(ConstEvalErrKind::RecursiveStatic).into();
1188 }
1189 if machine.static_root_ids.is_some() {
1192 if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
1193 if tcx.is_foreign_item(def_id) {
1194 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
1195 }
1196 tcx.eval_static_initializer(def_id)?;
1197 }
1198 }
1199 interp_ok(())
1200 }
1201
1202 fn cached_union_data_range<'e>(
1203 ecx: &'e mut InterpCx<'tcx, Self>,
1204 ty: Ty<'tcx>,
1205 compute_range: impl FnOnce() -> RangeSet,
1206 ) -> Cow<'e, RangeSet> {
1207 if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
1208 Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
1209 } else {
1210 Cow::Owned(compute_range())
1212 }
1213 }
1214
1215 fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
1216 }
1217}
1218
1219