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