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