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