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