]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_consts/validation.rs
Remove `CheckOpResult`
[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             // Taking a shared borrow of a `static` is always legal, even if that `static` has
368             // interior mutability.
369             | Rvalue::Ref(_, BorrowKind::Shared, ref place)
370             | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
371             if matches!(place.base, PlaceBase::Static(_))
372             => {}
373
374             | Rvalue::Ref(_, kind @ BorrowKind::Shared, ref place)
375             | Rvalue::Ref(_, kind @ BorrowKind::Shallow, ref place)
376             => {
377                 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
378                 // seek the cursors beforehand.
379                 self.qualifs.has_mut_interior.cursor.seek_before(location);
380                 self.qualifs.indirectly_mutable.seek(location);
381
382                 let borrowed_place_has_mut_interior = HasMutInterior::in_place(
383                     &self.item,
384                     &|local| self.qualifs.has_mut_interior_eager_seek(local),
385                     place.as_ref(),
386                 );
387
388                 if borrowed_place_has_mut_interior {
389                     self.check_op(ops::MutBorrow(kind));
390                 }
391             }
392
393             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
394                 let operand_ty = operand.ty(self.body, self.tcx);
395                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
396                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
397
398                 if let (CastTy::Ptr(_), CastTy::Int(_))
399                      | (CastTy::FnPtr,  CastTy::Int(_)) = (cast_in, cast_out) {
400                     self.check_op(ops::RawPtrToIntCast);
401                 }
402             }
403
404             Rvalue::BinaryOp(op, ref lhs, _) => {
405                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
406                     assert!(op == BinOp::Eq || op == BinOp::Ne ||
407                             op == BinOp::Le || op == BinOp::Lt ||
408                             op == BinOp::Ge || 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(
445         &mut self,
446         op: &Operand<'tcx>,
447         location: Location,
448     ) {
449         self.super_operand(op, location);
450         if let Operand::Constant(c) = op {
451             if let Some(def_id) = c.check_static_ptr(self.tcx) {
452                 self.check_static(def_id, self.span);
453             }
454         }
455     }
456
457     fn visit_projection_elem(
458         &mut self,
459         place_base: &PlaceBase<'tcx>,
460         proj_base: &[PlaceElem<'tcx>],
461         elem: &PlaceElem<'tcx>,
462         context: PlaceContext,
463         location: Location,
464     ) {
465         trace!(
466             "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
467             context={:?} location={:?}",
468             place_base,
469             proj_base,
470             elem,
471             context,
472             location,
473         );
474
475         self.super_projection_elem(place_base, proj_base, elem, context, location);
476
477         match elem {
478             ProjectionElem::Deref => {
479                 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
480                 if let ty::RawPtr(_) = base_ty.kind {
481                     if proj_base.is_empty() {
482                         if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
483                             let decl = &self.body.local_decls[*local];
484                             if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
485                                 let span = decl.source_info.span;
486                                 self.check_static(def_id, span);
487                                 return;
488                             }
489                         }
490                     }
491                     self.check_op(ops::RawPtrDeref);
492                 }
493
494                 if context.is_mutating_use() {
495                     self.check_op(ops::MutDeref);
496                 }
497             }
498
499             ProjectionElem::ConstantIndex {..} |
500             ProjectionElem::Subslice {..} |
501             ProjectionElem::Field(..) |
502             ProjectionElem::Index(_) => {
503                 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
504                 match base_ty.ty_adt_def() {
505                     Some(def) if def.is_union() => {
506                         self.check_op(ops::UnionAccess);
507                     }
508
509                     _ => {}
510                 }
511             }
512
513             ProjectionElem::Downcast(..) => {
514                 self.check_op(ops::Downcast);
515             }
516         }
517     }
518
519
520     fn visit_source_info(&mut self, source_info: &SourceInfo) {
521         trace!("visit_source_info: source_info={:?}", source_info);
522         self.span = source_info.span;
523     }
524
525     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
526         trace!("visit_statement: statement={:?} location={:?}", statement, location);
527
528         match statement.kind {
529             StatementKind::Assign(..) => {
530                 self.super_statement(statement, location);
531             }
532             StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
533                 self.check_op(ops::IfOrMatch);
534             }
535             // FIXME(eddyb) should these really do nothing?
536             StatementKind::FakeRead(..) |
537             StatementKind::SetDiscriminant { .. } |
538             StatementKind::StorageLive(_) |
539             StatementKind::StorageDead(_) |
540             StatementKind::InlineAsm {..} |
541             StatementKind::Retag { .. } |
542             StatementKind::AscribeUserType(..) |
543             StatementKind::Nop => {}
544         }
545     }
546
547     fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
548         trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
549         self.super_terminator_kind(kind, location);
550
551         match kind {
552             TerminatorKind::Call { func, .. } => {
553                 let fn_ty = func.ty(self.body, self.tcx);
554
555                 let def_id = match fn_ty.kind {
556                     ty::FnDef(def_id, _) => def_id,
557
558                     ty::FnPtr(_) => {
559                         self.check_op(ops::FnCallIndirect);
560                         return;
561                     }
562                     _ => {
563                         self.check_op(ops::FnCallOther);
564                         return;
565                     }
566                 };
567
568                 // At this point, we are calling a function whose `DefId` is known...
569
570                 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = self.tcx.fn_sig(def_id).abi() {
571                     assert!(!self.tcx.is_const_fn(def_id));
572
573                     if self.tcx.item_name(def_id) == sym::transmute {
574                         self.check_op(ops::Transmute);
575                         return;
576                     }
577
578                     // To preserve the current semantics, we return early, allowing all
579                     // intrinsics (except `transmute`) to pass unchecked to miri.
580                     //
581                     // FIXME: We should keep a whitelist of allowed intrinsics (or at least a
582                     // blacklist of unimplemented ones) and fail here instead.
583                     return;
584                 }
585
586                 if self.tcx.is_const_fn(def_id) {
587                     return;
588                 }
589
590                 if is_lang_panic_fn(self.tcx, def_id) {
591                     self.check_op(ops::Panic);
592                 } else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
593                     // Exempt unstable const fns inside of macros with
594                     // `#[allow_internal_unstable]`.
595                     if !self.span.allows_unstable(feature) {
596                         self.check_op(ops::FnCallUnstable(def_id, feature));
597                     }
598                 } else {
599                     self.check_op(ops::FnCallNonConst(def_id));
600                 }
601
602             }
603
604             // Forbid all `Drop` terminators unless the place being dropped is a local with no
605             // projections that cannot be `NeedsDrop`.
606             | TerminatorKind::Drop { location: dropped_place, .. }
607             | TerminatorKind::DropAndReplace { location: dropped_place, .. }
608             => {
609                 let mut err_span = self.span;
610
611                 // Check to see if the type of this place can ever have a drop impl. If not, this
612                 // `Drop` terminator is frivolous.
613                 let ty_needs_drop = dropped_place
614                     .ty(self.body, self.tcx)
615                     .ty
616                     .needs_drop(self.tcx, self.param_env);
617
618                 if !ty_needs_drop {
619                     return;
620                 }
621
622                 let needs_drop = if let Some(local) = dropped_place.as_local() {
623                     // Use the span where the local was declared as the span of the drop error.
624                     err_span = self.body.local_decls[local].source_info.span;
625                     self.qualifs.needs_drop_lazy_seek(local, location)
626                 } else {
627                     true
628                 };
629
630                 if needs_drop {
631                     self.check_op_spanned(ops::LiveDrop, err_span);
632                 }
633             }
634
635             _ => {}
636         }
637     }
638 }
639
640 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
641     struct_span_err!(tcx.sess, span, E0723, "{}", msg)
642         .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
643         .help("add `#![feature(const_fn)]` to the crate attributes to enable")
644         .emit();
645 }
646
647 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
648     let body = item.body;
649
650     if body.control_flow_destroyed.is_empty() {
651         return;
652     }
653
654     let mut locals = body.vars_iter();
655     if let Some(local) = locals.next() {
656         let span = body.local_decls[local].source_info.span;
657         let mut error = item.tcx.sess.struct_span_err(
658             span,
659             &format!(
660                 "new features like let bindings are not permitted in {}s \
661                 which also use short circuiting operators",
662                 item.const_kind(),
663             ),
664         );
665         for (span, kind) in body.control_flow_destroyed.iter() {
666             error.span_note(
667                 *span,
668                 &format!("use of {} here does not actually short circuit due to \
669                 the const evaluator presently not being able to do control flow. \
670                 See https://github.com/rust-lang/rust/issues/49146 for more \
671                 information.", kind),
672             );
673         }
674         for local in locals {
675             let span = body.local_decls[local].source_info.span;
676             error.span_note(span, "more locals defined here");
677         }
678         error.emit();
679     }
680 }
681
682 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
683     let ty = body.return_ty();
684     tcx.infer_ctxt().enter(|infcx| {
685         let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
686         let mut fulfillment_cx = traits::FulfillmentContext::new();
687         let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
688         fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
689         if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
690             infcx.report_fulfillment_errors(&err, None, false);
691         }
692     });
693 }
694
695 fn place_as_reborrow(
696     tcx: TyCtxt<'tcx>,
697     body: &Body<'tcx>,
698     place: &'a Place<'tcx>,
699 ) -> Option<&'a [PlaceElem<'tcx>]> {
700     place
701         .projection
702         .split_last()
703         .and_then(|(outermost, inner)| {
704             if outermost != &ProjectionElem::Deref {
705                 return None;
706             }
707
708             let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
709             match inner_ty.kind {
710                 ty::Ref(..) => Some(inner),
711                 _ => None,
712             }
713         })
714 }