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::mir::AssertMessage;
12 use rustc_span::source_map::Span;
13 use rustc_span::symbol::Symbol;
15 use crate::interpret::{
16 self, snapshot, AllocId, Allocation, GlobalId, ImmTy, InterpCx, InterpResult, Memory,
17 MemoryKind, OpTy, PlaceTy, Pointer, Scalar,
22 impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> {
23 /// Evaluate a const function where all arguments (if any) are zero-sized types.
24 /// The evaluation is memoized thanks to the query system.
26 /// Returns `true` if the call has been evaluated.
27 fn try_eval_const_fn_call(
29 instance: ty::Instance<'tcx>,
30 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
32 ) -> InterpResult<'tcx, bool> {
33 trace!("try_eval_const_fn_call: {:?}", instance);
34 // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot
35 // perform this optimization on items tagged with it.
36 if instance.def.requires_caller_location(self.tcx()) {
39 // For the moment we only do this for functions which take no arguments
40 // (or all arguments are ZSTs) so that we don't memoize too much.
41 if args.iter().any(|a| !a.layout.is_zst()) {
45 let dest = match ret {
46 Some((dest, _)) => dest,
47 // Don't memoize diverging function calls.
48 None => return Ok(false),
51 let gid = GlobalId { instance, promoted: None };
53 let place = self.const_eval_raw(gid)?;
55 self.copy_op(place.into(), dest)?;
57 self.return_to_block(ret.map(|r| r.1))?;
58 self.dump_place(*dest);
62 /// "Intercept" a function call to a panic-related function
63 /// because we have something special to do for it.
64 /// If this returns successfully (`Ok`), the function should just be evaluated normally.
68 instance: ty::Instance<'tcx>,
70 ) -> InterpResult<'tcx> {
71 let def_id = instance.def_id();
72 if Some(def_id) == self.tcx.lang_items().panic_fn()
73 || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
76 assert!(args.len() == 1);
78 let msg_place = self.deref_operand(args[0])?;
79 let msg = Symbol::intern(self.read_str(msg_place)?);
80 let span = self.find_closest_untracked_caller_location().unwrap_or(span);
81 let (file, line, col) = self.location_triple_for_span(span);
82 Err(ConstEvalErrKind::Panic { msg, file, line, col }.into())
89 /// Number of steps until the detector even starts doing anything.
90 /// Also, a warning is shown to the user when this number is reached.
91 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
92 /// The number of steps between loop detector snapshots.
93 /// Should be a power of two for performance reasons.
94 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
96 // Extra machine state for CTFE, and the Machine instance
97 pub struct CompileTimeInterpreter<'mir, 'tcx> {
98 /// When this value is negative, it indicates the number of interpreter
99 /// steps *until* the loop detector is enabled. When it is positive, it is
100 /// the number of steps after the detector has been enabled modulo the loop
102 pub(super) steps_since_detector_enabled: isize,
104 /// Extra state to detect loops.
105 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>,
108 #[derive(Copy, Clone, Debug)]
109 pub struct MemoryExtra {
110 /// Whether this machine may read from statics
111 pub(super) can_access_statics: bool,
114 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
115 pub(super) fn new() -> Self {
116 CompileTimeInterpreter {
117 loop_detector: Default::default(),
118 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
123 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
125 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
129 FxHashMap::contains_key(self, k)
133 fn insert(&mut self, k: K, v: V) -> Option<V> {
134 FxHashMap::insert(self, k, v)
138 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
142 FxHashMap::remove(self, k)
146 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
147 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
151 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
156 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
162 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
163 match self.entry(k) {
164 Entry::Occupied(e) => Ok(e.into_mut()),
165 Entry::Vacant(e) => {
173 crate type CompileTimeEvalContext<'mir, 'tcx> =
174 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
176 impl interpret::MayLeak for ! {
178 fn may_leak(self) -> bool {
179 // `self` is uninhabited
184 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
185 type MemoryKinds = !;
186 type PointerTag = ();
189 type FrameExtra = ();
190 type MemoryExtra = MemoryExtra;
191 type AllocExtra = ();
193 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
195 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
197 // We do not check for alignment to avoid having to carry an `Align`
198 // in `ConstValue::ByRef`.
199 const CHECK_ALIGN: bool = false;
202 fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
203 false // for now, we don't enforce validity
206 fn find_mir_or_eval_fn(
207 ecx: &mut InterpCx<'mir, 'tcx, Self>,
209 instance: ty::Instance<'tcx>,
211 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
212 _unwind: Option<mir::BasicBlock>, // unwinding is not supported in consts
213 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
214 debug!("find_mir_or_eval_fn: {:?}", instance);
216 // Only check non-glue functions
217 if let ty::InstanceDef::Item(def_id) = instance.def {
218 // Execution might have wandered off into other crates, so we cannot do a stability-
219 // sensitive check here. But we can at least rule out functions that are not const
221 if ecx.tcx.is_const_fn_raw(def_id) {
222 // If this function is a `const fn` then under certain circumstances we
223 // can evaluate call via the query system, thus memoizing all future calls.
224 if ecx.try_eval_const_fn_call(instance, ret, args)? {
228 // Some functions we support even if they are non-const -- but avoid testing
229 // that for const fn!
230 ecx.hook_panic_fn(span, instance, args)?;
231 // We certainly do *not* want to actually call the fn
232 // though, so be sure we return here.
233 throw_unsup_format!("calling non-const function `{}`", instance)
236 // This is a const fn. Call it.
237 Ok(Some(match ecx.load_mir(instance.def, None) {
240 if let err_unsup!(NoMirFor(ref path)) = err.kind {
241 return Err(ConstEvalErrKind::NeedsRfc(format!(
242 "calling extern function `{}`",
253 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
255 _args: &[OpTy<'tcx>],
256 _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
257 _unwind: Option<mir::BasicBlock>,
258 ) -> InterpResult<'tcx> {
263 ecx: &mut InterpCx<'mir, 'tcx, Self>,
265 instance: ty::Instance<'tcx>,
267 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
268 _unwind: Option<mir::BasicBlock>,
269 ) -> InterpResult<'tcx> {
270 if ecx.emulate_intrinsic(span, instance, args, ret)? {
273 // An intrinsic that we do not support
274 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
275 Err(ConstEvalErrKind::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into())
279 ecx: &mut InterpCx<'mir, 'tcx, Self>,
281 msg: &AssertMessage<'tcx>,
282 _unwind: Option<mir::BasicBlock>,
283 ) -> InterpResult<'tcx> {
284 use rustc::mir::AssertKind::*;
285 // Convert `AssertKind<Operand>` to `AssertKind<u64>`.
286 let err = match msg {
287 BoundsCheck { ref len, ref index } => {
289 .read_immediate(ecx.eval_operand(len, None)?)
290 .expect("can't eval len")
292 .to_machine_usize(&*ecx)?;
294 .read_immediate(ecx.eval_operand(index, None)?)
295 .expect("can't eval index")
297 .to_machine_usize(&*ecx)?;
298 BoundsCheck { len, index }
300 Overflow(op) => Overflow(*op),
301 OverflowNeg => OverflowNeg,
302 DivisionByZero => DivisionByZero,
303 RemainderByZero => RemainderByZero,
304 ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
305 ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
307 Err(ConstEvalErrKind::AssertFailure(err).into())
310 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
311 Err(ConstEvalErrKind::NeedsRfc("pointer-to-integer cast".to_string()).into())
315 _ecx: &InterpCx<'mir, 'tcx, Self>,
319 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
320 Err(ConstEvalErrKind::NeedsRfc("pointer arithmetic or comparison".to_string()).into())
323 fn find_foreign_static(
326 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
327 throw_unsup!(ReadForeignStatic)
331 fn init_allocation_extra<'b>(
332 _memory_extra: &MemoryExtra,
334 alloc: Cow<'b, Allocation>,
335 _kind: Option<MemoryKind<!>>,
336 ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
337 // We do not use a tag so we can just cheaply forward the allocation
342 fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag {
347 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
348 _dest: PlaceTy<'tcx>,
349 ) -> InterpResult<'tcx> {
350 Err(ConstEvalErrKind::NeedsRfc("heap allocations via `box` keyword".to_string()).into())
353 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
355 let steps = &mut ecx.machine.steps_since_detector_enabled;
362 *steps %= DETECTOR_SNAPSHOT_PERIOD;
368 let span = ecx.frame().span;
369 ecx.machine.loop_detector.observe_and_analyze(*ecx.tcx, span, &ecx.memory, &ecx.stack[..])
373 fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
377 fn before_access_static(
378 memory_extra: &MemoryExtra,
379 _allocation: &Allocation,
380 ) -> InterpResult<'tcx> {
381 if memory_extra.can_access_statics {
384 Err(ConstEvalErrKind::ConstAccessesStatic.into())
389 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
390 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
391 // at the bottom of this file.