]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval.rs
`find_fn` -> `find_mir_or_eval_fn` rename
[rust.git] / src / librustc_mir / const_eval.rs
1 // Not in interpret to make sure we do not use private implementation details
2
3 use std::fmt;
4 use std::error::Error;
5 use std::borrow::{Borrow, Cow};
6 use std::hash::Hash;
7 use std::collections::hash_map::Entry;
8 use std::convert::TryInto;
9
10 use rustc::hir::def::DefKind;
11 use rustc::hir::def_id::DefId;
12 use rustc::middle::lang_items::PanicLocationLangItem;
13 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled, ScalarMaybeUndef};
14 use rustc::mir;
15 use rustc::ty::{self, Ty, TyCtxt, subst::Subst};
16 use rustc::ty::layout::{self, LayoutOf, VariantIdx};
17 use rustc::traits::Reveal;
18 use rustc_data_structures::fx::FxHashMap;
19 use crate::interpret::eval_nullary_intrinsic;
20
21 use syntax::{source_map::{Span, DUMMY_SP}, symbol::Symbol};
22
23 use crate::interpret::{self,
24     PlaceTy, MPlaceTy, OpTy, ImmTy, Immediate, Scalar, Pointer,
25     RawConst, ConstValue, Machine,
26     InterpResult, InterpErrorInfo, GlobalId, InterpCx, StackPopCleanup,
27     Allocation, AllocId, MemoryKind, Memory,
28     snapshot, RefTracking, intern_const_alloc_recursive,
29 };
30
31 /// Number of steps until the detector even starts doing anything.
32 /// Also, a warning is shown to the user when this number is reached.
33 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
34 /// The number of steps between loop detector snapshots.
35 /// Should be a power of two for performance reasons.
36 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
37
38 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
39 /// `simd_shuffle` and const patterns in match arms.
40 ///
41 /// The function containing the `match` that is currently being analyzed may have generic bounds
42 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
43 /// of a function's generic parameter will require knowledge about the bounds on the generic
44 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
45 fn mk_eval_cx<'mir, 'tcx>(
46     tcx: TyCtxt<'tcx>,
47     span: Span,
48     param_env: ty::ParamEnv<'tcx>,
49 ) -> CompileTimeEvalContext<'mir, 'tcx> {
50     debug!("mk_eval_cx: {:?}", param_env);
51     InterpCx::new(tcx.at(span), param_env, CompileTimeInterpreter::new(), Default::default())
52 }
53
54 fn op_to_const<'tcx>(
55     ecx: &CompileTimeEvalContext<'_, 'tcx>,
56     op: OpTy<'tcx>,
57 ) -> &'tcx ty::Const<'tcx> {
58     // We do not have value optimizations for everything.
59     // Only scalars and slices, since they are very common.
60     // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result
61     // from scalar unions that are initialized with one of their zero sized variants. We could
62     // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all
63     // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
64     // `Undef` situation.
65     let try_as_immediate = match op.layout.abi {
66         layout::Abi::Scalar(..) => true,
67         layout::Abi::ScalarPair(..) => match op.layout.ty.kind {
68             ty::Ref(_, inner, _) => match inner.kind {
69                 ty::Slice(elem) => elem == ecx.tcx.types.u8,
70                 ty::Str => true,
71                 _ => false,
72             },
73             _ => false,
74         },
75         _ => false,
76     };
77     let immediate = if try_as_immediate {
78         Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
79     } else {
80         // It is guaranteed that any non-slice scalar pair is actually ByRef here.
81         // When we come back from raw const eval, we are always by-ref. The only way our op here is
82         // by-val is if we are in const_field, i.e., if this is (a field of) something that we
83         // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
84         // structs containing such.
85         op.try_as_mplace()
86     };
87     let val = match immediate {
88         Ok(mplace) => {
89             let ptr = mplace.ptr.to_ptr().unwrap();
90             let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
91             ConstValue::ByRef { alloc, offset: ptr.offset }
92         },
93         // see comment on `let try_as_immediate` above
94         Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x {
95             ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s),
96             ScalarMaybeUndef::Undef => {
97                 // When coming out of "normal CTFE", we'll always have an `Indirect` operand as
98                 // argument and we will not need this. The only way we can already have an
99                 // `Immediate` is when we are called from `const_field`, and that `Immediate`
100                 // comes from a constant so it can happen have `Undef`, because the indirect
101                 // memory that was read had undefined bytes.
102                 let mplace = op.assert_mem_place();
103                 let ptr = mplace.ptr.to_ptr().unwrap();
104                 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
105                 ConstValue::ByRef { alloc, offset: ptr.offset }
106             },
107         },
108         Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => {
109             let (data, start) = match a.not_undef().unwrap() {
110                 Scalar::Ptr(ptr) => (
111                     ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
112                     ptr.offset.bytes(),
113                 ),
114                 Scalar::Raw { .. } => (
115                     ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(
116                         b"" as &[u8],
117                     )),
118                     0,
119                 ),
120             };
121             let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap();
122             let start = start.try_into().unwrap();
123             let len: usize = len.try_into().unwrap();
124             ConstValue::Slice {
125                 data,
126                 start,
127                 end: start + len,
128             }
129         },
130     };
131     ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty })
132 }
133
134 // Returns a pointer to where the result lives
135 fn eval_body_using_ecx<'mir, 'tcx>(
136     ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
137     cid: GlobalId<'tcx>,
138     body: &'mir mir::Body<'tcx>,
139 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
140     debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
141     let tcx = ecx.tcx.tcx;
142     let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
143     assert!(!layout.is_unsized());
144     let ret = ecx.allocate(layout, MemoryKind::Stack);
145
146     let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
147     let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
148     trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
149
150     // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
151     // make sense if the body is expecting nontrivial arguments.
152     // (The alternative would be to use `eval_fn_call` with an args slice.)
153     for arg in body.args_iter() {
154         let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
155         let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
156         assert!(layout.is_zst())
157     };
158
159     ecx.push_stack_frame(
160         cid.instance,
161         body.span,
162         body,
163         Some(ret.into()),
164         StackPopCleanup::None { cleanup: false },
165     )?;
166
167     // The main interpreter loop.
168     ecx.run()?;
169
170     // Intern the result
171     intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?;
172
173     debug!("eval_body_using_ecx done: {:?}", *ret);
174     Ok(ret)
175 }
176
177 #[derive(Clone, Debug)]
178 pub enum ConstEvalError {
179     NeedsRfc(String),
180 }
181
182 impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalError {
183     fn into(self) -> InterpErrorInfo<'tcx> {
184         err_unsup!(Unsupported(self.to_string())).into()
185     }
186 }
187
188 impl fmt::Display for ConstEvalError {
189     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190         use self::ConstEvalError::*;
191         match *self {
192             NeedsRfc(ref msg) => {
193                 write!(
194                     f,
195                     "\"{}\" needs an rfc before being allowed inside constants",
196                     msg
197                 )
198             }
199         }
200     }
201 }
202
203 impl Error for ConstEvalError {
204     fn description(&self) -> &str {
205         use self::ConstEvalError::*;
206         match *self {
207             NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
208         }
209     }
210
211     fn cause(&self) -> Option<&dyn Error> {
212         None
213     }
214 }
215
216 // Extra machine state for CTFE, and the Machine instance
217 pub struct CompileTimeInterpreter<'mir, 'tcx> {
218     /// When this value is negative, it indicates the number of interpreter
219     /// steps *until* the loop detector is enabled. When it is positive, it is
220     /// the number of steps after the detector has been enabled modulo the loop
221     /// detector period.
222     pub(super) steps_since_detector_enabled: isize,
223
224     /// Extra state to detect loops.
225     pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>,
226 }
227
228 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
229     fn new() -> Self {
230         CompileTimeInterpreter {
231             loop_detector: Default::default(),
232             steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
233         }
234     }
235 }
236
237 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
238     #[inline(always)]
239     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
240         where K: Borrow<Q>
241     {
242         FxHashMap::contains_key(self, k)
243     }
244
245     #[inline(always)]
246     fn insert(&mut self, k: K, v: V) -> Option<V>
247     {
248         FxHashMap::insert(self, k, v)
249     }
250
251     #[inline(always)]
252     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
253         where K: Borrow<Q>
254     {
255         FxHashMap::remove(self, k)
256     }
257
258     #[inline(always)]
259     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
260         self.iter()
261             .filter_map(move |(k, v)| f(k, &*v))
262             .collect()
263     }
264
265     #[inline(always)]
266     fn get_or<E>(
267         &self,
268         k: K,
269         vacant: impl FnOnce() -> Result<V, E>
270     ) -> Result<&V, E>
271     {
272         match self.get(&k) {
273             Some(v) => Ok(v),
274             None => {
275                 vacant()?;
276                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
277             }
278         }
279     }
280
281     #[inline(always)]
282     fn get_mut_or<E>(
283         &mut self,
284         k: K,
285         vacant: impl FnOnce() -> Result<V, E>
286     ) -> Result<&mut V, E>
287     {
288         match self.entry(k) {
289             Entry::Occupied(e) => Ok(e.into_mut()),
290             Entry::Vacant(e) => {
291                 let v = vacant()?;
292                 Ok(e.insert(v))
293             }
294         }
295     }
296 }
297
298 crate type CompileTimeEvalContext<'mir, 'tcx> =
299     InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
300
301 impl interpret::MayLeak for ! {
302     #[inline(always)]
303     fn may_leak(self) -> bool {
304         // `self` is uninhabited
305         self
306     }
307 }
308
309 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
310     type MemoryKinds = !;
311     type PointerTag = ();
312     type ExtraFnVal = !;
313
314     type FrameExtra = ();
315     type MemoryExtra = ();
316     type AllocExtra = ();
317
318     type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
319
320     const STATIC_KIND: Option<!> = None; // no copying of statics allowed
321
322     // We do not check for alignment to avoid having to carry an `Align`
323     // in `ConstValue::ByRef`.
324     const CHECK_ALIGN: bool = false;
325
326     #[inline(always)]
327     fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
328         false // for now, we don't enforce validity
329     }
330
331     fn find_mir_or_eval_fn(
332         ecx: &mut InterpCx<'mir, 'tcx, Self>,
333         instance: ty::Instance<'tcx>,
334         args: &[OpTy<'tcx>],
335         ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
336         _unwind: Option<mir::BasicBlock> // unwinding is not supported in consts
337     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
338         debug!("find_mir_or_eval_fn: {:?}", instance);
339
340         // If this function is a `const fn` then as an optimization we can query this
341         // evaluation immediately.
342         //
343         // For the moment we only do this for functions which take no arguments
344         // (or all arguments are ZSTs) so that we don't memoize too much.
345         if ecx.tcx.is_const_fn_raw(instance.def.def_id()) &&
346             args.iter().all(|a| a.layout.is_zst())
347         {
348             let gid = GlobalId { instance, promoted: None };
349             ecx.eval_const_fn_call(gid, ret)?;
350             return Ok(None);
351         }
352
353         // Only check non-glue functions
354         if let ty::InstanceDef::Item(def_id) = instance.def {
355             // Execution might have wandered off into other crates, so we cannot do a stability-
356             // sensitive check here.  But we can at least rule out functions that are not const
357             // at all.
358             if !ecx.tcx.is_const_fn_raw(def_id) {
359                 // Some functions we support even if they are non-const -- but avoid testing
360                 // that for const fn!  We certainly do *not* want to actually call the fn
361                 // though, so be sure we return here.
362                 return if ecx.hook_panic_fn(instance, args, ret)? {
363                     Ok(None)
364                 } else {
365                     throw_unsup_format!("calling non-const function `{}`", instance)
366                 };
367             }
368         }
369         // This is a const fn. Call it.
370         Ok(Some(match ecx.load_mir(instance.def, None) {
371             Ok(body) => body,
372             Err(err) => {
373                 if let err_unsup!(NoMirFor(ref path)) = err.kind {
374                     return Err(
375                         ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
376                             .into(),
377                     );
378                 }
379                 return Err(err);
380             }
381         }))
382     }
383
384     fn call_extra_fn(
385         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
386         fn_val: !,
387         _args: &[OpTy<'tcx>],
388         _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
389         _unwind: Option<mir::BasicBlock>
390     ) -> InterpResult<'tcx> {
391         match fn_val {}
392     }
393
394     fn call_intrinsic(
395         ecx: &mut InterpCx<'mir, 'tcx, Self>,
396         span: Span,
397         instance: ty::Instance<'tcx>,
398         args: &[OpTy<'tcx>],
399         ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
400         _unwind: Option<mir::BasicBlock>
401     ) -> InterpResult<'tcx> {
402         if ecx.emulate_intrinsic(span, instance, args, ret)? {
403             return Ok(());
404         }
405         // An intrinsic that we do not support
406         let intrinsic_name = ecx.tcx.item_name(instance.def_id());
407         Err(
408             ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
409         )
410     }
411
412     fn ptr_to_int(
413         _mem: &Memory<'mir, 'tcx, Self>,
414         _ptr: Pointer,
415     ) -> InterpResult<'tcx, u64> {
416         Err(
417             ConstEvalError::NeedsRfc("pointer-to-integer cast".to_string()).into(),
418         )
419     }
420
421     fn binary_ptr_op(
422         _ecx: &InterpCx<'mir, 'tcx, Self>,
423         _bin_op: mir::BinOp,
424         _left: ImmTy<'tcx>,
425         _right: ImmTy<'tcx>,
426     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
427         Err(
428             ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
429         )
430     }
431
432     fn find_foreign_static(
433         _tcx: TyCtxt<'tcx>,
434         _def_id: DefId,
435     ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
436         throw_unsup!(ReadForeignStatic)
437     }
438
439     #[inline(always)]
440     fn tag_allocation<'b>(
441         _memory_extra: &(),
442         _id: AllocId,
443         alloc: Cow<'b, Allocation>,
444         _kind: Option<MemoryKind<!>>,
445     ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
446         // We do not use a tag so we can just cheaply forward the allocation
447         (alloc, ())
448     }
449
450     #[inline(always)]
451     fn tag_static_base_pointer(
452         _memory_extra: &(),
453         _id: AllocId,
454     ) -> Self::PointerTag {
455         ()
456     }
457
458     fn box_alloc(
459         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
460         _dest: PlaceTy<'tcx>,
461     ) -> InterpResult<'tcx> {
462         Err(
463             ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
464         )
465     }
466
467     fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
468         {
469             let steps = &mut ecx.machine.steps_since_detector_enabled;
470
471             *steps += 1;
472             if *steps < 0 {
473                 return Ok(());
474             }
475
476             *steps %= DETECTOR_SNAPSHOT_PERIOD;
477             if *steps != 0 {
478                 return Ok(());
479             }
480         }
481
482         let span = ecx.frame().span;
483         ecx.machine.loop_detector.observe_and_analyze(
484             *ecx.tcx,
485             span,
486             &ecx.memory,
487             &ecx.stack[..],
488         )
489     }
490
491     #[inline(always)]
492     fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
493         Ok(())
494     }
495 }
496
497 /// Extracts a field of a (variant of a) const.
498 // this function uses `unwrap` copiously, because an already validated constant must have valid
499 // fields and can thus never fail outside of compiler bugs
500 pub fn const_field<'tcx>(
501     tcx: TyCtxt<'tcx>,
502     param_env: ty::ParamEnv<'tcx>,
503     variant: Option<VariantIdx>,
504     field: mir::Field,
505     value: &'tcx ty::Const<'tcx>,
506 ) -> &'tcx ty::Const<'tcx> {
507     trace!("const_field: {:?}, {:?}", field, value);
508     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
509     // get the operand again
510     let op = ecx.eval_const_to_op(value, None).unwrap();
511     // downcast
512     let down = match variant {
513         None => op,
514         Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
515     };
516     // then project
517     let field = ecx.operand_field(down, field.index() as u64).unwrap();
518     // and finally move back to the const world, always normalizing because
519     // this is not called for statics.
520     op_to_const(&ecx, field)
521 }
522
523 pub fn const_caller_location<'tcx>(
524     tcx: TyCtxt<'tcx>,
525     (file, line, col): (Symbol, u32, u32),
526 ) -> &'tcx ty::Const<'tcx> {
527     trace!("const_caller_location: {}:{}:{}", file, line, col);
528     let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all());
529
530     let loc_ty = tcx.mk_imm_ref(
531         tcx.lifetimes.re_static,
532         tcx.type_of(tcx.require_lang_item(PanicLocationLangItem, None))
533             .subst(tcx, tcx.mk_substs([tcx.lifetimes.re_static.into()].iter())),
534     );
535     let loc_place = ecx.alloc_caller_location(file, line, col).unwrap();
536     intern_const_alloc_recursive(&mut ecx, None, loc_place).unwrap();
537     let loc_const = ty::Const {
538         ty: loc_ty,
539         val: ty::ConstKind::Value(ConstValue::Scalar(loc_place.ptr.into())),
540     };
541
542     tcx.mk_const(loc_const)
543 }
544
545 // this function uses `unwrap` copiously, because an already validated constant must have valid
546 // fields and can thus never fail outside of compiler bugs
547 pub fn const_variant_index<'tcx>(
548     tcx: TyCtxt<'tcx>,
549     param_env: ty::ParamEnv<'tcx>,
550     val: &'tcx ty::Const<'tcx>,
551 ) -> VariantIdx {
552     trace!("const_variant_index: {:?}", val);
553     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
554     let op = ecx.eval_const_to_op(val, None).unwrap();
555     ecx.read_discriminant(op).unwrap().1
556 }
557
558 /// Turn an interpreter error into something to report to the user.
559 /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace.
560 /// Should be called only if the error is actually going to to be reported!
561 pub fn error_to_const_error<'mir, 'tcx, M: Machine<'mir, 'tcx>>(
562     ecx: &InterpCx<'mir, 'tcx, M>,
563     mut error: InterpErrorInfo<'tcx>,
564 ) -> ConstEvalErr<'tcx> {
565     error.print_backtrace();
566     let stacktrace = ecx.generate_stacktrace(None);
567     ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
568 }
569
570 pub fn note_on_undefined_behavior_error() -> &'static str {
571     "The rules on what exactly is undefined behavior aren't clear, \
572      so this check might be overzealous. Please open an issue on the rustc \
573      repository if you believe it should not be considered undefined behavior."
574 }
575
576 fn validate_and_turn_into_const<'tcx>(
577     tcx: TyCtxt<'tcx>,
578     constant: RawConst<'tcx>,
579     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
580 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
581     let cid = key.value;
582     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
583     let val = (|| {
584         let mplace = ecx.raw_const_to_mplace(constant)?;
585         let mut ref_tracking = RefTracking::new(mplace);
586         while let Some((mplace, path)) = ref_tracking.todo.pop() {
587             ecx.validate_operand(
588                 mplace.into(),
589                 path,
590                 Some(&mut ref_tracking),
591             )?;
592         }
593         // Now that we validated, turn this into a proper constant.
594         // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
595         // whether they become immediates.
596         let def_id = cid.instance.def.def_id();
597         if tcx.is_static(def_id) || cid.promoted.is_some() {
598             let ptr = mplace.ptr.to_ptr()?;
599             Ok(tcx.mk_const(ty::Const {
600                 val: ty::ConstKind::Value(ConstValue::ByRef {
601                     alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
602                     offset: ptr.offset,
603                 }),
604                 ty: mplace.layout.ty,
605             }))
606         } else {
607             Ok(op_to_const(&ecx, mplace.into()))
608         }
609     })();
610
611     val.map_err(|error| {
612         let err = error_to_const_error(&ecx, error);
613         match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
614             Ok(mut diag) => {
615                 diag.note(note_on_undefined_behavior_error());
616                 diag.emit();
617                 ErrorHandled::Reported
618             }
619             Err(err) => err,
620         }
621     })
622 }
623
624 pub fn const_eval_provider<'tcx>(
625     tcx: TyCtxt<'tcx>,
626     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
627 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
628     // see comment in const_eval_raw_provider for what we're doing here
629     if key.param_env.reveal == Reveal::All {
630         let mut key = key.clone();
631         key.param_env.reveal = Reveal::UserFacing;
632         match tcx.const_eval(key) {
633             // try again with reveal all as requested
634             Err(ErrorHandled::TooGeneric) => {
635                 // Promoteds should never be "too generic" when getting evaluated.
636                 // They either don't get evaluated, or we are in a monomorphic context
637                 assert!(key.value.promoted.is_none());
638             },
639             // dedupliate calls
640             other => return other,
641         }
642     }
643
644     // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
645     // Catch such calls and evaluate them instead of trying to load a constant's MIR.
646     if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
647         let ty = key.value.instance.ty(tcx);
648         let substs = match ty.kind {
649             ty::FnDef(_, substs) => substs,
650             _ => bug!("intrinsic with type {:?}", ty),
651         };
652         return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs)
653             .map_err(|error| {
654                 let span = tcx.def_span(def_id);
655                 let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
656                 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
657             })
658     }
659
660     tcx.const_eval_raw(key).and_then(|val| {
661         validate_and_turn_into_const(tcx, val, key)
662     })
663 }
664
665 pub fn const_eval_raw_provider<'tcx>(
666     tcx: TyCtxt<'tcx>,
667     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
668 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
669     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
670     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
671     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
672     // computed. For a large percentage of constants that will already have succeeded. Only
673     // associated constants of generic functions will fail due to not enough monomorphization
674     // information being available.
675
676     // In case we fail in the `UserFacing` variant, we just do the real computation.
677     if key.param_env.reveal == Reveal::All {
678         let mut key = key.clone();
679         key.param_env.reveal = Reveal::UserFacing;
680         match tcx.const_eval_raw(key) {
681             // try again with reveal all as requested
682             Err(ErrorHandled::TooGeneric) => {},
683             // dedupliate calls
684             other => return other,
685         }
686     }
687     if cfg!(debug_assertions) {
688         // Make sure we format the instance even if we do not print it.
689         // This serves as a regression test against an ICE on printing.
690         // The next two lines concatenated contain some discussion:
691         // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
692         // subject/anon_const_instance_printing/near/135980032
693         let instance = key.value.instance.to_string();
694         trace!("const eval: {:?} ({})", key, instance);
695     }
696
697     let cid = key.value;
698     let def_id = cid.instance.def.def_id();
699
700     if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
701         return Err(ErrorHandled::Reported);
702     }
703
704     let span = tcx.def_span(cid.instance.def_id());
705     let mut ecx = InterpCx::new(
706         tcx.at(span),
707         key.param_env,
708         CompileTimeInterpreter::new(),
709         Default::default()
710     );
711
712     let res = ecx.load_mir(cid.instance.def, cid.promoted);
713     res.and_then(
714         |body| eval_body_using_ecx(&mut ecx, cid, body)
715     ).and_then(|place| {
716         Ok(RawConst {
717             alloc_id: place.ptr.assert_ptr().alloc_id,
718             ty: place.layout.ty
719         })
720     }).map_err(|error| {
721         let err = error_to_const_error(&ecx, error);
722         // errors in statics are always emitted as fatal errors
723         if tcx.is_static(def_id) {
724             // Ensure that if the above error was either `TooGeneric` or `Reported`
725             // an error must be reported.
726             let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer");
727             tcx.sess.delay_span_bug(
728                 err.span,
729                 &format!("static eval failure did not emit an error: {:#?}", v)
730             );
731             v
732         } else if def_id.is_local() {
733             // constant defined in this crate, we can figure out a lint level!
734             match tcx.def_kind(def_id) {
735                 // constants never produce a hard error at the definition site. Anything else is
736                 // a backwards compatibility hazard (and will break old versions of winapi for sure)
737                 //
738                 // note that validation may still cause a hard error on this very same constant,
739                 // because any code that existed before validation could not have failed validation
740                 // thus preventing such a hard error from being a backwards compatibility hazard
741                 Some(DefKind::Const) | Some(DefKind::AssocConst) => {
742                     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
743                     err.report_as_lint(
744                         tcx.at(tcx.def_span(def_id)),
745                         "any use of this value will cause an error",
746                         hir_id,
747                         Some(err.span),
748                     )
749                 },
750                 // promoting runtime code is only allowed to error if it references broken constants
751                 // any other kind of error will be reported to the user as a deny-by-default lint
752                 _ => if let Some(p) = cid.promoted {
753                     let span = tcx.promoted_mir(def_id)[p].span;
754                     if let err_inval!(ReferencedConstant) = err.error {
755                         err.report_as_error(
756                             tcx.at(span),
757                             "evaluation of constant expression failed",
758                         )
759                     } else {
760                         err.report_as_lint(
761                             tcx.at(span),
762                             "reaching this expression at runtime will panic or abort",
763                             tcx.hir().as_local_hir_id(def_id).unwrap(),
764                             Some(err.span),
765                         )
766                     }
767                 // anything else (array lengths, enum initializers, constant patterns) are reported
768                 // as hard errors
769                 } else {
770                     err.report_as_error(
771                         ecx.tcx,
772                         "evaluation of constant value failed",
773                     )
774                 },
775             }
776         } else {
777             // use of broken constant from other crate
778             err.report_as_error(ecx.tcx, "could not evaluate constant")
779         }
780     })
781 }