2 use rustc::ty::layout::HasTyCtxt;
3 use rustc::ty::{self, Ty, TyCtxt};
4 use rustc_hir::def_id::DefId;
5 use std::borrow::{Borrow, Cow};
6 use std::collections::hash_map::Entry;
9 use rustc_data_structures::fx::FxHashMap;
11 use rustc_span::source_map::Span;
13 use crate::interpret::{
14 self, snapshot, AllocId, Allocation, AssertMessage, GlobalId, ImmTy, InterpCx, InterpResult,
15 Memory, MemoryKind, OpTy, PlaceTy, Pointer, Scalar,
20 impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> {
21 /// Evaluate a const function where all arguments (if any) are zero-sized types.
22 /// The evaluation is memoized thanks to the query system.
24 /// Returns `true` if the call has been evaluated.
25 fn try_eval_const_fn_call(
27 instance: ty::Instance<'tcx>,
28 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
30 ) -> InterpResult<'tcx, bool> {
31 trace!("try_eval_const_fn_call: {:?}", instance);
32 // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot
33 // perform this optimization on items tagged with it.
34 if instance.def.requires_caller_location(self.tcx()) {
37 // For the moment we only do this for functions which take no arguments
38 // (or all arguments are ZSTs) so that we don't memoize too much.
39 if args.iter().any(|a| !a.layout.is_zst()) {
43 let dest = match ret {
44 Some((dest, _)) => dest,
45 // Don't memoize diverging function calls.
46 None => return Ok(false),
49 let gid = GlobalId { instance, promoted: None };
51 let place = self.const_eval_raw(gid)?;
53 self.copy_op(place.into(), dest)?;
55 self.return_to_block(ret.map(|r| r.1))?;
56 self.dump_place(*dest);
61 /// Number of steps until the detector even starts doing anything.
62 /// Also, a warning is shown to the user when this number is reached.
63 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
64 /// The number of steps between loop detector snapshots.
65 /// Should be a power of two for performance reasons.
66 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
68 // Extra machine state for CTFE, and the Machine instance
69 pub struct CompileTimeInterpreter<'mir, 'tcx> {
70 /// When this value is negative, it indicates the number of interpreter
71 /// steps *until* the loop detector is enabled. When it is positive, it is
72 /// the number of steps after the detector has been enabled modulo the loop
74 pub(super) steps_since_detector_enabled: isize,
76 /// Extra state to detect loops.
77 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>,
80 #[derive(Copy, Clone, Debug)]
81 pub struct MemoryExtra {
82 /// Whether this machine may read from statics
83 pub(super) can_access_statics: bool,
86 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
87 pub(super) fn new() -> Self {
88 CompileTimeInterpreter {
89 loop_detector: Default::default(),
90 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
95 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
97 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
101 FxHashMap::contains_key(self, k)
105 fn insert(&mut self, k: K, v: V) -> Option<V> {
106 FxHashMap::insert(self, k, v)
110 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
114 FxHashMap::remove(self, k)
118 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
119 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
123 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
128 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
134 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
135 match self.entry(k) {
136 Entry::Occupied(e) => Ok(e.into_mut()),
137 Entry::Vacant(e) => {
145 crate type CompileTimeEvalContext<'mir, 'tcx> =
146 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
148 impl interpret::MayLeak for ! {
150 fn may_leak(self) -> bool {
151 // `self` is uninhabited
156 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
157 type MemoryKinds = !;
158 type PointerTag = ();
161 type FrameExtra = ();
162 type MemoryExtra = MemoryExtra;
163 type AllocExtra = ();
165 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
167 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
169 // We do not check for alignment to avoid having to carry an `Align`
170 // in `ConstValue::ByRef`.
171 const CHECK_ALIGN: bool = false;
174 fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
175 false // for now, we don't enforce validity
178 fn find_mir_or_eval_fn(
179 ecx: &mut InterpCx<'mir, 'tcx, Self>,
181 instance: ty::Instance<'tcx>,
183 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
184 _unwind: Option<mir::BasicBlock>, // unwinding is not supported in consts
185 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
186 debug!("find_mir_or_eval_fn: {:?}", instance);
188 // Only check non-glue functions
189 if let ty::InstanceDef::Item(def_id) = instance.def {
190 // Execution might have wandered off into other crates, so we cannot do a stability-
191 // sensitive check here. But we can at least rule out functions that are not const
193 if ecx.tcx.is_const_fn_raw(def_id) {
194 // If this function is a `const fn` then under certain circumstances we
195 // can evaluate call via the query system, thus memoizing all future calls.
196 if ecx.try_eval_const_fn_call(instance, ret, args)? {
200 // Some functions we support even if they are non-const -- but avoid testing
201 // that for const fn! We certainly do *not* want to actually call the fn
202 // though, so be sure we return here.
203 return if ecx.hook_panic_fn(span, instance, args)? {
206 throw_unsup_format!("calling non-const function `{}`", instance)
210 // This is a const fn. Call it.
211 Ok(Some(match ecx.load_mir(instance.def, None) {
214 if let err_unsup!(NoMirFor(ref path)) = err.kind {
215 return Err(ConstEvalError::NeedsRfc(format!(
216 "calling extern function `{}`",
227 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
229 _args: &[OpTy<'tcx>],
230 _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
231 _unwind: Option<mir::BasicBlock>,
232 ) -> InterpResult<'tcx> {
237 ecx: &mut InterpCx<'mir, 'tcx, Self>,
239 instance: ty::Instance<'tcx>,
241 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
242 _unwind: Option<mir::BasicBlock>,
243 ) -> InterpResult<'tcx> {
244 if ecx.emulate_intrinsic(span, instance, args, ret)? {
247 // An intrinsic that we do not support
248 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
249 Err(ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into())
253 ecx: &mut InterpCx<'mir, 'tcx, Self>,
255 msg: &AssertMessage<'tcx>,
256 _unwind: Option<mir::BasicBlock>,
257 ) -> InterpResult<'tcx> {
258 use rustc::mir::interpret::PanicInfo::*;
260 BoundsCheck { ref len, ref index } => {
262 .read_immediate(ecx.eval_operand(len, None)?)
263 .expect("can't eval len")
265 .to_machine_usize(&*ecx)?;
267 .read_immediate(ecx.eval_operand(index, None)?)
268 .expect("can't eval index")
270 .to_machine_usize(&*ecx)?;
271 err_panic!(BoundsCheck { len, index })
273 Overflow(op) => err_panic!(Overflow(*op)),
274 OverflowNeg => err_panic!(OverflowNeg),
275 DivisionByZero => err_panic!(DivisionByZero),
276 RemainderByZero => err_panic!(RemainderByZero),
277 ResumedAfterReturn(generator_kind) => err_panic!(ResumedAfterReturn(*generator_kind)),
278 ResumedAfterPanic(generator_kind) => err_panic!(ResumedAfterPanic(*generator_kind)),
279 Panic { .. } => bug!("`Panic` variant cannot occur in MIR"),
284 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
285 Err(ConstEvalError::NeedsRfc("pointer-to-integer cast".to_string()).into())
289 _ecx: &InterpCx<'mir, 'tcx, Self>,
293 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
294 Err(ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into())
297 fn find_foreign_static(
300 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
301 throw_unsup!(ReadForeignStatic)
305 fn init_allocation_extra<'b>(
306 _memory_extra: &MemoryExtra,
308 alloc: Cow<'b, Allocation>,
309 _kind: Option<MemoryKind<!>>,
310 ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
311 // We do not use a tag so we can just cheaply forward the allocation
316 fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag {
321 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
322 _dest: PlaceTy<'tcx>,
323 ) -> InterpResult<'tcx> {
324 Err(ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into())
327 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
329 let steps = &mut ecx.machine.steps_since_detector_enabled;
336 *steps %= DETECTOR_SNAPSHOT_PERIOD;
342 let span = ecx.frame().span;
343 ecx.machine.loop_detector.observe_and_analyze(*ecx.tcx, span, &ecx.memory, &ecx.stack[..])
347 fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
351 fn before_access_static(
352 memory_extra: &MemoryExtra,
353 _allocation: &Allocation,
354 ) -> InterpResult<'tcx> {
355 if memory_extra.can_access_statics {
358 Err(ConstEvalError::ConstAccessesStatic.into())
363 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
364 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
365 // at the bottom of this file.