1use std::debug_assert_matches;
23use either::{Left, Right};
4use rustc_abi::{Align, HasDataLayout, Size, TargetDataLayout};
5use rustc_hir::def_id::DefId;
6use rustc_hir::limit::Limit;
7use rustc_middle::mir::interpret::{ErrorHandled, InvalidMetaKind, ReportedErrorInfo};
8use rustc_middle::query::TyCtxtAt;
9use rustc_middle::ty::layout::{
10self, FnAbiError, FnAbiOf, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOf,
11LayoutOfHelpers, TyAndLayout,
12};
13use rustc_middle::ty::{
14self, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingEnv, Variance,
15};
16use rustc_middle::{mir, span_bug};
17use rustc_span::Span;
18use rustc_target::callconv::FnAbi;
19use tracing::{debug, trace};
2021use super::{
22Frame, FrameInfo, GlobalId, InterpErrorInfo, InterpErrorKind, InterpResult, MPlaceTy, Machine,
23MemPlaceMeta, Memory, OpTy, Place, PlaceTy, PointerArithmetic, Projectable, Provenance,
24err_inval, interp_ok, throw_inval, throw_ub, throw_ub_format,
25};
26use crate::{enter_trace_span, util};
2728pub struct InterpCx<'tcx, M: Machine<'tcx>> {
29/// Stores the `Machine` instance.
30 ///
31 /// Note: the stack is provided by the machine.
32pub machine: M,
3334/// The results of the type checker, from rustc.
35 /// The span in this is the "root" of the evaluation, i.e., the const
36 /// we are evaluating (if this is CTFE).
37pub tcx: TyCtxtAt<'tcx>,
3839/// The current context in case we're evaluating in a
40 /// polymorphic context. This always uses `ty::TypingMode::PostAnalysis`.
41pub(super) typing_env: ty::TypingEnv<'tcx>,
4243/// The virtual memory system.
44pub memory: Memory<'tcx, M>,
4546/// The recursion limit (cached from `tcx.recursion_limit(())`)
47pub recursion_limit: Limit,
48}
4950impl<'tcx, M: Machine<'tcx>> HasDataLayoutfor InterpCx<'tcx, M> {
51#[inline]
52fn data_layout(&self) -> &TargetDataLayout {
53&self.tcx.data_layout
54 }
55}
5657impl<'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'tcx, M>
58where
59M: Machine<'tcx>,
60{
61#[inline]
62fn tcx(&self) -> TyCtxt<'tcx> {
63*self.tcx
64 }
65}
6667impl<'tcx, M> layout::HasTypingEnv<'tcx> for InterpCx<'tcx, M>
68where
69M: Machine<'tcx>,
70{
71fn typing_env(&self) -> ty::TypingEnv<'tcx> {
72self.typing_env
73 }
74}
7576impl<'tcx, M: Machine<'tcx>> LayoutOfHelpers<'tcx> for InterpCx<'tcx, M> {
77type LayoutOfResult = Result<TyAndLayout<'tcx>, InterpErrorKind<'tcx>>;
7879#[inline]
80fn layout_tcx_at_span(&self) -> Span {
81// Using the cheap root span for performance.
82self.tcx.span
83 }
8485#[inline]
86fn handle_layout_err(
87&self,
88mut err: LayoutError<'tcx>,
89_: Span,
90_: Ty<'tcx>,
91 ) -> InterpErrorKind<'tcx> {
92// FIXME(#149283): This is really hacky and is only used to hide type
93 // system bugs. We use it as a temporary fix for #149081.
94 //
95 // While it's expected that we sometimes get ambiguity errors when
96 // entering another generic environment while the current environment
97 // itself is still generic, we should never fail to entirely prove
98 // something.
99match err {
100 LayoutError::NormalizationFailure(ty, _) => {
101if ty.has_non_region_param() {
102err = LayoutError::TooGeneric(ty);
103 }
104 }
105106 LayoutError::Unknown(_)
107 | LayoutError::SizeOverflow(_)
108 | LayoutError::InvalidSimd { .. }
109 | LayoutError::TooGeneric(_)
110 | LayoutError::ReferencesError(_) => {}
111 }
112::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::Layout(err))err_inval!(Layout(err))113 }
114}
115116impl<'tcx, M: Machine<'tcx>> FnAbiOfHelpers<'tcx> for InterpCx<'tcx, M> {
117type FnAbiOfResult = Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, InterpErrorKind<'tcx>>;
118119fn handle_fn_abi_err(
120&self,
121 err: FnAbiError<'tcx>,
122 _span: Span,
123 _fn_abi_request: FnAbiRequest<'tcx>,
124 ) -> InterpErrorKind<'tcx> {
125match err {
126 FnAbiError::Layout(err) => ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::Layout(err))err_inval!(Layout(err)),
127 }
128 }
129}
130131impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
132/// This inherent method takes priority over the trait method with the same name in LayoutOf,
133 /// and allows wrapping the actual [LayoutOf::layout_of] with a tracing span.
134 /// See [LayoutOf::layout_of] for the original documentation.
135#[inline(always)]
136pub fn layout_of(&self, ty: Ty<'tcx>) -> Result<TyAndLayout<'tcx>, InterpErrorKind<'tcx>> {
137let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("layouting",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(137u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["layouting", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&"layout_of")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty.kind())
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, layouting::layout_of, ty = ?ty.kind());
138 LayoutOf::layout_of(self, ty)
139 }
140141/// This inherent method takes priority over the trait method with the same name in FnAbiOf,
142 /// and allows wrapping the actual [FnAbiOf::fn_abi_of_fn_ptr] with a tracing span.
143 /// See [FnAbiOf::fn_abi_of_fn_ptr] for the original documentation.
144#[inline(always)]
145pub fn fn_abi_of_fn_ptr(
146&self,
147 sig: ty::PolyFnSig<'tcx>,
148 extra_args: &'tcx ty::List<Ty<'tcx>>,
149 ) -> <Self as FnAbiOfHelpers<'tcx>>::FnAbiOfResult {
150let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("layouting",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(150u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["layouting", "sig",
"extra_args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&"fn_abi_of_fn_ptr")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&sig) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&extra_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, layouting::fn_abi_of_fn_ptr, ?sig, ?extra_args);
151 FnAbiOf::fn_abi_of_fn_ptr(self, sig, extra_args)
152 }
153154/// This inherent method takes priority over the trait method with the same name in FnAbiOf,
155 /// and allows wrapping the actual [FnAbiOf::fn_abi_of_instance_no_deduced_attrs] with a tracing span.
156 /// See [FnAbiOf::fn_abi_of_instance_no_deduced_attrs] for the original documentation.
157#[inline(always)]
158pub fn fn_abi_of_instance_no_deduced_attrs(
159&self,
160 instance: ty::Instance<'tcx>,
161 extra_args: &'tcx ty::List<Ty<'tcx>>,
162 ) -> <Self as FnAbiOfHelpers<'tcx>>::FnAbiOfResult {
163let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("layouting",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(163u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["layouting",
"instance", "extra_args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&"fn_abi_of_instance")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&instance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&extra_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, layouting::fn_abi_of_instance, ?instance, ?extra_args);
164 FnAbiOf::fn_abi_of_instance_no_deduced_attrs(self, instance, extra_args)
165 }
166}
167168/// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
169/// This test should be symmetric, as it is primarily about layout compatibility.
170pub(super) fn mir_assign_valid_types<'tcx>(
171 tcx: TyCtxt<'tcx>,
172 typing_env: TypingEnv<'tcx>,
173 src: TyAndLayout<'tcx>,
174 dest: TyAndLayout<'tcx>,
175) -> bool {
176// Type-changing assignments can happen when subtyping is used. While
177 // all normal lifetimes are erased, higher-ranked types with their
178 // late-bound lifetimes are still around and can lead to type
179 // differences.
180if util::relate_types(tcx, typing_env, Variance::Covariant, src.ty, dest.ty) {
181// Make sure the layout is equal, too -- just to be safe. Miri really
182 // needs layout equality. For performance reason we skip this check when
183 // the types are equal. Equal types *can* have different layouts when
184 // enum downcast is involved (as enum variants carry the type of the
185 // enum), but those should never occur in assignments.
186if truecfg!(debug_assertions) || src.ty != dest.ty {
187match (&src.layout, &dest.layout) {
(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!(src.layout, dest.layout);
188 }
189true
190} else {
191false
192}
193}
194195/// Use the already known layout if given (but sanity check in debug mode),
196/// or compute the layout.
197#[cfg_attr(not(debug_assertions), inline(always))]
198pub(super) fn from_known_layout<'tcx>(
199 tcx: TyCtxtAt<'tcx>,
200 typing_env: TypingEnv<'tcx>,
201 known_layout: Option<TyAndLayout<'tcx>>,
202 compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
203) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
204match known_layout {
205None => compute(),
206Some(known_layout) => {
207if truecfg!(debug_assertions) {
208let check_layout = compute()?;
209if !mir_assign_valid_types(tcx.tcx, typing_env, check_layout, known_layout) {
210::rustc_middle::util::bug::span_bug_fmt(tcx.span,
format_args!("expected type differs from actual type.\nexpected: {0}\nactual: {1}",
known_layout.ty, check_layout.ty));span_bug!(
211tcx.span,
212"expected type differs from actual type.\nexpected: {}\nactual: {}",
213 known_layout.ty,
214 check_layout.ty,
215 );
216 }
217 }
218interp_ok(known_layout)
219 }
220 }
221}
222223/// Turn the given error into a human-readable string. Expects the string to be printed, so if
224/// `RUSTC_CTFE_BACKTRACE` is set this will show a backtrace of the rustc internals that
225/// triggered the error.
226///
227/// This is NOT the preferred way to render an error; use `report` from `const_eval` instead.
228/// However, this is useful when error messages appear in ICEs.
229pub fn format_interp_error<'tcx>(e: InterpErrorInfo<'tcx>) -> String {
230let (e, backtrace) = e.into_parts();
231backtrace.print_backtrace();
232e.to_string()
233}
234235impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
236pub fn new(
237 tcx: TyCtxt<'tcx>,
238 root_span: Span,
239 typing_env: ty::TypingEnv<'tcx>,
240 machine: M,
241 ) -> Self {
242// Const eval always happens in post analysis mode in order to be able to use the hidden types of
243 // opaque types. This is needed for trivial things like `size_of`, but also for using associated
244 // types that are not specified in the opaque type. We also use MIR bodies whose opaque types have
245 // already been revealed, so we'd be able to at least partially observe the hidden types anyways.
246if true {
match typing_env.typing_mode {
ty::TypingMode::PostAnalysis => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"ty::TypingMode::PostAnalysis", ::core::option::Option::None);
}
};
};debug_assert_matches!(typing_env.typing_mode, ty::TypingMode::PostAnalysis);
247InterpCx {
248machine,
249 tcx: tcx.at(root_span),
250typing_env,
251 memory: Memory::new(),
252 recursion_limit: tcx.recursion_limit(),
253 }
254 }
255256/// Returns the span of the currently executed statement/terminator.
257 /// This is the span typically used for error reporting.
258#[inline(always)]
259pub fn cur_span(&self) -> Span {
260// This deliberately does *not* honor `requires_caller_location` since it is used for much
261 // more than just panics.
262self.stack().last().map_or(self.tcx.span, |f| f.current_span())
263 }
264265pub(crate) fn stack(&self) -> &[Frame<'tcx, M::Provenance, M::FrameExtra>] {
266 M::stack(self)
267 }
268269#[inline(always)]
270pub(crate) fn stack_mut(&mut self) -> &mut Vec<Frame<'tcx, M::Provenance, M::FrameExtra>> {
271 M::stack_mut(self)
272 }
273274#[inline(always)]
275pub fn frame_idx(&self) -> usize {
276let stack = self.stack();
277if !!stack.is_empty() {
::core::panicking::panic("assertion failed: !stack.is_empty()")
};assert!(!stack.is_empty());
278stack.len() - 1
279}
280281#[inline(always)]
282pub fn frame(&self) -> &Frame<'tcx, M::Provenance, M::FrameExtra> {
283self.stack().last().expect("no call frames exist")
284 }
285286#[inline(always)]
287pub fn frame_mut(&mut self) -> &mut Frame<'tcx, M::Provenance, M::FrameExtra> {
288self.stack_mut().last_mut().expect("no call frames exist")
289 }
290291#[inline(always)]
292pub fn body(&self) -> &'tcx mir::Body<'tcx> {
293self.frame().body
294 }
295296#[inline]
297pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
298ty.is_freeze(*self.tcx, self.typing_env)
299 }
300301pub fn load_mir(
302&self,
303 instance: ty::InstanceKind<'tcx>,
304 promoted: Option<mir::Promoted>,
305 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
306{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/eval_context.rs:306",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(306u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("load mir(instance={0:?}, promoted={1:?})",
instance, promoted) as &dyn Value))])
});
} else { ; }
};trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
307let body = if let Some(promoted) = promoted {
308let def = instance.def_id();
309&self.tcx.promoted_mir(def)[promoted]
310 } else {
311 M::load_mir(self, instance)
312 };
313// do not continue if typeck errors occurred (can only occur in local crate)
314if let Some(err) = body.tainted_by_errors {
315do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::non_const_eval_error(err)));throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(err)));
316 }
317interp_ok(body)
318 }
319320/// Call this on things you got out of the MIR (so it is as generic as the current
321 /// stack frame), to bring it into the proper environment for this interpreter.
322pub fn instantiate_from_current_frame_and_normalize_erasing_regions<
323 T: TypeFoldable<TyCtxt<'tcx>>,
324 >(
325&self,
326 value: T,
327 ) -> Result<T, ErrorHandled> {
328self.instantiate_from_frame_and_normalize_erasing_regions(self.frame(), value)
329 }
330331/// Call this on things you got out of the MIR (so it is as generic as the provided
332 /// stack frame), to bring it into the proper environment for this interpreter.
333pub fn instantiate_from_frame_and_normalize_erasing_regions<T: TypeFoldable<TyCtxt<'tcx>>>(
334&self,
335 frame: &Frame<'tcx, M::Provenance, M::FrameExtra>,
336 value: T,
337 ) -> Result<T, ErrorHandled> {
338let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("instantiate_from_frame_and_normalize_erasing_regions",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(338u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["frame.instance"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&frame.instance)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(
339 M,
340"instantiate_from_frame_and_normalize_erasing_regions",
341 %frame.instance
342 );
343frame344 .instance
345 .try_instantiate_mir_and_normalize_erasing_regions(
346*self.tcx,
347self.typing_env,
348 ty::EarlyBinder::bind(value),
349 )
350 .map_err(|_| ErrorHandled::TooGeneric(self.cur_span()))
351 }
352353/// The `args` are assumed to already be in our interpreter "universe".
354pub(super) fn resolve(
355&self,
356 def: DefId,
357 args: GenericArgsRef<'tcx>,
358 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
359let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("resolve",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(359u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["resolve", "def"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&"try_resolve")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&def) as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, resolve::try_resolve, def = ?def);
360{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/eval_context.rs:360",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(360u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve: {0:?}, {1:#?}",
def, args) as &dyn Value))])
});
} else { ; }
};trace!("resolve: {:?}, {:#?}", def, args);
361{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/eval_context.rs:361",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(361u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("typing_env: {0:#?}",
self.typing_env) as &dyn Value))])
});
} else { ; }
};trace!("typing_env: {:#?}", self.typing_env);
362{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/eval_context.rs:362",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(362u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("args: {0:#?}",
args) as &dyn Value))])
});
} else { ; }
};trace!("args: {:#?}", args);
363match ty::Instance::try_resolve(*self.tcx, self.typing_env, def, args) {
364Ok(Some(instance)) => interp_ok(instance),
365Ok(None) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)throw_inval!(TooGeneric),
366367// FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
368Err(error_guaranteed) => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::non_const_eval_error(error_guaranteed)))throw_inval!(AlreadyReported(
369 ReportedErrorInfo::non_const_eval_error(error_guaranteed)
370 )),
371 }
372 }
373374/// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a
375 /// frame which is not `#[track_caller]`. This matches the `caller_location` intrinsic,
376 /// and is primarily intended for the panic machinery.
377pub(crate) fn find_closest_untracked_caller_location(&self) -> Span {
378for frame in self.stack().iter().rev() {
379{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/eval_context.rs:379",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(379u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("find_closest_untracked_caller_location: checking frame {0:?}",
frame.instance) as &dyn Value))])
});
} else { ; }
};debug!("find_closest_untracked_caller_location: checking frame {:?}", frame.instance);
380381// Assert that the frame we look at is actually executing code currently
382 // (`loc` is `Right` when we are unwinding and the frame does not require cleanup).
383let loc = frame.loc.left().unwrap();
384385// This could be a non-`Call` terminator (such as `Drop`), or not a terminator at all
386 // (such as `box`). Use the normal span by default.
387let mut source_info = *frame.body.source_info(loc);
388389// If this is a `Call` terminator, use the `fn_span` instead.
390let block = &frame.body.basic_blocks[loc.block];
391if loc.statement_index == block.statements.len() {
392{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/eval_context.rs:392",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(392u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("find_closest_untracked_caller_location: got terminator {0:?} ({1:?})",
block.terminator(), block.terminator().kind) as
&dyn Value))])
});
} else { ; }
};debug!(
393"find_closest_untracked_caller_location: got terminator {:?} ({:?})",
394 block.terminator(),
395 block.terminator().kind,
396 );
397if let mir::TerminatorKind::Call { fn_span, .. } = block.terminator().kind {
398 source_info.span = fn_span;
399 }
400 }
401402let caller_location = if frame.instance.def.requires_caller_location(*self.tcx) {
403// We use `Err(())` as indication that we should continue up the call stack since
404 // this is a `#[track_caller]` function.
405Some(Err(()))
406 } else {
407None
408};
409if let Ok(span) =
410 frame.body.caller_location_span(source_info, caller_location, *self.tcx, Ok)
411 {
412return span;
413 }
414 }
415416::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("no non-`#[track_caller]` frame found"))span_bug!(self.cur_span(), "no non-`#[track_caller]` frame found")417 }
418419/// Returns the actual dynamic size and alignment of the place at the given type.
420 /// Only the "meta" (metadata) part of the place matters.
421 /// This can fail to provide an answer for extern types.
422pub(super) fn size_and_align_from_meta(
423&self,
424 metadata: &MemPlaceMeta<M::Provenance>,
425 layout: &TyAndLayout<'tcx>,
426 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
427if layout.is_sized() {
428return interp_ok(Some((layout.size, layout.align.abi)));
429 }
430match layout.ty.kind() {
431 ty::Adt(..) | ty::Tuple(..) => {
432// First get the size of all statically known fields.
433 // Don't use type_of::sizing_type_of because that expects t to be sized,
434 // and it also rounds up to alignment, which we want to avoid,
435 // as the unsized field's alignment could be smaller.
436if !!layout.ty.is_simd() {
::core::panicking::panic("assertion failed: !layout.ty.is_simd()")
};assert!(!layout.ty.is_simd());
437if !(layout.fields.count() > 0) {
::core::panicking::panic("assertion failed: layout.fields.count() > 0")
};assert!(layout.fields.count() > 0);
438{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/eval_context.rs:438",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(438u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("DST layout: {0:?}",
layout) as &dyn Value))])
});
} else { ; }
};trace!("DST layout: {:?}", layout);
439440let unsized_offset_unadjusted = layout.fields.offset(layout.fields.count() - 1);
441let sized_align = layout.align.abi;
442443// Recurse to get the size of the dynamically sized field (must be
444 // the last field). Can't have foreign types here, how would we
445 // adjust alignment and size for them?
446let field = layout.field(self, layout.fields.count() - 1);
447let Some((unsized_size, mut unsized_align)) =
448self.size_and_align_from_meta(metadata, &field)?
449else {
450// A field with an extern type. We don't know the actual dynamic size
451 // or the alignment.
452return interp_ok(None);
453 };
454455// # First compute the dynamic alignment
456457 // Packed type alignment needs to be capped.
458if let ty::Adt(def, _) = layout.ty.kind()
459 && let Some(packed) = def.repr().pack
460 {
461unsized_align = unsized_align.min(packed);
462 }
463464// Choose max of two known alignments (combined value must
465 // be aligned according to more restrictive of the two).
466let full_align = sized_align.max(unsized_align);
467468// # Then compute the dynamic size
469470let unsized_offset_adjusted = unsized_offset_unadjusted.align_to(unsized_align);
471let full_size = (unsized_offset_adjusted + unsized_size).align_to(full_align);
472473// Just for our sanitiy's sake, assert that this is equal to what codegen would compute.
474match (&full_size,
&(unsized_offset_unadjusted + unsized_size).align_to(full_align)) {
(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!(
475 full_size,
476 (unsized_offset_unadjusted + unsized_size).align_to(full_align)
477 );
478479// Check if this brought us over the size limit.
480if full_size > self.max_size_of_val() {
481do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidMeta(InvalidMetaKind::TooBig));throw_ub!(InvalidMeta(InvalidMetaKind::TooBig));
482 }
483interp_ok(Some((full_size, full_align)))
484 }
485 ty::Dynamic(expected_trait, _) => {
486let vtable = metadata.unwrap_meta().to_pointer(self)?;
487// Read size and align from vtable (already checks size).
488interp_ok(Some(self.get_vtable_size_and_align(vtable, Some(expected_trait))?))
489 }
490491 ty::Slice(_) | ty::Str => {
492let len = metadata.unwrap_meta().to_target_usize(self)?;
493let elem = layout.field(self, 0);
494495// Make sure the slice is not too big.
496let size = elem.size.bytes().saturating_mul(len); // we rely on `max_size_of_val` being smaller than `u64::MAX`.
497let size = Size::from_bytes(size);
498if size > self.max_size_of_val() {
499do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::InvalidMeta(InvalidMetaKind::SliceTooBig));throw_ub!(InvalidMeta(InvalidMetaKind::SliceTooBig));
500 }
501interp_ok(Some((size, elem.align.abi)))
502 }
503504 ty::Foreign(_) => interp_ok(None),
505506_ => ::rustc_middle::util::bug::span_bug_fmt(self.cur_span(),
format_args!("size_and_align_of::<{0}> not supported", layout.ty))span_bug!(self.cur_span(), "size_and_align_of::<{}> not supported", layout.ty),
507 }
508 }
509#[inline]
510pub fn size_and_align_of_val(
511&self,
512 val: &impl Projectable<'tcx, M::Provenance>,
513 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
514self.size_and_align_from_meta(&val.meta(), &val.layout())
515 }
516517/// Jump to the given block.
518#[inline]
519pub fn go_to_block(&mut self, target: mir::BasicBlock) {
520self.frame_mut().loc = Left(mir::Location { block: target, statement_index: 0 });
521 }
522523/// *Return* to the given `target` basic block.
524 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
525 ///
526 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
527pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
528if let Some(target) = target {
529self.go_to_block(target);
530interp_ok(())
531 } else {
532do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Unreachable)throw_ub!(Unreachable)533 }
534 }
535536/// *Unwind* to the given `target` basic block.
537 /// Do *not* use for returning! Use `return_to_block` instead.
538 ///
539 /// If `target` is `UnwindAction::Continue`, that indicates the function does not need cleanup
540 /// during unwinding, and we will just keep propagating that upwards.
541 ///
542 /// If `target` is `UnwindAction::Unreachable`, that indicates the function does not allow
543 /// unwinding, and doing so is UB.
544#[cold] // usually we have normal returns, not unwinding
545pub fn unwind_to_block(&mut self, target: mir::UnwindAction) -> InterpResult<'tcx> {
546self.frame_mut().loc = match target {
547 mir::UnwindAction::Cleanup(block) => Left(mir::Location { block, statement_index: 0 }),
548 mir::UnwindAction::Continue => Right(self.frame_mut().body.span),
549 mir::UnwindAction::Unreachable => {
550do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unwinding past a stack frame that does not allow unwinding"))
})));throw_ub_format!("unwinding past a stack frame that does not allow unwinding");
551 }
552 mir::UnwindAction::Terminate(reason) => {
553self.frame_mut().loc = Right(self.frame_mut().body.span);
554 M::unwind_terminate(self, reason)?;
555// This might have pushed a new stack frame, or it terminated execution.
556 // Either way, `loc` will not be updated.
557return interp_ok(());
558 }
559 };
560interp_ok(())
561 }
562563/// Call a query that can return `ErrorHandled`. Should be used for statics and other globals.
564 /// (`mir::Const`/`ty::Const` have `eval` methods that can be used directly instead.)
565pub fn ctfe_query<T>(
566&self,
567 query: impl FnOnce(TyCtxtAt<'tcx>) -> Result<T, ErrorHandled>,
568 ) -> Result<T, ErrorHandled> {
569// Use a precise span for better cycle errors.
570query(self.tcx.at(self.cur_span())).map_err(|err| {
571err.emit_note(*self.tcx);
572err573 })
574 }
575576pub fn eval_global(
577&self,
578 instance: ty::Instance<'tcx>,
579 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
580let gid = GlobalId { instance, promoted: None };
581let val = if self.tcx.is_static(gid.instance.def_id()) {
582let alloc_id = self.tcx.reserve_and_set_static_alloc(gid.instance.def_id());
583584let ty = instance.ty(self.tcx.tcx, self.typing_env);
585 mir::ConstAlloc { alloc_id, ty }
586 } else {
587self.ctfe_query(|tcx| tcx.eval_to_allocation_raw(self.typing_env.as_query_input(gid)))?
588};
589self.raw_const_to_mplace(val)
590 }
591592pub fn eval_mir_constant(
593&self,
594 val: &mir::Const<'tcx>,
595 span: Span,
596 layout: Option<TyAndLayout<'tcx>>,
597 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
598let _trace = <M as
crate::interpret::Machine>::enter_trace_span(||
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("const_eval",
"rustc_const_eval::interpret::eval_context",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/eval_context.rs"),
::tracing_core::__macro_support::Option::Some(598u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::eval_context"),
::tracing_core::field::FieldSet::new(&["const_eval", "val"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&display(&"eval_mir_constant")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&val) as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
})enter_trace_span!(M, const_eval::eval_mir_constant, ?val);
599let const_val = val.eval(*self.tcx, self.typing_env, span).map_err(|err| {
600if M::ALL_CONSTS_ARE_PRECHECKED {
601match err {
602 ErrorHandled::TooGeneric(..) => {},
603 ErrorHandled::Reported(reported, span) => {
604if reported.is_allowed_in_infallible() {
605// These errors can just sometimes happen, even when the expression
606 // is nominally "infallible", e.g. when running out of memory
607 // or when some layout could not be computed.
608} else {
609// Looks like the const is not captured by `required_consts`, that's bad.
610::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("interpret const eval failure of {0:?} which is not in required_consts",
val));span_bug!(span, "interpret const eval failure of {val:?} which is not in required_consts");
611 }
612 }
613 }
614 }
615err.emit_note(*self.tcx);
616err617 })?;
618self.const_val_to_op(const_val, val.ty(), layout)
619 }
620621#[must_use]
622pub fn dump_place(&self, place: &PlaceTy<'tcx, M::Provenance>) -> PlacePrinter<'_, 'tcx, M> {
623PlacePrinter { ecx: self, place: *place.place() }
624 }
625626#[must_use]
627pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
628Frame::generate_stacktrace_from_stack(self.stack(), *self.tcx)
629 }
630631pub fn adjust_nan<F1, F2>(&self, f: F2, inputs: &[F1]) -> F2
632where
633F1: rustc_apfloat::Float + rustc_apfloat::FloatConvert<F2>,
634 F2: rustc_apfloat::Float,
635 {
636if f.is_nan() { M::generate_nan(self, inputs) } else { f }
637 }
638}
639640#[doc(hidden)]
641/// Helper struct for the `dump_place` function.
642pub struct PlacePrinter<'a, 'tcx, M: Machine<'tcx>> {
643 ecx: &'a InterpCx<'tcx, M>,
644 place: Place<M::Provenance>,
645}
646647impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debugfor PlacePrinter<'a, 'tcx, M> {
648fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649match self.place {
650 Place::Local { local, offset, locals_addr } => {
651if true {
match (&locals_addr, &self.ecx.frame().locals_addr()) {
(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);
}
}
};
};debug_assert_eq!(locals_addr, self.ecx.frame().locals_addr());
652let mut allocs = Vec::new();
653fmt.write_fmt(format_args!("{0:?}", local))write!(fmt, "{local:?}")?;
654if let Some(offset) = offset {
655fmt.write_fmt(format_args!("+{0:#x}", offset.bytes()))write!(fmt, "+{:#x}", offset.bytes())?;
656 }
657fmt.write_fmt(format_args!(":"))write!(fmt, ":")?;
658659self.ecx.frame().locals[local].print(&mut allocs, fmt)?;
660661fmt.write_fmt(format_args!(": {0:?}",
self.ecx.dump_allocs(allocs.into_iter().flatten().collect())))write!(fmt, ": {:?}", self.ecx.dump_allocs(allocs.into_iter().flatten().collect()))662 }
663 Place::Ptr(mplace) => match mplace.ptr.provenance.and_then(Provenance::get_alloc_id) {
664Some(alloc_id) => {
665fmt.write_fmt(format_args!("by ref {0:?}: {1:?}", mplace.ptr,
self.ecx.dump_alloc(alloc_id)))write!(fmt, "by ref {:?}: {:?}", mplace.ptr, self.ecx.dump_alloc(alloc_id))666 }
667 ptr => fmt.write_fmt(format_args!(" integral by ref: {0:?}", ptr))write!(fmt, " integral by ref: {ptr:?}"),
668 },
669 }
670 }
671}