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