]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_consts/validation.rs
824ec36e275e46e32da50ac1a2a4afe96f6f5d57
[rust.git] / src / librustc_mir / transform / check_consts / validation.rs
1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
2
3 use rustc::hir::{HirId, def_id::DefId};
4 use rustc::middle::lang_items;
5 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
6 use rustc::mir::*;
7 use rustc::traits::{self, TraitEngine};
8 use rustc::ty::cast::CastTy;
9 use rustc::ty::{self, TyCtxt};
10 use rustc_index::bit_set::BitSet;
11 use rustc_target::spec::abi::Abi;
12 use rustc_error_codes::*;
13 use syntax::symbol::sym;
14 use syntax_pos::Span;
15
16 use std::borrow::Cow;
17 use std::ops::Deref;
18
19 use crate::dataflow::{self as old_dataflow, generic as dataflow};
20 use self::old_dataflow::IndirectlyMutableLocals;
21 use super::ops::{self, NonConstOp};
22 use super::qualifs::{self, HasMutInterior, NeedsDrop};
23 use super::resolver::FlowSensitiveAnalysis;
24 use super::{ConstKind, Item, Qualif, is_lang_panic_fn};
25
26 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
27 pub enum CheckOpResult {
28     Forbidden,
29     Unleashed,
30     Allowed,
31 }
32
33 pub type IndirectlyMutableResults<'mir, 'tcx> =
34     old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
35
36 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
37     cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
38     in_any_value_of_ty: BitSet<Local>,
39 }
40
41 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
42     pub fn new(
43         q: Q,
44         item: &'a Item<'mir, 'tcx>,
45         dead_unwinds: &BitSet<BasicBlock>,
46     ) -> Self {
47         let analysis = FlowSensitiveAnalysis::new(q, item);
48         let results =
49             dataflow::Engine::new(item.tcx, item.body, item.def_id, dead_unwinds, analysis)
50                 .iterate_to_fixpoint();
51         let cursor = dataflow::ResultsCursor::new(item.body, results);
52
53         let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
54         for (local, decl) in item.body.local_decls.iter_enumerated() {
55             if Q::in_any_value_of_ty(item, decl.ty) {
56                 in_any_value_of_ty.insert(local);
57             }
58         }
59
60         QualifCursor {
61             cursor,
62             in_any_value_of_ty,
63         }
64     }
65 }
66
67 pub struct Qualifs<'a, 'mir, 'tcx> {
68     has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
69     needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
70     indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
71 }
72
73 impl Qualifs<'a, 'mir, 'tcx> {
74     fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
75         self.indirectly_mutable.seek(location);
76         self.indirectly_mutable.get().contains(local)
77     }
78
79     /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
80     ///
81     /// Only updates the cursor if absolutely necessary
82     fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
83         if !self.needs_drop.in_any_value_of_ty.contains(local) {
84             return false;
85         }
86
87         self.needs_drop.cursor.seek_before(location);
88         self.needs_drop.cursor.get().contains(local)
89             || self.indirectly_mutable(local, location)
90     }
91
92     /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
93     ///
94     /// Only updates the cursor if absolutely necessary.
95     fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
96         if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
97             return false;
98         }
99
100         self.has_mut_interior.cursor.seek_before(location);
101         self.has_mut_interior.cursor.get().contains(local)
102             || self.indirectly_mutable(local, location)
103     }
104
105     /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
106     /// `indirectly_mutable` cursors to be updated beforehand.
107     fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
108         if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
109             return false;
110         }
111
112         self.has_mut_interior.cursor.get().contains(local)
113             || self.indirectly_mutable.get().contains(local)
114     }
115
116     fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
117         // Find the `Return` terminator if one exists.
118         //
119         // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
120         // qualifs for the return type.
121         let return_block = item.body
122             .basic_blocks()
123             .iter_enumerated()
124             .find(|(_, block)| {
125                 match block.terminator().kind {
126                     TerminatorKind::Return => true,
127                     _ => false,
128                 }
129             })
130             .map(|(bb, _)| bb);
131
132         let return_block = match return_block {
133             None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
134             Some(bb) => bb,
135         };
136
137         let return_loc = item.body.terminator_loc(return_block);
138
139         ConstQualifs {
140             needs_drop: self.needs_drop_lazy_seek(RETURN_PLACE, return_loc),
141             has_mut_interior: self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc),
142         }
143     }
144 }
145
146 pub struct Validator<'a, 'mir, 'tcx> {
147     item: &'a Item<'mir, 'tcx>,
148     qualifs: Qualifs<'a, 'mir, 'tcx>,
149
150     /// The span of the current statement.
151     span: Span,
152
153     /// True if the local was assigned the result of an illegal borrow (`ops::MutBorrow`).
154     ///
155     /// This is used to hide errors from {re,}borrowing the newly-assigned local, instead pointing
156     /// the user to the place where the illegal borrow occurred. This set is only populated once an
157     /// error has been emitted, so it will never cause an erroneous `mir::Body` to pass validation.
158     ///
159     /// FIXME(ecstaticmorse): assert at the end of checking that if `tcx.has_errors() == false`,
160     /// this set is empty. Note that if we start removing locals from
161     /// `derived_from_illegal_borrow`, just checking at the end won't be enough.
162     derived_from_illegal_borrow: BitSet<Local>,
163 }
164
165 impl Deref for Validator<'_, 'mir, 'tcx> {
166     type Target = Item<'mir, 'tcx>;
167
168     fn deref(&self) -> &Self::Target {
169         &self.item
170     }
171 }
172
173 impl Validator<'a, 'mir, 'tcx> {
174     pub fn new(
175         item: &'a Item<'mir, 'tcx>,
176     ) -> Self {
177         let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
178
179         let needs_drop = QualifCursor::new(
180             NeedsDrop,
181             item,
182             &dead_unwinds,
183         );
184
185         let has_mut_interior = QualifCursor::new(
186             HasMutInterior,
187             item,
188             &dead_unwinds,
189         );
190
191         let indirectly_mutable = old_dataflow::do_dataflow(
192             item.tcx,
193             item.body,
194             item.def_id,
195             &item.tcx.get_attrs(item.def_id),
196             &dead_unwinds,
197             old_dataflow::IndirectlyMutableLocals::new(item.tcx, item.body, item.param_env),
198             |_, local| old_dataflow::DebugFormatted::new(&local),
199         );
200
201         let indirectly_mutable = old_dataflow::DataflowResultsCursor::new(
202             indirectly_mutable,
203             item.body,
204         );
205
206         let qualifs = Qualifs {
207             needs_drop,
208             has_mut_interior,
209             indirectly_mutable,
210         };
211
212         Validator {
213             span: item.body.span,
214             item,
215             qualifs,
216             derived_from_illegal_borrow: BitSet::new_empty(item.body.local_decls.len()),
217         }
218     }
219
220     pub fn check_body(&mut self) {
221         let Item { tcx, body, def_id, const_kind, ..  } = *self.item;
222
223         let use_min_const_fn_checks =
224             tcx.is_min_const_fn(def_id)
225             && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
226
227         if use_min_const_fn_checks {
228             // Enforce `min_const_fn` for stable `const fn`s.
229             use crate::transform::qualify_min_const_fn::is_min_const_fn;
230             if let Err((span, err)) = is_min_const_fn(tcx, def_id, body) {
231                 error_min_const_fn_violation(tcx, span, err);
232                 return;
233             }
234         }
235
236         check_short_circuiting_in_const_local(self.item);
237
238         if body.is_cfg_cyclic() {
239             // We can't provide a good span for the error here, but this should be caught by the
240             // HIR const-checker anyways.
241             self.check_op_spanned(ops::Loop, body.span);
242         }
243
244         self.visit_body(body);
245
246         // Ensure that the end result is `Sync` in a non-thread local `static`.
247         let should_check_for_sync = const_kind == Some(ConstKind::Static)
248             && !tcx.has_attr(def_id, sym::thread_local);
249
250         if should_check_for_sync {
251             let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
252             check_return_ty_is_sync(tcx, body, hir_id);
253         }
254     }
255
256     pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
257         self.qualifs.in_return_place(self.item)
258     }
259
260     /// Emits an error at the given `span` if an expression cannot be evaluated in the current
261     /// context. Returns `Forbidden` if an error was emitted.
262     pub fn check_op_spanned<O>(&mut self, op: O, span: Span) -> CheckOpResult
263     where
264         O: NonConstOp
265     {
266         trace!("check_op: op={:?}", op);
267
268         if op.is_allowed_in_item(self) {
269             return CheckOpResult::Allowed;
270         }
271
272         // If an operation is supported in miri (and is not already controlled by a feature gate) it
273         // can be turned on with `-Zunleash-the-miri-inside-of-you`.
274         let is_unleashable = O::IS_SUPPORTED_IN_MIRI
275             && O::feature_gate(self.tcx).is_none();
276
277         if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
278             self.tcx.sess.span_warn(span, "skipping const checks");
279             return CheckOpResult::Unleashed;
280         }
281
282         op.emit_error(self, span);
283         CheckOpResult::Forbidden
284     }
285
286     /// Emits an error if an expression cannot be evaluated in the current context.
287     pub fn check_op(&mut self, op: impl NonConstOp) -> CheckOpResult {
288         let span = self.span;
289         self.check_op_spanned(op, span)
290     }
291
292     fn check_static(&mut self, def_id: DefId, span: Span) -> CheckOpResult {
293         let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
294         if is_thread_local {
295             self.check_op_spanned(ops::ThreadLocalAccess, span)
296         } else {
297             self.check_op_spanned(ops::StaticAccess, span)
298         }
299     }
300 }
301
302 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
303     fn visit_basic_block_data(
304         &mut self,
305         bb: BasicBlock,
306         block: &BasicBlockData<'tcx>,
307     ) {
308         trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
309
310         // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
311         // These blocks often drop locals that would otherwise be returned from the function.
312         //
313         // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
314         // error anyway, but maybe we should do more here?
315         if block.is_cleanup {
316             return;
317         }
318
319         self.super_basic_block_data(bb, block);
320     }
321
322     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
323         trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
324
325         // Special-case reborrows to be more like a copy of a reference.
326         if let Rvalue::Ref(_, kind, ref place) = *rvalue {
327             if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
328                 let ctx = match kind {
329                     BorrowKind::Shared => PlaceContext::NonMutatingUse(
330                         NonMutatingUseContext::SharedBorrow,
331                     ),
332                     BorrowKind::Shallow => PlaceContext::NonMutatingUse(
333                         NonMutatingUseContext::ShallowBorrow,
334                     ),
335                     BorrowKind::Unique => PlaceContext::NonMutatingUse(
336                         NonMutatingUseContext::UniqueBorrow,
337                     ),
338                     BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
339                         MutatingUseContext::Borrow,
340                     ),
341                 };
342                 self.visit_place_base(&place.base, ctx, location);
343                 self.visit_projection(&place.base, reborrowed_proj, ctx, location);
344                 return;
345             }
346         }
347
348         self.super_rvalue(rvalue, location);
349
350         match *rvalue {
351             Rvalue::Use(_) |
352             Rvalue::Repeat(..) |
353             Rvalue::UnaryOp(UnOp::Neg, _) |
354             Rvalue::UnaryOp(UnOp::Not, _) |
355             Rvalue::NullaryOp(NullOp::SizeOf, _) |
356             Rvalue::CheckedBinaryOp(..) |
357             Rvalue::Cast(CastKind::Pointer(_), ..) |
358             Rvalue::Discriminant(..) |
359             Rvalue::Len(_) |
360             Rvalue::Aggregate(..) => {}
361
362             | Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
363             | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place)
364             => {
365                 let ty = place.ty(self.body, self.tcx).ty;
366                 let is_allowed = match ty.kind {
367                     // Inside a `static mut`, `&mut [...]` is allowed.
368                     ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut
369                         => true,
370
371                     // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
372                     // that this is merely a ZST and it is already eligible for promotion.
373                     // This may require an RFC?
374                     /*
375                     ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
376                         => true,
377                     */
378
379                     _ => false,
380                 };
381
382                 if !is_allowed {
383                     self.check_op(ops::MutBorrow(kind));
384                 }
385             }
386
387             // Taking a shared borrow of a `static` is always legal, even if that `static` has
388             // interior mutability.
389             | Rvalue::Ref(_, BorrowKind::Shared, ref place)
390             | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
391             if matches!(place.base, PlaceBase::Static(_))
392             => {}
393
394             | Rvalue::Ref(_, kind @ BorrowKind::Shared, ref place)
395             | Rvalue::Ref(_, kind @ BorrowKind::Shallow, ref place)
396             => {
397                 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
398                 // seek the cursors beforehand.
399                 self.qualifs.has_mut_interior.cursor.seek_before(location);
400                 self.qualifs.indirectly_mutable.seek(location);
401
402                 let borrowed_place_has_mut_interior = HasMutInterior::in_place(
403                     &self.item,
404                     &|local| self.qualifs.has_mut_interior_eager_seek(local),
405                     place.as_ref(),
406                 );
407
408                 if borrowed_place_has_mut_interior {
409                     let src_derived_from_illegal_borrow = borrowed_place
410                         .as_local()
411                         .map_or(false, |local| self.derived_from_illegal_borrow.contains(local));
412
413                     // Don't emit errors for borrows of values that are *themselves* the result of
414                     // an illegal borrow (e.g., the outermost `&` in `&&Cell::new(42)`). We want to
415                     // point the user to the place where the original illegal borrow occurred, not
416                     // to subsequent borrows of the resulting value.
417                     let dest_derived_from_illegal_borrow = if !src_derived_from_illegal_borrow {
418                         self.check_op(ops::MutBorrow(kind)) == CheckOpResult::Forbidden
419                     } else {
420                         true
421                     };
422
423                     // When the target of the assignment is a local with no projections, it will be
424                     // marked as derived from an illegal borrow if necessary.
425                     //
426                     // FIXME: should we also clear `derived_from_illegal_borrow` when a local is
427                     // assigned a new value?
428
429                     if dest_derived_from_illegal_borrow {
430                         let block = &self.body[location.block];
431                         let statement = &block.statements[location.statement_index];
432                         if let StatementKind::Assign(box (dest, _)) = &statement.kind {
433                             if let Some(dest) = dest.as_local() {
434                                 self.derived_from_illegal_borrow.insert(dest);
435                             }
436                         }
437                     }
438                 }
439             }
440
441             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
442                 let operand_ty = operand.ty(self.body, self.tcx);
443                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
444                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
445
446                 if let (CastTy::Ptr(_), CastTy::Int(_))
447                      | (CastTy::FnPtr,  CastTy::Int(_)) = (cast_in, cast_out) {
448                     self.check_op(ops::RawPtrToIntCast);
449                 }
450             }
451
452             Rvalue::BinaryOp(op, ref lhs, _) => {
453                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
454                     assert!(op == BinOp::Eq || op == BinOp::Ne ||
455                             op == BinOp::Le || op == BinOp::Lt ||
456                             op == BinOp::Ge || op == BinOp::Gt ||
457                             op == BinOp::Offset);
458
459
460                     self.check_op(ops::RawPtrComparison);
461                 }
462             }
463
464             Rvalue::NullaryOp(NullOp::Box, _) => {
465                 self.check_op(ops::HeapAllocation);
466             }
467         }
468     }
469
470     fn visit_place_base(
471         &mut self,
472         place_base: &PlaceBase<'tcx>,
473         context: PlaceContext,
474         location: Location,
475     ) {
476         trace!(
477             "visit_place_base: place_base={:?} context={:?} location={:?}",
478             place_base,
479             context,
480             location,
481         );
482         self.super_place_base(place_base, context, location);
483
484         match place_base {
485             PlaceBase::Local(_) => {}
486             PlaceBase::Static(_) => {
487                 bug!("Promotion must be run after const validation");
488             }
489         }
490     }
491
492     fn visit_operand(
493         &mut self,
494         op: &Operand<'tcx>,
495         location: Location,
496     ) {
497         self.super_operand(op, location);
498         if let Operand::Constant(c) = op {
499             if let Some(def_id) = c.check_static_ptr(self.tcx) {
500                 self.check_static(def_id, self.span);
501             }
502         }
503     }
504
505     fn visit_projection_elem(
506         &mut self,
507         place_base: &PlaceBase<'tcx>,
508         proj_base: &[PlaceElem<'tcx>],
509         elem: &PlaceElem<'tcx>,
510         context: PlaceContext,
511         location: Location,
512     ) {
513         trace!(
514             "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
515             context={:?} location={:?}",
516             place_base,
517             proj_base,
518             elem,
519             context,
520             location,
521         );
522
523         self.super_projection_elem(place_base, proj_base, elem, context, location);
524
525         match elem {
526             ProjectionElem::Deref => {
527                 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
528                 if let ty::RawPtr(_) = base_ty.kind {
529                     if proj_base.is_empty() {
530                         if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
531                             let decl = &self.body.local_decls[*local];
532                             if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
533                                 let span = decl.source_info.span;
534                                 self.check_static(def_id, span);
535                                 return;
536                             }
537                         }
538                     }
539                     self.check_op(ops::RawPtrDeref);
540                 }
541
542                 if context.is_mutating_use() {
543                     self.check_op(ops::MutDeref);
544                 }
545             }
546
547             ProjectionElem::ConstantIndex {..} |
548             ProjectionElem::Subslice {..} |
549             ProjectionElem::Field(..) |
550             ProjectionElem::Index(_) => {
551                 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
552                 match base_ty.ty_adt_def() {
553                     Some(def) if def.is_union() => {
554                         self.check_op(ops::UnionAccess);
555                     }
556
557                     _ => {}
558                 }
559             }
560
561             ProjectionElem::Downcast(..) => {
562                 self.check_op(ops::Downcast);
563             }
564         }
565     }
566
567
568     fn visit_source_info(&mut self, source_info: &SourceInfo) {
569         trace!("visit_source_info: source_info={:?}", source_info);
570         self.span = source_info.span;
571     }
572
573     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
574         trace!("visit_statement: statement={:?} location={:?}", statement, location);
575
576         match statement.kind {
577             StatementKind::Assign(..) => {
578                 self.super_statement(statement, location);
579             }
580             StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
581                 self.check_op(ops::IfOrMatch);
582             }
583             // FIXME(eddyb) should these really do nothing?
584             StatementKind::FakeRead(..) |
585             StatementKind::SetDiscriminant { .. } |
586             StatementKind::StorageLive(_) |
587             StatementKind::StorageDead(_) |
588             StatementKind::InlineAsm {..} |
589             StatementKind::Retag { .. } |
590             StatementKind::AscribeUserType(..) |
591             StatementKind::Nop => {}
592         }
593     }
594
595     fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
596         trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
597         self.super_terminator_kind(kind, location);
598
599         match kind {
600             TerminatorKind::Call { func, .. } => {
601                 let fn_ty = func.ty(self.body, self.tcx);
602
603                 let def_id = match fn_ty.kind {
604                     ty::FnDef(def_id, _) => def_id,
605
606                     ty::FnPtr(_) => {
607                         self.check_op(ops::FnCallIndirect);
608                         return;
609                     }
610                     _ => {
611                         self.check_op(ops::FnCallOther);
612                         return;
613                     }
614                 };
615
616                 // At this point, we are calling a function whose `DefId` is known...
617
618                 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = self.tcx.fn_sig(def_id).abi() {
619                     assert!(!self.tcx.is_const_fn(def_id));
620
621                     if self.tcx.item_name(def_id) == sym::transmute {
622                         self.check_op(ops::Transmute);
623                         return;
624                     }
625
626                     // To preserve the current semantics, we return early, allowing all
627                     // intrinsics (except `transmute`) to pass unchecked to miri.
628                     //
629                     // FIXME: We should keep a whitelist of allowed intrinsics (or at least a
630                     // blacklist of unimplemented ones) and fail here instead.
631                     return;
632                 }
633
634                 if self.tcx.is_const_fn(def_id) {
635                     return;
636                 }
637
638                 if is_lang_panic_fn(self.tcx, def_id) {
639                     self.check_op(ops::Panic);
640                 } else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
641                     // Exempt unstable const fns inside of macros with
642                     // `#[allow_internal_unstable]`.
643                     if !self.span.allows_unstable(feature) {
644                         self.check_op(ops::FnCallUnstable(def_id, feature));
645                     }
646                 } else {
647                     self.check_op(ops::FnCallNonConst(def_id));
648                 }
649
650             }
651
652             // Forbid all `Drop` terminators unless the place being dropped is a local with no
653             // projections that cannot be `NeedsDrop`.
654             | TerminatorKind::Drop { location: dropped_place, .. }
655             | TerminatorKind::DropAndReplace { location: dropped_place, .. }
656             => {
657                 let mut err_span = self.span;
658
659                 // Check to see if the type of this place can ever have a drop impl. If not, this
660                 // `Drop` terminator is frivolous.
661                 let ty_needs_drop = dropped_place
662                     .ty(self.body, self.tcx)
663                     .ty
664                     .needs_drop(self.tcx, self.param_env);
665
666                 if !ty_needs_drop {
667                     return;
668                 }
669
670                 let needs_drop = if let Some(local) = dropped_place.as_local() {
671                     // Use the span where the local was declared as the span of the drop error.
672                     err_span = self.body.local_decls[local].source_info.span;
673                     self.qualifs.needs_drop_lazy_seek(local, location)
674                 } else {
675                     true
676                 };
677
678                 if needs_drop {
679                     self.check_op_spanned(ops::LiveDrop, err_span);
680                 }
681             }
682
683             _ => {}
684         }
685     }
686 }
687
688 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
689     struct_span_err!(tcx.sess, span, E0723, "{}", msg)
690         .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
691         .help("add `#![feature(const_fn)]` to the crate attributes to enable")
692         .emit();
693 }
694
695 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
696     let body = item.body;
697
698     if body.control_flow_destroyed.is_empty() {
699         return;
700     }
701
702     let mut locals = body.vars_iter();
703     if let Some(local) = locals.next() {
704         let span = body.local_decls[local].source_info.span;
705         let mut error = item.tcx.sess.struct_span_err(
706             span,
707             &format!(
708                 "new features like let bindings are not permitted in {}s \
709                 which also use short circuiting operators",
710                 item.const_kind(),
711             ),
712         );
713         for (span, kind) in body.control_flow_destroyed.iter() {
714             error.span_note(
715                 *span,
716                 &format!("use of {} here does not actually short circuit due to \
717                 the const evaluator presently not being able to do control flow. \
718                 See https://github.com/rust-lang/rust/issues/49146 for more \
719                 information.", kind),
720             );
721         }
722         for local in locals {
723             let span = body.local_decls[local].source_info.span;
724             error.span_note(span, "more locals defined here");
725         }
726         error.emit();
727     }
728 }
729
730 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
731     let ty = body.return_ty();
732     tcx.infer_ctxt().enter(|infcx| {
733         let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
734         let mut fulfillment_cx = traits::FulfillmentContext::new();
735         let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
736         fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
737         if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
738             infcx.report_fulfillment_errors(&err, None, false);
739         }
740     });
741 }
742
743 fn place_as_reborrow(
744     tcx: TyCtxt<'tcx>,
745     body: &Body<'tcx>,
746     place: &'a Place<'tcx>,
747 ) -> Option<&'a [PlaceElem<'tcx>]> {
748     place
749         .projection
750         .split_last()
751         .and_then(|(outermost, inner)| {
752             if outermost != &ProjectionElem::Deref {
753                 return None;
754             }
755
756             let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
757             match inner_ty.kind {
758                 ty::Ref(..) => Some(inner),
759                 _ => None,
760             }
761         })
762 }