1//! This module contains everything needed to instantiate an interpreter.
2//! This separation exists to ensure that no fancy miri features like
3//! interpreting common C functions leak into CTFE.
45use std::borrow::{Borrow, Cow};
6use std::fmt::Debug;
7use std::hash::Hash;
89use rustc_abi::{Align, Size};
10use rustc_apfloat::{Float, FloatConvert};
11use rustc_middle::query::TyCtxtAt;
12use rustc_middle::ty::Ty;
13use rustc_middle::ty::layout::TyAndLayout;
14use rustc_middle::{mir, ty};
15use rustc_span::def_id::DefId;
16use rustc_target::callconv::FnAbi;
1718use super::{
19AllocBytes, AllocId, AllocKind, AllocRange, Allocation, CTFE_ALLOC_SALT, ConstAllocation,
20CtfeProvenance, EnteredTraceSpan, FnArg, Frame, ImmTy, InterpCx, InterpResult, MPlaceTy,
21MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, interp_ok, throw_unsup,
22};
2324/// Data returned by [`Machine::after_stack_pop`], and consumed by
25/// [`InterpCx::return_from_current_stack_frame`] to determine what actions should be done when
26/// returning from a stack frame.
27#[derive(#[automatically_derived]
impl ::core::cmp::Eq for ReturnAction {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ReturnAction {
#[inline]
fn eq(&self, other: &ReturnAction) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for ReturnAction {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ReturnAction::Normal => "Normal",
ReturnAction::NoJump => "NoJump",
ReturnAction::NoCleanup => "NoCleanup",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for ReturnAction { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ReturnAction {
#[inline]
fn clone(&self) -> ReturnAction { *self }
}Clone)]
28pub enum ReturnAction {
29/// Indicates that no special handling should be
30 /// done - we'll either return normally or unwind
31 /// based on the terminator for the function
32 /// we're leaving.
33Normal,
3435/// Indicates that we should *not* jump to the return/unwind address, as the callback already
36 /// took care of everything.
37NoJump,
3839/// Returned by [`InterpCx::pop_stack_frame_raw`] when no cleanup should be done.
40NoCleanup,
41}
4243/// The currently active retagging mode.
44#[derive(#[automatically_derived]
impl ::core::cmp::Eq for RetagMode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for RetagMode {
#[inline]
fn eq(&self, other: &RetagMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for RetagMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RetagMode::Default => "Default",
RetagMode::TwoPhase => "TwoPhase",
RetagMode::FnEntry => "FnEntry",
RetagMode::Raw => "Raw",
RetagMode::None => "None",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RetagMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RetagMode {
#[inline]
fn clone(&self) -> RetagMode { *self }
}Clone)]
45pub enum RetagMode {
46/// A regular retag.
47Default,
48/// Retag preparing for a two-phase borrow.
49TwoPhase,
50/// The initial retag of arguments when entering a function.
51FnEntry,
52/// Retagging for reference-to-raw-pointer cast.
53Raw,
54/// No retagging.
55None,
56}
5758/// Whether this kind of memory is allowed to leak
59pub trait MayLeak: Copy {
60fn may_leak(self) -> bool;
61}
6263/// The functionality needed by memory to manage its allocations
64pub trait AllocMap<K: Hash + Eq, V> {
65/// Tests if the map contains the given key.
66 /// Deliberately takes `&mut` because that is sufficient, and some implementations
67 /// can be more efficient then (using `RefCell::get_mut`).
68fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool69where
70K: Borrow<Q>;
7172/// Callers should prefer [`AllocMap::contains_key`] when it is possible to call because it may
73 /// be more efficient. This function exists for callers that only have a shared reference
74 /// (which might make it slightly less efficient than `contains_key`, e.g. if
75 /// the data is stored inside a `RefCell`).
76fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool77where
78K: Borrow<Q>;
7980/// Inserts a new entry into the map.
81fn insert(&mut self, k: K, v: V) -> Option<V>;
8283/// Removes an entry from the map.
84fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
85where
86K: Borrow<Q>;
8788/// Returns data based on the keys and values in the map.
89fn filter_map_collect<T>(&self, f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T>;
9091/// Returns a reference to entry `k`. If no such entry exists, call
92 /// `vacant` and either forward its error, or add its result to the map
93 /// and return a reference to *that*.
94fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E>;
9596/// Returns a mutable reference to entry `k`. If no such entry exists, call
97 /// `vacant` and either forward its error, or add its result to the map
98 /// and return a reference to *that*.
99fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E>;
100101/// Read-only lookup.
102fn get(&self, k: K) -> Option<&V> {
103self.get_or(k, || Err(())).ok()
104 }
105106/// Mutable lookup.
107fn get_mut(&mut self, k: K) -> Option<&mut V> {
108self.get_mut_or(k, || Err(())).ok()
109 }
110}
111112/// Methods of this trait signifies a point where CTFE evaluation would fail
113/// and some use case dependent behaviour can instead be applied.
114pub trait Machine<'tcx>: Sized {
115/// Additional memory kinds a machine wishes to distinguish from the builtin ones
116type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static;
117118/// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
119type Provenance: Provenance + Eq + Hash + 'static;
120121/// When getting the AllocId of a pointer, some extra data is also obtained from the provenance
122 /// that is passed to memory access hooks so they can do things with it.
123type ProvenanceExtra: Copy + 'static;
124125/// Machines can define extra (non-instance) things that represent values of function pointers.
126 /// For example, Miri uses this to return a function pointer from `dlsym`
127 /// that can later be called to execute the right thing.
128type ExtraFnVal: Debug + Copy;
129130/// Extra data stored in every call frame.
131type FrameExtra;
132133/// Extra data stored in every allocation.
134type AllocExtra: Debug + Clone + 'tcx;
135136/// Type for the bytes of the allocation.
137type Bytes: AllocBytes + 'static;
138139/// Memory's allocation map
140type MemoryMap: AllocMap<
141AllocId,
142 (
143MemoryKind<Self::MemoryKind>,
144Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>,
145 ),
146 > + Default147 + Clone;
148149/// The memory kind to use for copied global memory (held in `tcx`) --
150 /// or None if such memory should not be mutated and thus any such attempt will cause
151 /// a `ModifiedStatic` error to be raised.
152 /// Statics are copied under two circumstances: When they are mutated, and when
153 /// `adjust_allocation` (see below) returns an owned allocation
154 /// that is added to the memory so that the work is not done twice.
155const GLOBAL_KIND: Option<Self::MemoryKind>;
156157/// Should the machine panic on allocation failures?
158const PANIC_ON_ALLOC_FAIL: bool;
159160/// Determines whether `eval_mir_constant` can never fail because all required consts have
161 /// already been checked before.
162const ALL_CONSTS_ARE_PRECHECKED: bool = true;
163164/// Whether memory accesses should be alignment-checked.
165fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool;
166167/// Gives the machine a chance to detect more misalignment than the built-in checks would catch.
168#[inline(always)]
169fn alignment_check(
170 _ecx: &InterpCx<'tcx, Self>,
171 _alloc_id: AllocId,
172 _alloc_align: Align,
173 _alloc_kind: AllocKind,
174 _offset: Size,
175 _align: Align,
176 ) -> Option<Misalignment> {
177None178 }
179180/// Whether to enforce the validity invariant for a specific layout.
181fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool;
182/// Whether to enforce the validity invariant *recursively*.
183fn enforce_validity_recursively(
184 _ecx: &InterpCx<'tcx, Self>,
185 _layout: TyAndLayout<'tcx>,
186 ) -> bool {
187false
188}
189190/// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually
191 /// check for overflow.
192fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool;
193194/// Entry point for obtaining the MIR of anything that should get evaluated.
195 /// So not just functions and shims, but also const/static initializers, anonymous
196 /// constants, ...
197fn load_mir(
198 ecx: &InterpCx<'tcx, Self>,
199 instance: ty::InstanceKind<'tcx>,
200 ) -> &'tcx mir::Body<'tcx> {
201ecx.tcx.instance_mir(instance)
202 }
203204/// Entry point to all function calls.
205 ///
206 /// Returns either the mir to use for the call, or `None` if execution should
207 /// just proceed (which usually means this hook did all the work that the
208 /// called function should usually have done). In the latter case, it is
209 /// this hook's responsibility to advance the instruction pointer!
210 /// (This is to support functions like `__rust_maybe_catch_panic` that neither find a MIR
211 /// nor just jump to `ret`, but instead push their own stack frame.)
212 /// Passing `dest`and `ret` in the same `Option` proved very annoying when only one of them
213 /// was used.
214fn find_mir_or_eval_fn(
215 ecx: &mut InterpCx<'tcx, Self>,
216 instance: ty::Instance<'tcx>,
217 abi: &FnAbi<'tcx, Ty<'tcx>>,
218 args: &[FnArg<'tcx, Self::Provenance>],
219 destination: &PlaceTy<'tcx, Self::Provenance>,
220 target: Option<mir::BasicBlock>,
221 unwind: mir::UnwindAction,
222 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>>;
223224/// Execute `fn_val`. It is the hook's responsibility to advance the instruction
225 /// pointer as appropriate.
226fn call_extra_fn(
227 ecx: &mut InterpCx<'tcx, Self>,
228 fn_val: Self::ExtraFnVal,
229 abi: &FnAbi<'tcx, Ty<'tcx>>,
230 args: &[FnArg<'tcx, Self::Provenance>],
231 destination: &PlaceTy<'tcx, Self::Provenance>,
232 target: Option<mir::BasicBlock>,
233 unwind: mir::UnwindAction,
234 ) -> InterpResult<'tcx>;
235236/// Directly process an intrinsic without pushing a stack frame. It is the hook's
237 /// responsibility to advance the instruction pointer as appropriate.
238 ///
239 /// Returns `None` if the intrinsic was fully handled.
240 /// Otherwise, returns an `Instance` of the function that implements the intrinsic.
241fn call_intrinsic(
242 ecx: &mut InterpCx<'tcx, Self>,
243 instance: ty::Instance<'tcx>,
244 args: &[OpTy<'tcx, Self::Provenance>],
245 destination: &PlaceTy<'tcx, Self::Provenance>,
246 target: Option<mir::BasicBlock>,
247 unwind: mir::UnwindAction,
248 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>>;
249250/// Directly process an LLVM intrinsic without pushing a stack frame. It is the hook's
251 /// responsibility to advance the instruction pointer as appropriate.
252fn call_llvm_intrinsic(
253 ecx: &mut InterpCx<'tcx, Self>,
254 instance: ty::Instance<'tcx>,
255 args: &[OpTy<'tcx, Self::Provenance>],
256 destination: &PlaceTy<'tcx, Self::Provenance>,
257 target: Option<mir::BasicBlock>,
258 ) -> InterpResult<'tcx>;
259260/// Check whether the given function may be executed on the current machine, in terms of the
261 /// target features is requires.
262fn check_fn_target_features(
263 _ecx: &InterpCx<'tcx, Self>,
264 _instance: ty::Instance<'tcx>,
265 ) -> InterpResult<'tcx>;
266267/// Called to evaluate `Assert` MIR terminators that trigger a panic.
268fn assert_panic(
269 ecx: &mut InterpCx<'tcx, Self>,
270 msg: &mir::AssertMessage<'tcx>,
271 unwind: mir::UnwindAction,
272 ) -> InterpResult<'tcx>;
273274/// Called to trigger a non-unwinding panic.
275fn panic_nounwind(_ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx>;
276277/// Called when unwinding reached a state where execution should be terminated.
278fn unwind_terminate(
279 ecx: &mut InterpCx<'tcx, Self>,
280 reason: mir::UnwindTerminateReason,
281 ) -> InterpResult<'tcx>;
282283/// Called for all binary operations where the LHS has pointer type.
284 ///
285 /// Returns a (value, overflowed) pair if the operation succeeded
286fn binary_ptr_op(
287 ecx: &InterpCx<'tcx, Self>,
288 bin_op: mir::BinOp,
289 left: &ImmTy<'tcx, Self::Provenance>,
290 right: &ImmTy<'tcx, Self::Provenance>,
291 ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>>;
292293/// Generate the NaN returned by a float operation, given the list of inputs.
294 /// (This is all inputs, not just NaN inputs!)
295fn generate_nan<F1: Float + FloatConvert<F2>, F2: Float>(
296 _ecx: &InterpCx<'tcx, Self>,
297 _inputs: &[F1],
298 ) -> F2 {
299// By default we always return the preferred NaN.
300F2::NAN301 }
302303/// Apply non-determinism to float operations that do not return a precise result.
304fn apply_float_nondet(
305 _ecx: &mut InterpCx<'tcx, Self>,
306 val: ImmTy<'tcx, Self::Provenance>,
307 ) -> InterpResult<'tcx, ImmTy<'tcx, Self::Provenance>> {
308interp_ok(val)
309 }
310311/// Determines the result of `min`/`max` on floats when the arguments are equal.
312fn equal_float_min_max<F: Float>(_ecx: &InterpCx<'tcx, Self>, a: F, _b: F) -> F {
313// By default, we pick the left argument.
314a315 }
316317/// Determines whether the `fmuladd` intrinsics fuse the multiply-add or use separate operations.
318fn float_fuse_mul_add(_ecx: &InterpCx<'tcx, Self>) -> bool;
319320/// Called before a basic block terminator is executed.
321#[inline]
322fn before_terminator(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
323interp_ok(())
324 }
325326/// Determines the result of a `Operand::RuntimeChecks` invocation.
327fn runtime_checks(
328 _ecx: &InterpCx<'tcx, Self>,
329 r: mir::RuntimeChecks,
330 ) -> InterpResult<'tcx, bool>;
331332/// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction.
333 /// You can use this to detect long or endlessly running programs.
334#[inline]
335fn increment_const_eval_counter(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
336interp_ok(())
337 }
338339/// Called before a global allocation is accessed.
340 /// `def_id` is `Some` if this is the "lazy" allocation of a static.
341#[inline]
342fn before_access_global(
343 _tcx: TyCtxtAt<'tcx>,
344 _machine: &Self,
345 _alloc_id: AllocId,
346 _allocation: ConstAllocation<'tcx>,
347 _static_def_id: Option<DefId>,
348 _is_write: bool,
349 ) -> InterpResult<'tcx> {
350interp_ok(())
351 }
352353/// Return the `AllocId` for the given thread-local static in the current thread.
354fn thread_local_static_pointer(
355 _ecx: &mut InterpCx<'tcx, Self>,
356 def_id: DefId,
357 ) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
358do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ThreadLocalStatic(def_id))throw_unsup!(ThreadLocalStatic(def_id))359 }
360361/// Return the `AllocId` for the given `extern static`.
362fn extern_static_pointer(
363 ecx: &InterpCx<'tcx, Self>,
364 def_id: DefId,
365 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
366367/// "Int-to-pointer cast"
368fn ptr_from_addr_cast(
369 ecx: &InterpCx<'tcx, Self>,
370 addr: u64,
371 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>>;
372373/// Marks a pointer as exposed, allowing its provenance
374 /// to be recovered. "Pointer-to-int cast"
375fn expose_provenance(
376 ecx: &InterpCx<'tcx, Self>,
377 provenance: Self::Provenance,
378 ) -> InterpResult<'tcx>;
379380/// Convert a pointer with provenance into an allocation-offset pair and extra provenance info.
381 /// `size` says how many bytes of memory are expected at that pointer. The *sign* of `size` can
382 /// be used to disambiguate situations where a wildcard pointer sits right in between two
383 /// allocations.
384 ///
385 /// If `ptr.provenance.get_alloc_id()` is `Some(p)`, the returned `AllocId` must be `p`.
386 /// The resulting `AllocId` will just be used for that one step and the forgotten again
387 /// (i.e., we'll never turn the data returned here back into a `Pointer` that might be
388 /// stored in machine state).
389 ///
390 /// When this fails, that means the pointer does not point to a live allocation.
391fn ptr_get_alloc(
392 ecx: &InterpCx<'tcx, Self>,
393 ptr: Pointer<Self::Provenance>,
394 size: i64,
395 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>;
396397/// Return a "root" pointer for the given allocation: the one that is used for direct
398 /// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
399 ///
400 /// Not called on `extern` or thread-local statics (those use the methods above).
401 ///
402 /// `kind` is the kind of the allocation the pointer points to; it can be `None` when
403 /// it's a global and `GLOBAL_KIND` is `None`.
404fn adjust_alloc_root_pointer(
405 ecx: &InterpCx<'tcx, Self>,
406 ptr: Pointer,
407 kind: Option<MemoryKind<Self::MemoryKind>>,
408 ) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
409410/// Called to adjust global allocations to the Provenance and AllocExtra of this machine.
411 ///
412 /// If `alloc` contains pointers, then they are all pointing to globals.
413 ///
414 /// This should avoid copying if no work has to be done! If this returns an owned
415 /// allocation (because a copy had to be done to adjust things), machine memory will
416 /// cache the result. (This relies on `AllocMap::get_or` being able to add the
417 /// owned allocation to the map even when the map is shared.)
418fn adjust_global_allocation<'b>(
419 ecx: &InterpCx<'tcx, Self>,
420 id: AllocId,
421 alloc: &'b Allocation,
422 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>;
423424/// Initialize the extra state of an allocation local to this machine.
425 ///
426 /// This is guaranteed to be called exactly once on all allocations local to this machine.
427 /// It will not be called automatically for global allocations; `adjust_global_allocation`
428 /// has to do that itself if that is desired.
429fn init_local_allocation(
430 ecx: &InterpCx<'tcx, Self>,
431 id: AllocId,
432 kind: MemoryKind<Self::MemoryKind>,
433 size: Size,
434 align: Align,
435 ) -> InterpResult<'tcx, Self::AllocExtra>;
436437/// Hook for performing extra checks on a memory read access.
438 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
439 /// `range`.
440 ///
441 /// This will *not* be called during validation!
442 ///
443 /// Takes read-only access to the allocation so we can keep all the memory read
444 /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
445 /// need to mutate.
446 ///
447 /// This is not invoked for ZST accesses, as no read actually happens.
448#[inline(always)]
449fn before_memory_read(
450 _tcx: TyCtxtAt<'tcx>,
451 _machine: &Self,
452 _alloc_extra: &Self::AllocExtra,
453 _ptr: Pointer<Option<Self::Provenance>>,
454 _prov: (AllocId, Self::ProvenanceExtra),
455 _range: AllocRange,
456 ) -> InterpResult<'tcx> {
457interp_ok(())
458 }
459460/// Hook for performing extra checks on any memory read access,
461 /// that involves an allocation, even ZST reads.
462 ///
463 /// This will *not* be called during validation!
464 ///
465 /// Used to prevent statics from self-initializing by reading from their own memory
466 /// as it is being initialized.
467fn before_alloc_access(
468 _tcx: TyCtxtAt<'tcx>,
469 _machine: &Self,
470 _alloc_id: AllocId,
471 ) -> InterpResult<'tcx> {
472interp_ok(())
473 }
474475/// Hook for performing extra checks on a memory write access.
476 /// This is not invoked for ZST accesses, as no write actually happens.
477 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
478 /// `range`.
479#[inline(always)]
480fn before_memory_write(
481 _tcx: TyCtxtAt<'tcx>,
482 _machine: &mut Self,
483 _alloc_extra: &mut Self::AllocExtra,
484 _ptr: Pointer<Option<Self::Provenance>>,
485 _prov: (AllocId, Self::ProvenanceExtra),
486 _range: AllocRange,
487 ) -> InterpResult<'tcx> {
488interp_ok(())
489 }
490491/// Hook for performing extra operations on a memory deallocation.
492 /// `ptr` will always be a pointer with the provenance in `prov` pointing to the beginning of
493 /// the allocation.
494#[inline(always)]
495fn before_memory_deallocation(
496 _tcx: TyCtxtAt<'tcx>,
497 _machine: &mut Self,
498 _alloc_extra: &mut Self::AllocExtra,
499 _ptr: Pointer<Option<Self::Provenance>>,
500 _prov: (AllocId, Self::ProvenanceExtra),
501 _size: Size,
502 _align: Align,
503 _kind: MemoryKind<Self::MemoryKind>,
504 ) -> InterpResult<'tcx> {
505interp_ok(())
506 }
507508/// Executes a retagging operation for a single pointer.
509 /// Returns the possibly adjusted pointer. Return `None` if the pointer
510 /// was left unchanged.
511 ///
512 /// `ty` is the full type of the pointer. This is not the same as `val.layout.ty` for boxes
513 /// where `val` is just the inner raw pointer, but `ty` is the entire `Box` type.
514#[inline]
515fn retag_ptr_value(
516 _ecx: &mut InterpCx<'tcx, Self>,
517 _val: &ImmTy<'tcx, Self::Provenance>,
518 _ty: Ty<'tcx>,
519 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, Self::Provenance>>> {
520interp_ok(None)
521 }
522523/// Invoke `f` in a state where calls to `retag_ptr_value` will use the given retag mode.
524#[inline(always)]
525fn with_retag_mode<T>(
526 ecx: &mut InterpCx<'tcx, Self>,
527 _mode: RetagMode,
528 f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
529 ) -> InterpResult<'tcx, T> {
530f(ecx)
531 }
532533/// Called on places used for in-place function argument and return value handling.
534 ///
535 /// These places need to be protected to make sure the program cannot tell whether the
536 /// argument/return value was actually copied or passed in-place..
537fn protect_in_place_function_argument(
538 ecx: &mut InterpCx<'tcx, Self>,
539 mplace: &MPlaceTy<'tcx, Self::Provenance>,
540 ) -> InterpResult<'tcx> {
541// Without an aliasing model, all we can do is put `Uninit` into the place.
542 // Conveniently this also ensures that the place actually points to suitable memory.
543ecx.write_uninit(mplace)
544 }
545546/// Called immediately before a new stack frame gets pushed.
547fn init_frame(
548 ecx: &mut InterpCx<'tcx, Self>,
549 frame: Frame<'tcx, Self::Provenance>,
550 ) -> InterpResult<'tcx, Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
551552/// Borrow the current thread's stack.
553fn stack<'a>(
554 ecx: &'a InterpCx<'tcx, Self>,
555 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>];
556557/// Mutably borrow the current thread's stack.
558fn stack_mut<'a>(
559 ecx: &'a mut InterpCx<'tcx, Self>,
560 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>>;
561562/// Called immediately after a stack frame got pushed and its locals got initialized.
563fn after_stack_push(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
564interp_ok(())
565 }
566567/// Called just before the frame is removed from the stack (followed by return value copy and
568 /// local cleanup).
569fn before_stack_pop(_ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
570interp_ok(())
571 }
572573/// Called immediately after a stack frame got popped, but before jumping back to the caller.
574 /// The `locals` have already been destroyed!
575#[inline(always)]
576fn after_stack_pop(
577 _ecx: &mut InterpCx<'tcx, Self>,
578 _frame: Frame<'tcx, Self::Provenance, Self::FrameExtra>,
579 unwinding: bool,
580 ) -> InterpResult<'tcx, ReturnAction> {
581// By default, we do not support unwinding from panics
582if !!unwinding { ::core::panicking::panic("assertion failed: !unwinding") };assert!(!unwinding);
583interp_ok(ReturnAction::Normal)
584 }
585586/// Called immediately after an "immediate" local variable is read in a given frame
587 /// (i.e., this is called for reads that do not end up accessing addressable memory).
588#[inline(always)]
589fn after_local_read(
590 _ecx: &InterpCx<'tcx, Self>,
591 _frame: &Frame<'tcx, Self::Provenance, Self::FrameExtra>,
592 _local: mir::Local,
593 ) -> InterpResult<'tcx> {
594interp_ok(())
595 }
596597/// Called immediately after an "immediate" local variable is assigned a new value
598 /// (i.e., this is called for writes that do not end up in memory).
599 /// `storage_live` indicates whether this is the initial write upon `StorageLive`.
600#[inline(always)]
601fn after_local_write(
602 _ecx: &mut InterpCx<'tcx, Self>,
603 _local: mir::Local,
604 _storage_live: bool,
605 ) -> InterpResult<'tcx> {
606interp_ok(())
607 }
608609/// Called immediately after actual memory was allocated for a local
610 /// but before the local's stack frame is updated to point to that memory.
611#[inline(always)]
612fn after_local_moved_to_memory(
613 _ecx: &mut InterpCx<'tcx, Self>,
614 _local: mir::Local,
615 _mplace: &MPlaceTy<'tcx, Self::Provenance>,
616 ) -> InterpResult<'tcx> {
617interp_ok(())
618 }
619620/// Returns the salt to be used for a deduplicated global alloation.
621 /// If the allocation is for a function, the instance is provided as well
622 /// (this lets Miri ensure unique addresses for some functions).
623fn get_global_alloc_salt(
624 ecx: &InterpCx<'tcx, Self>,
625 instance: Option<ty::Instance<'tcx>>,
626 ) -> usize;
627628fn cached_union_data_range<'e>(
629 _ecx: &'e mut InterpCx<'tcx, Self>,
630 _ty: Ty<'tcx>,
631 compute_range: impl FnOnce() -> RangeSet,
632 ) -> Cow<'e, RangeSet> {
633// Default to no caching.
634Cow::Owned(compute_range())
635 }
636637/// Compute the value passed to the constructors of the `AllocBytes` type for
638 /// abstract machine allocations.
639fn get_default_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams;
640641/// Allows enabling/disabling tracing calls from within `rustc_const_eval` at compile time, by
642 /// delegating the entering of [tracing::Span]s to implementors of the [Machine] trait. The
643 /// default implementation corresponds to tracing being disabled, meaning the tracing calls will
644 /// supposedly be optimized out completely. To enable tracing, override this trait method and
645 /// return `span.entered()`. Also see [crate::enter_trace_span].
646#[must_use]
647 #[inline(always)]
648fn enter_trace_span(_span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan {
649 ()
650 }
651}
652653/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
654/// (CTFE and ConstProp) use the same instance. Here, we share that code.
655pub macro compile_time_machine(<$tcx: lifetime>) {
656type Provenance = CtfeProvenance;
657type ProvenanceExtra = bool; // the "immutable" flag
658659type ExtraFnVal = !;
660661type MemoryKind = $crate::const_eval::MemoryKind;
662type MemoryMap =
663 rustc_data_structures::fx::FxIndexMap<AllocId, (MemoryKind<Self::MemoryKind>, Allocation)>;
664const GLOBAL_KIND: Option<Self::MemoryKind> = None; // no copying of globals from `tcx` to machine memory
665666type AllocExtra = ();
667type FrameExtra = ();
668type Bytes = Box<[u8]>;
669670#[inline(always)]
671fn ignore_optional_overflow_checks(_ecx: &InterpCx<$tcx, Self>) -> bool {
672false
673}
674675#[inline(always)]
676fn unwind_terminate(
677 _ecx: &mut InterpCx<$tcx, Self>,
678 _reason: mir::UnwindTerminateReason,
679 ) -> InterpResult<$tcx> {
680unreachable!("unwinding cannot happen during compile-time evaluation")
681 }
682683#[inline(always)]
684fn check_fn_target_features(
685 _ecx: &InterpCx<$tcx, Self>,
686 _instance: ty::Instance<$tcx>,
687 ) -> InterpResult<$tcx> {
688// For now we don't do any checking here. We can't use `tcx.sess` because that can differ
689 // between crates, and we need to ensure that const-eval always behaves the same.
690interp_ok(())
691 }
692693#[inline(always)]
694fn call_extra_fn(
695 _ecx: &mut InterpCx<$tcx, Self>,
696 fn_val: !,
697 _abi: &FnAbi<$tcx, Ty<$tcx>>,
698 _args: &[FnArg<$tcx>],
699 _destination: &PlaceTy<$tcx, Self::Provenance>,
700 _target: Option<mir::BasicBlock>,
701 _unwind: mir::UnwindAction,
702 ) -> InterpResult<$tcx> {
703match fn_val {}
704 }
705706#[inline(always)]
707fn float_fuse_mul_add(_ecx: &InterpCx<$tcx, Self>) -> bool {
708true
709}
710711#[inline(always)]
712fn adjust_global_allocation<'b>(
713 _ecx: &InterpCx<$tcx, Self>,
714 _id: AllocId,
715 alloc: &'b Allocation,
716 ) -> InterpResult<$tcx, Cow<'b, Allocation<Self::Provenance>>> {
717// Overwrite default implementation: no need to adjust anything.
718interp_ok(Cow::Borrowed(alloc))
719 }
720721fn init_local_allocation(
722 _ecx: &InterpCx<$tcx, Self>,
723 _id: AllocId,
724 _kind: MemoryKind<Self::MemoryKind>,
725 _size: Size,
726 _align: Align,
727 ) -> InterpResult<$tcx, Self::AllocExtra> {
728 interp_ok(())
729 }
730731fn extern_static_pointer(
732 ecx: &InterpCx<$tcx, Self>,
733 def_id: DefId,
734 ) -> InterpResult<$tcx, Pointer> {
735// Use the `AllocId` associated with the `DefId`. Any actual *access* will fail.
736interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(), Size::ZERO))
737 }
738739#[inline(always)]
740fn adjust_alloc_root_pointer(
741 _ecx: &InterpCx<$tcx, Self>,
742 ptr: Pointer<CtfeProvenance>,
743 _kind: Option<MemoryKind<Self::MemoryKind>>,
744 ) -> InterpResult<$tcx, Pointer<CtfeProvenance>> {
745 interp_ok(ptr)
746 }
747748#[inline(always)]
749fn ptr_from_addr_cast(
750 _ecx: &InterpCx<$tcx, Self>,
751 addr: u64,
752 ) -> InterpResult<$tcx, Pointer<Option<CtfeProvenance>>> {
753// Allow these casts, but make the pointer not dereferenceable.
754 // (I.e., they behave like transmutation.)
755 // This is correct because no pointers can ever be exposed in compile-time evaluation.
756interp_ok(Pointer::without_provenance(addr))
757 }
758759#[inline(always)]
760fn ptr_get_alloc(
761 _ecx: &InterpCx<$tcx, Self>,
762 ptr: Pointer<CtfeProvenance>,
763 _size: i64,
764 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
765let (prov, offset) = ptr.prov_and_relative_offset();
766Some((prov.alloc_id(), offset, prov.immutable()))
767 }
768769#[inline(always)]
770fn get_global_alloc_salt(
771 _ecx: &InterpCx<$tcx, Self>,
772 _instance: Option<ty::Instance<$tcx>>,
773 ) -> usize {
774 CTFE_ALLOC_SALT
775 }
776}