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