1 //! An interpreter for MIR used in CTFE and by miri.
4 macro_rules! err_unsup {
6 $crate::mir::interpret::InterpError::Unsupported(
7 $crate::mir::interpret::UnsupportedOpInfo::$($tt)*
13 macro_rules! err_unsup_format {
14 ($($tt:tt)*) => { err_unsup!(Unsupported(format!($($tt)*))) };
18 macro_rules! err_inval {
20 $crate::mir::interpret::InterpError::InvalidProgram(
21 $crate::mir::interpret::InvalidProgramInfo::$($tt)*
29 $crate::mir::interpret::InterpError::UndefinedBehavior(
30 $crate::mir::interpret::UndefinedBehaviorInfo::$($tt)*
36 macro_rules! err_ub_format {
37 ($($tt:tt)*) => { err_ub!(Ub(format!($($tt)*))) };
41 macro_rules! err_panic {
43 $crate::mir::interpret::InterpError::Panic(
44 $crate::mir::interpret::PanicInfo::$($tt)*
50 macro_rules! err_exhaust {
52 $crate::mir::interpret::InterpError::ResourceExhaustion(
53 $crate::mir::interpret::ResourceExhaustionInfo::$($tt)*
59 macro_rules! throw_unsup {
60 ($($tt:tt)*) => { return Err(err_unsup!($($tt)*).into()) };
64 macro_rules! throw_unsup_format {
65 ($($tt:tt)*) => { throw_unsup!(Unsupported(format!($($tt)*))) };
69 macro_rules! throw_inval {
70 ($($tt:tt)*) => { return Err(err_inval!($($tt)*).into()) };
74 macro_rules! throw_ub {
75 ($($tt:tt)*) => { return Err(err_ub!($($tt)*).into()) };
79 macro_rules! throw_ub_format {
80 ($($tt:tt)*) => { throw_ub!(Ub(format!($($tt)*))) };
84 macro_rules! throw_panic {
85 ($($tt:tt)*) => { return Err(err_panic!($($tt)*).into()) };
89 macro_rules! throw_exhaust {
90 ($($tt:tt)*) => { return Err(err_exhaust!($($tt)*).into()) };
94 macro_rules! throw_machine_stop {
96 return Err($crate::mir::interpret::InterpError::MachineStop(Box::new($($tt)*)).into())
106 pub use self::error::{
107 InterpErrorInfo, InterpResult, InterpError, AssertMessage, ConstEvalErr, struct_error,
108 FrameInfo, ConstEvalRawResult, ConstEvalResult, ErrorHandled, PanicInfo, UnsupportedOpInfo,
109 InvalidProgramInfo, ResourceExhaustionInfo, UndefinedBehaviorInfo,
112 pub use self::value::{Scalar, ScalarMaybeUndef, RawConst, ConstValue, get_slice_bytes};
114 pub use self::allocation::{Allocation, AllocationExtra, Relocations, UndefMask};
116 pub use self::pointer::{Pointer, PointerArithmetic, CheckInAllocMsg};
119 use crate::hir::def_id::DefId;
120 use crate::ty::{self, TyCtxt, Instance};
121 use crate::ty::codec::TyDecoder;
122 use crate::ty::layout::{self, Size};
123 use crate::ty::subst::GenericArgKind;
126 use std::num::NonZeroU32;
127 use std::sync::atomic::{AtomicU32, Ordering};
128 use rustc_serialize::{Encoder, Decodable, Encodable};
129 use rustc_data_structures::fx::FxHashMap;
130 use rustc_data_structures::sync::{Lock, HashMapExt};
131 use rustc_data_structures::tiny_list::TinyList;
132 use rustc_macros::HashStable;
133 use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian, BigEndian};
135 /// Uniquely identifies one of the following:
138 /// - A const fn where all arguments (if any) are zero-sized types
139 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, RustcEncodable, RustcDecodable)]
140 #[derive(HashStable, Lift)]
141 pub struct GlobalId<'tcx> {
142 /// For a constant or static, the `Instance` of the item itself.
143 /// For a promoted global, the `Instance` of the function they belong to.
144 pub instance: ty::Instance<'tcx>,
146 /// The index for promoted globals within their function's `mir::Body`.
147 pub promoted: Option<mir::Promoted>,
150 #[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
151 pub struct AllocId(pub u64);
153 impl rustc_serialize::UseSpecializedEncodable for AllocId {}
154 impl rustc_serialize::UseSpecializedDecodable for AllocId {}
156 #[derive(RustcDecodable, RustcEncodable)]
157 enum AllocDiscriminant {
163 pub fn specialized_encode_alloc_id<'tcx, E: Encoder>(
167 ) -> Result<(), E::Error> {
168 let alloc: GlobalAlloc<'tcx> = tcx.alloc_map.lock().get(alloc_id)
169 .expect("no value for given alloc ID");
171 GlobalAlloc::Memory(alloc) => {
172 trace!("encoding {:?} with {:#?}", alloc_id, alloc);
173 AllocDiscriminant::Alloc.encode(encoder)?;
174 alloc.encode(encoder)?;
176 GlobalAlloc::Function(fn_instance) => {
177 trace!("encoding {:?} with {:#?}", alloc_id, fn_instance);
178 AllocDiscriminant::Fn.encode(encoder)?;
179 fn_instance.encode(encoder)?;
181 GlobalAlloc::Static(did) => {
182 // References to statics doesn't need to know about their allocations,
183 // just about its `DefId`.
184 AllocDiscriminant::Static.encode(encoder)?;
185 did.encode(encoder)?;
191 // Used to avoid infinite recursion when decoding cyclic allocations.
192 type DecodingSessionId = NonZeroU32;
197 InProgressNonAlloc(TinyList<DecodingSessionId>),
198 InProgress(TinyList<DecodingSessionId>, AllocId),
202 pub struct AllocDecodingState {
203 // For each `AllocId`, we keep track of which decoding state it's currently in.
204 decoding_state: Vec<Lock<State>>,
205 // The offsets of each allocation in the data stream.
206 data_offsets: Vec<u32>,
209 impl AllocDecodingState {
210 pub fn new_decoding_session(&self) -> AllocDecodingSession<'_> {
211 static DECODER_SESSION_ID: AtomicU32 = AtomicU32::new(0);
212 let counter = DECODER_SESSION_ID.fetch_add(1, Ordering::SeqCst);
214 // Make sure this is never zero.
215 let session_id = DecodingSessionId::new((counter & 0x7FFFFFFF) + 1).unwrap();
217 AllocDecodingSession {
223 pub fn new(data_offsets: Vec<u32>) -> Self {
224 let decoding_state = vec![Lock::new(State::Empty); data_offsets.len()];
233 #[derive(Copy, Clone)]
234 pub struct AllocDecodingSession<'s> {
235 state: &'s AllocDecodingState,
236 session_id: DecodingSessionId,
239 impl<'s> AllocDecodingSession<'s> {
240 /// Decodes an `AllocId` in a thread-safe way.
241 pub fn decode_alloc_id<D>(&self, decoder: &mut D) -> Result<AllocId, D::Error>
245 // Read the index of the allocation.
246 let idx = decoder.read_u32()? as usize;
247 let pos = self.state.data_offsets[idx] as usize;
249 // Decode the `AllocDiscriminant` now so that we know if we have to reserve an
251 let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
252 let alloc_kind = AllocDiscriminant::decode(decoder)?;
253 Ok((alloc_kind, decoder.position()))
256 // Check the decoding state to see if it's already decoded or if we should
259 let mut entry = self.state.decoding_state[idx].lock();
262 State::Done(alloc_id) => {
265 ref mut entry @ State::Empty => {
266 // We are allowed to decode.
268 AllocDiscriminant::Alloc => {
269 // If this is an allocation, we need to reserve an
270 // `AllocId` so we can decode cyclic graphs.
271 let alloc_id = decoder.tcx().alloc_map.lock().reserve();
272 *entry = State::InProgress(
273 TinyList::new_single(self.session_id),
277 AllocDiscriminant::Fn | AllocDiscriminant::Static => {
278 // Fns and statics cannot be cyclic, and their `AllocId`
279 // is determined later by interning.
280 *entry = State::InProgressNonAlloc(
281 TinyList::new_single(self.session_id));
286 State::InProgressNonAlloc(ref mut sessions) => {
287 if sessions.contains(&self.session_id) {
288 bug!("this should be unreachable");
290 // Start decoding concurrently.
291 sessions.insert(self.session_id);
295 State::InProgress(ref mut sessions, alloc_id) => {
296 if sessions.contains(&self.session_id) {
300 // Start decoding concurrently.
301 sessions.insert(self.session_id);
308 // Now decode the actual data.
309 let alloc_id = decoder.with_position(pos, |decoder| {
311 AllocDiscriminant::Alloc => {
312 let alloc = <&'tcx Allocation as Decodable>::decode(decoder)?;
313 // We already have a reserved `AllocId`.
314 let alloc_id = alloc_id.unwrap();
315 trace!("decoded alloc {:?}: {:#?}", alloc_id, alloc);
316 decoder.tcx().alloc_map.lock().set_alloc_id_same_memory(alloc_id, alloc);
319 AllocDiscriminant::Fn => {
320 assert!(alloc_id.is_none());
321 trace!("creating fn alloc ID");
322 let instance = ty::Instance::decode(decoder)?;
323 trace!("decoded fn alloc instance: {:?}", instance);
324 let alloc_id = decoder.tcx().alloc_map.lock().create_fn_alloc(instance);
327 AllocDiscriminant::Static => {
328 assert!(alloc_id.is_none());
329 trace!("creating extern static alloc ID");
330 let did = DefId::decode(decoder)?;
331 trace!("decoded static def-ID: {:?}", did);
332 let alloc_id = decoder.tcx().alloc_map.lock().create_static_alloc(did);
338 self.state.decoding_state[idx].with_lock(|entry| {
339 *entry = State::Done(alloc_id);
346 impl fmt::Display for AllocId {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 write!(f, "{}", self.0)
352 /// An allocation in the global (tcx-managed) memory can be either a function pointer,
353 /// a static, or a "real" allocation with some data in it.
354 #[derive(Debug, Clone, Eq, PartialEq, Hash, RustcDecodable, RustcEncodable, HashStable)]
355 pub enum GlobalAlloc<'tcx> {
356 /// The alloc ID is used as a function pointer.
357 Function(Instance<'tcx>),
358 /// The alloc ID points to a "lazy" static variable that did not get computed (yet).
359 /// This is also used to break the cycle in recursive statics.
361 /// The alloc ID points to memory.
362 Memory(&'tcx Allocation),
365 pub struct AllocMap<'tcx> {
366 /// Maps `AllocId`s to their corresponding allocations.
367 alloc_map: FxHashMap<AllocId, GlobalAlloc<'tcx>>,
369 /// Used to ensure that statics and functions only get one associated `AllocId`.
370 /// Should never contain a `GlobalAlloc::Memory`!
372 // FIXME: Should we just have two separate dedup maps for statics and functions each?
373 dedup: FxHashMap<GlobalAlloc<'tcx>, AllocId>,
375 /// The `AllocId` to assign to the next requested ID.
376 /// Always incremented; never gets smaller.
380 impl<'tcx> AllocMap<'tcx> {
381 pub fn new() -> Self {
383 alloc_map: Default::default(),
384 dedup: Default::default(),
389 /// Obtains a new allocation ID that can be referenced but does not
390 /// yet have an allocation backing it.
392 /// Make sure to call `set_alloc_id_memory` or `set_alloc_id_same_memory` before returning such
393 /// an `AllocId` from a query.
397 let next = self.next_id;
398 self.next_id.0 = self.next_id.0
400 .expect("You overflowed a u64 by incrementing by 1... \
401 You've just earned yourself a free drink if we ever meet. \
402 Seriously, how did you do that?!");
406 /// Reserves a new ID *if* this allocation has not been dedup-reserved before.
407 /// Should only be used for function pointers and statics, we don't want
408 /// to dedup IDs for "real" memory!
409 fn reserve_and_set_dedup(&mut self, alloc: GlobalAlloc<'tcx>) -> AllocId {
411 GlobalAlloc::Function(..) | GlobalAlloc::Static(..) => {},
412 GlobalAlloc::Memory(..) => bug!("Trying to dedup-reserve memory with real data!"),
414 if let Some(&alloc_id) = self.dedup.get(&alloc) {
417 let id = self.reserve();
418 debug!("creating alloc {:?} with id {}", alloc, id);
419 self.alloc_map.insert(id, alloc.clone());
420 self.dedup.insert(alloc, id);
424 /// Generates an `AllocId` for a static or return a cached one in case this function has been
425 /// called on the same static before.
426 pub fn create_static_alloc(&mut self, static_id: DefId) -> AllocId {
427 self.reserve_and_set_dedup(GlobalAlloc::Static(static_id))
430 /// Generates an `AllocId` for a function. Depending on the function type,
431 /// this might get deduplicated or assigned a new ID each time.
432 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> AllocId {
433 // Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
434 // by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
435 // duplicated across crates.
436 // We thus generate a new `AllocId` for every mention of a function. This means that
437 // `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
438 // However, formatting code relies on function identity (see #58320), so we only do
439 // this for generic functions. Lifetime parameters are ignored.
440 let is_generic = instance.substs.into_iter().any(|kind| {
441 match kind.unpack() {
442 GenericArgKind::Lifetime(_) => false,
448 let id = self.reserve();
449 self.alloc_map.insert(id, GlobalAlloc::Function(instance));
453 self.reserve_and_set_dedup(GlobalAlloc::Function(instance))
457 /// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical
458 /// `Allocation` with a different `AllocId`.
459 /// Statics with identical content will still point to the same `Allocation`, i.e.,
460 /// their data will be deduplicated through `Allocation` interning -- but they
461 /// are different places in memory and as such need different IDs.
462 pub fn create_memory_alloc(&mut self, mem: &'tcx Allocation) -> AllocId {
463 let id = self.reserve();
464 self.set_alloc_id_memory(id, mem);
468 /// Returns `None` in case the `AllocId` is dangling. An `InterpretCx` can still have a
469 /// local `Allocation` for that `AllocId`, but having such an `AllocId` in a constant is
470 /// illegal and will likely ICE.
471 /// This function exists to allow const eval to detect the difference between evaluation-
472 /// local dangling pointers and allocations in constants/statics.
474 pub fn get(&self, id: AllocId) -> Option<GlobalAlloc<'tcx>> {
475 self.alloc_map.get(&id).cloned()
478 /// Panics if the `AllocId` does not refer to an `Allocation`
479 pub fn unwrap_memory(&self, id: AllocId) -> &'tcx Allocation {
481 Some(GlobalAlloc::Memory(mem)) => mem,
482 _ => bug!("expected allocation ID {} to point to memory", id),
486 /// Panics if the `AllocId` does not refer to a function
487 pub fn unwrap_fn(&self, id: AllocId) -> Instance<'tcx> {
489 Some(GlobalAlloc::Function(instance)) => instance,
490 _ => bug!("expected allocation ID {} to point to a function", id),
494 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. Trying to
495 /// call this function twice, even with the same `Allocation` will ICE the compiler.
496 pub fn set_alloc_id_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
497 if let Some(old) = self.alloc_map.insert(id, GlobalAlloc::Memory(mem)) {
498 bug!("tried to set allocation ID {}, but it was already existing as {:#?}", id, old);
502 /// Freezes an `AllocId` created with `reserve` by pointing it at an `Allocation`. May be called
503 /// twice for the same `(AllocId, Allocation)` pair.
504 fn set_alloc_id_same_memory(&mut self, id: AllocId, mem: &'tcx Allocation) {
505 self.alloc_map.insert_same(id, GlobalAlloc::Memory(mem));
509 ////////////////////////////////////////////////////////////////////////////////
510 // Methods to access integers in the target endianness
511 ////////////////////////////////////////////////////////////////////////////////
514 pub fn write_target_uint(
515 endianness: layout::Endian,
516 mut target: &mut [u8],
518 ) -> Result<(), io::Error> {
519 let len = target.len();
521 layout::Endian::Little => target.write_uint128::<LittleEndian>(data, len),
522 layout::Endian::Big => target.write_uint128::<BigEndian>(data, len),
527 pub fn read_target_uint(endianness: layout::Endian, mut source: &[u8]) -> Result<u128, io::Error> {
529 layout::Endian::Little => source.read_uint128::<LittleEndian>(source.len()),
530 layout::Endian::Big => source.read_uint128::<BigEndian>(source.len()),
534 ////////////////////////////////////////////////////////////////////////////////
535 // Methods to facilitate working with signed integers stored in a u128
536 ////////////////////////////////////////////////////////////////////////////////
538 /// Truncates `value` to `size` bits and then sign-extend it to 128 bits
539 /// (i.e., if it is negative, fill with 1's on the left).
541 pub fn sign_extend(value: u128, size: Size) -> u128 {
542 let size = size.bits();
544 // Truncated until nothing is left.
548 let shift = 128 - size;
549 // Shift the unsigned value to the left, then shift back to the right as signed
550 // (essentially fills with FF on the left).
551 (((value << shift) as i128) >> shift) as u128
554 /// Truncates `value` to `size` bits.
556 pub fn truncate(value: u128, size: Size) -> u128 {
557 let size = size.bits();
559 // Truncated until nothing is left.
562 let shift = 128 - size;
563 // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
564 (value << shift) >> shift