]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/visit.rs
make `super_projection` take a `PlaceRef`
[rust.git] / compiler / rustc_middle / src / mir / visit.rs
1 //! # The MIR Visitor
2 //!
3 //! ## Overview
4 //!
5 //! There are two visitors, one for immutable and one for mutable references,
6 //! but both are generated by the following macro. The code is written according
7 //! to the following conventions:
8 //!
9 //! - introduce a `visit_foo` and a `super_foo` method for every MIR type
10 //! - `visit_foo`, by default, calls `super_foo`
11 //! - `super_foo`, by default, destructures the `foo` and calls `visit_foo`
12 //!
13 //! This allows you as a user to override `visit_foo` for types are
14 //! interested in, and invoke (within that method) call
15 //! `self.super_foo` to get the default behavior. Just as in an OO
16 //! language, you should never call `super` methods ordinarily except
17 //! in that circumstance.
18 //!
19 //! For the most part, we do not destructure things external to the
20 //! MIR, e.g., types, spans, etc, but simply visit them and stop. This
21 //! avoids duplication with other visitors like `TypeFoldable`.
22 //!
23 //! ## Updating
24 //!
25 //! The code is written in a very deliberate style intended to minimize
26 //! the chance of things being overlooked. You'll notice that we always
27 //! use pattern matching to reference fields and we ensure that all
28 //! matches are exhaustive.
29 //!
30 //! For example, the `super_basic_block_data` method begins like this:
31 //!
32 //! ```rust
33 //! fn super_basic_block_data(&mut self,
34 //!                           block: BasicBlock,
35 //!                           data: & $($mutability)? BasicBlockData<'tcx>) {
36 //!     let BasicBlockData {
37 //!         statements,
38 //!         terminator,
39 //!         is_cleanup: _
40 //!     } = *data;
41 //!
42 //!     for statement in statements {
43 //!         self.visit_statement(block, statement);
44 //!     }
45 //!
46 //!     ...
47 //! }
48 //! ```
49 //!
50 //! Here we used `let BasicBlockData { <fields> } = *data` deliberately,
51 //! rather than writing `data.statements` in the body. This is because if one
52 //! adds a new field to `BasicBlockData`, one will be forced to revise this code,
53 //! and hence one will (hopefully) invoke the correct visit methods (if any).
54 //!
55 //! For this to work, ALL MATCHES MUST BE EXHAUSTIVE IN FIELDS AND VARIANTS.
56 //! That means you never write `..` to skip over fields, nor do you write `_`
57 //! to skip over variants in a `match`.
58 //!
59 //! The only place that `_` is acceptable is to match a field (or
60 //! variant argument) that does not require visiting, as in
61 //! `is_cleanup` above.
62
63 use crate::mir::*;
64 use crate::ty::subst::SubstsRef;
65 use crate::ty::{CanonicalUserTypeAnnotation, Ty};
66 use rustc_span::Span;
67
68 macro_rules! make_mir_visitor {
69     ($visitor_trait_name:ident, $($mutability:ident)?) => {
70         pub trait $visitor_trait_name<'tcx> {
71             // Override these, and call `self.super_xxx` to revert back to the
72             // default behavior.
73
74             fn visit_body(
75                 &mut self,
76                 body: &$($mutability)? Body<'tcx>,
77             ) {
78                 self.super_body(body);
79             }
80
81             fn visit_basic_block_data(&mut self,
82                                       block: BasicBlock,
83                                       data: & $($mutability)? BasicBlockData<'tcx>) {
84                 self.super_basic_block_data(block, data);
85             }
86
87             fn visit_source_scope_data(&mut self,
88                                            scope_data: & $($mutability)? SourceScopeData<'tcx>) {
89                 self.super_source_scope_data(scope_data);
90             }
91
92             fn visit_statement(&mut self,
93                                statement: & $($mutability)? Statement<'tcx>,
94                                location: Location) {
95                 self.super_statement(statement, location);
96             }
97
98             fn visit_assign(&mut self,
99                             place: & $($mutability)? Place<'tcx>,
100                             rvalue: & $($mutability)? Rvalue<'tcx>,
101                             location: Location) {
102                 self.super_assign(place, rvalue, location);
103             }
104
105             fn visit_terminator(&mut self,
106                                 terminator: & $($mutability)? Terminator<'tcx>,
107                                 location: Location) {
108                 self.super_terminator(terminator, location);
109             }
110
111             fn visit_assert_message(&mut self,
112                                     msg: & $($mutability)? AssertMessage<'tcx>,
113                                     location: Location) {
114                 self.super_assert_message(msg, location);
115             }
116
117             fn visit_rvalue(&mut self,
118                             rvalue: & $($mutability)? Rvalue<'tcx>,
119                             location: Location) {
120                 self.super_rvalue(rvalue, location);
121             }
122
123             fn visit_operand(&mut self,
124                              operand: & $($mutability)? Operand<'tcx>,
125                              location: Location) {
126                 self.super_operand(operand, location);
127             }
128
129             fn visit_ascribe_user_ty(&mut self,
130                                      place: & $($mutability)? Place<'tcx>,
131                                      variance: & $($mutability)? ty::Variance,
132                                      user_ty: & $($mutability)? UserTypeProjection,
133                                      location: Location) {
134                 self.super_ascribe_user_ty(place, variance, user_ty, location);
135             }
136
137             fn visit_coverage(&mut self,
138                               coverage: & $($mutability)? Coverage,
139                               location: Location) {
140                 self.super_coverage(coverage, location);
141             }
142
143             fn visit_retag(&mut self,
144                            kind: & $($mutability)? RetagKind,
145                            place: & $($mutability)? Place<'tcx>,
146                            location: Location) {
147                 self.super_retag(kind, place, location);
148             }
149
150             fn visit_place(&mut self,
151                             place: & $($mutability)? Place<'tcx>,
152                             context: PlaceContext,
153                             location: Location) {
154                 self.super_place(place, context, location);
155             }
156
157             visit_place_fns!($($mutability)?);
158
159             fn visit_constant(&mut self,
160                               constant: & $($mutability)? Constant<'tcx>,
161                               location: Location) {
162                 self.super_constant(constant, location);
163             }
164
165             fn visit_span(&mut self,
166                           span: & $($mutability)? Span) {
167                 self.super_span(span);
168             }
169
170             fn visit_source_info(&mut self,
171                                  source_info: & $($mutability)? SourceInfo) {
172                 self.super_source_info(source_info);
173             }
174
175             fn visit_ty(&mut self,
176                         ty: $(& $mutability)? Ty<'tcx>,
177                         _: TyContext) {
178                 self.super_ty(ty);
179             }
180
181             fn visit_user_type_projection(
182                 &mut self,
183                 ty: & $($mutability)? UserTypeProjection,
184             ) {
185                 self.super_user_type_projection(ty);
186             }
187
188             fn visit_user_type_annotation(
189                 &mut self,
190                 index: UserTypeAnnotationIndex,
191                 ty: & $($mutability)? CanonicalUserTypeAnnotation<'tcx>,
192             ) {
193                 self.super_user_type_annotation(index, ty);
194             }
195
196             fn visit_region(&mut self,
197                             region: & $($mutability)? ty::Region<'tcx>,
198                             _: Location) {
199                 self.super_region(region);
200             }
201
202             fn visit_const(&mut self,
203                            constant: & $($mutability)? &'tcx ty::Const<'tcx>,
204                            _: Location) {
205                 self.super_const(constant);
206             }
207
208             fn visit_substs(&mut self,
209                             substs: & $($mutability)? SubstsRef<'tcx>,
210                             _: Location) {
211                 self.super_substs(substs);
212             }
213
214             fn visit_local_decl(&mut self,
215                                 local: Local,
216                                 local_decl: & $($mutability)? LocalDecl<'tcx>) {
217                 self.super_local_decl(local, local_decl);
218             }
219
220             fn visit_var_debug_info(&mut self,
221                                     var_debug_info: & $($mutability)* VarDebugInfo<'tcx>) {
222                 self.super_var_debug_info(var_debug_info);
223             }
224
225             fn visit_local(&mut self,
226                             _local: & $($mutability)? Local,
227                             _context: PlaceContext,
228                             _location: Location) {
229             }
230
231             fn visit_source_scope(&mut self,
232                                       scope: & $($mutability)? SourceScope) {
233                 self.super_source_scope(scope);
234             }
235
236             // The `super_xxx` methods comprise the default behavior and are
237             // not meant to be overridden.
238
239             fn super_body(
240                 &mut self,
241                 body: &$($mutability)? Body<'tcx>,
242             ) {
243                 let span = body.span;
244                 if let Some(yield_ty) = &$($mutability)? body.yield_ty {
245                     self.visit_ty(
246                         yield_ty,
247                         TyContext::YieldTy(SourceInfo::outermost(span))
248                     );
249                 }
250
251                 // for best performance, we want to use an iterator rather
252                 // than a for-loop, to avoid calling `body::Body::invalidate` for
253                 // each basic block.
254                 macro_rules! basic_blocks {
255                     (mut) => (body.basic_blocks_mut().iter_enumerated_mut());
256                     () => (body.basic_blocks().iter_enumerated());
257                 }
258                 for (bb, data) in basic_blocks!($($mutability)?) {
259                     self.visit_basic_block_data(bb, data);
260                 }
261
262                 for scope in &$($mutability)? body.source_scopes {
263                     self.visit_source_scope_data(scope);
264                 }
265
266                 self.visit_ty(
267                     &$($mutability)? body.return_ty(),
268                     TyContext::ReturnTy(SourceInfo::outermost(body.span))
269                 );
270
271                 for local in body.local_decls.indices() {
272                     self.visit_local_decl(local, & $($mutability)? body.local_decls[local]);
273                 }
274
275                 macro_rules! type_annotations {
276                     (mut) => (body.user_type_annotations.iter_enumerated_mut());
277                     () => (body.user_type_annotations.iter_enumerated());
278                 }
279
280                 for (index, annotation) in type_annotations!($($mutability)?) {
281                     self.visit_user_type_annotation(
282                         index, annotation
283                     );
284                 }
285
286                 for var_debug_info in &$($mutability)? body.var_debug_info {
287                     self.visit_var_debug_info(var_debug_info);
288                 }
289
290                 self.visit_span(&$($mutability)? body.span);
291
292                 for const_ in &$($mutability)? body.required_consts {
293                     let location = START_BLOCK.start_location();
294                     self.visit_constant(const_, location);
295                 }
296             }
297
298             fn super_basic_block_data(&mut self,
299                                       block: BasicBlock,
300                                       data: & $($mutability)? BasicBlockData<'tcx>) {
301                 let BasicBlockData {
302                     statements,
303                     terminator,
304                     is_cleanup: _
305                 } = data;
306
307                 let mut index = 0;
308                 for statement in statements {
309                     let location = Location { block, statement_index: index };
310                     self.visit_statement(statement, location);
311                     index += 1;
312                 }
313
314                 if let Some(terminator) = terminator {
315                     let location = Location { block, statement_index: index };
316                     self.visit_terminator(terminator, location);
317                 }
318             }
319
320             fn super_source_scope_data(
321                 &mut self,
322                 scope_data: & $($mutability)? SourceScopeData<'tcx>,
323             ) {
324                 let SourceScopeData {
325                     span,
326                     parent_scope,
327                     inlined,
328                     inlined_parent_scope,
329                     local_data: _,
330                 } = scope_data;
331
332                 self.visit_span(span);
333                 if let Some(parent_scope) = parent_scope {
334                     self.visit_source_scope(parent_scope);
335                 }
336                 if let Some((callee, callsite_span)) = inlined {
337                     let location = START_BLOCK.start_location();
338
339                     self.visit_span(callsite_span);
340
341                     let ty::Instance { def: callee_def, substs: callee_substs } = callee;
342                     match callee_def {
343                         ty::InstanceDef::Item(_def_id) => {}
344
345                         ty::InstanceDef::Intrinsic(_def_id) |
346                         ty::InstanceDef::VtableShim(_def_id) |
347                         ty::InstanceDef::ReifyShim(_def_id) |
348                         ty::InstanceDef::Virtual(_def_id, _) |
349                         ty::InstanceDef::ClosureOnceShim { call_once: _def_id } |
350                         ty::InstanceDef::DropGlue(_def_id, None) => {}
351
352                         ty::InstanceDef::FnPtrShim(_def_id, ty) |
353                         ty::InstanceDef::DropGlue(_def_id, Some(ty)) |
354                         ty::InstanceDef::CloneShim(_def_id, ty) => {
355                             // FIXME(eddyb) use a better `TyContext` here.
356                             self.visit_ty(ty, TyContext::Location(location));
357                         }
358                     }
359                     self.visit_substs(callee_substs, location);
360                 }
361                 if let Some(inlined_parent_scope) = inlined_parent_scope {
362                     self.visit_source_scope(inlined_parent_scope);
363                 }
364             }
365
366             fn super_statement(&mut self,
367                                statement: & $($mutability)? Statement<'tcx>,
368                                location: Location) {
369                 let Statement {
370                     source_info,
371                     kind,
372                 } = statement;
373
374                 self.visit_source_info(source_info);
375                 match kind {
376                     StatementKind::Assign(
377                         box(ref $($mutability)? place, ref $($mutability)? rvalue)
378                     ) => {
379                         self.visit_assign(place, rvalue, location);
380                     }
381                     StatementKind::FakeRead(_, place) => {
382                         self.visit_place(
383                             place,
384                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
385                             location
386                         );
387                     }
388                     StatementKind::SetDiscriminant { place, .. } => {
389                         self.visit_place(
390                             place,
391                             PlaceContext::MutatingUse(MutatingUseContext::Store),
392                             location
393                         );
394                     }
395                     StatementKind::StorageLive(local) => {
396                         self.visit_local(
397                             local,
398                             PlaceContext::NonUse(NonUseContext::StorageLive),
399                             location
400                         );
401                     }
402                     StatementKind::StorageDead(local) => {
403                         self.visit_local(
404                             local,
405                             PlaceContext::NonUse(NonUseContext::StorageDead),
406                             location
407                         );
408                     }
409                     StatementKind::LlvmInlineAsm(asm) => {
410                         for output in & $($mutability)? asm.outputs[..] {
411                             self.visit_place(
412                                 output,
413                                 PlaceContext::MutatingUse(MutatingUseContext::AsmOutput),
414                                 location
415                             );
416                         }
417                         for (span, input) in & $($mutability)? asm.inputs[..] {
418                             self.visit_span(span);
419                             self.visit_operand(input, location);
420                         }
421                     }
422                     StatementKind::Retag(kind, place) => {
423                         self.visit_retag(kind, place, location);
424                     }
425                     StatementKind::AscribeUserType(
426                         box(ref $($mutability)? place, ref $($mutability)? user_ty),
427                         variance
428                     ) => {
429                         self.visit_ascribe_user_ty(place, variance, user_ty, location);
430                     }
431                     StatementKind::Coverage(coverage) => {
432                         self.visit_coverage(
433                             coverage,
434                             location
435                         )
436                     }
437                     StatementKind::Nop => {}
438                 }
439             }
440
441             fn super_assign(&mut self,
442                             place: &$($mutability)? Place<'tcx>,
443                             rvalue: &$($mutability)? Rvalue<'tcx>,
444                             location: Location) {
445                 self.visit_place(
446                     place,
447                     PlaceContext::MutatingUse(MutatingUseContext::Store),
448                     location
449                 );
450                 self.visit_rvalue(rvalue, location);
451             }
452
453             fn super_terminator(&mut self,
454                                 terminator: &$($mutability)? Terminator<'tcx>,
455                                 location: Location) {
456                 let Terminator { source_info, kind } = terminator;
457
458                 self.visit_source_info(source_info);
459                 match kind {
460                     TerminatorKind::Goto { .. } |
461                     TerminatorKind::Resume |
462                     TerminatorKind::Abort |
463                     TerminatorKind::GeneratorDrop |
464                     TerminatorKind::Unreachable |
465                     TerminatorKind::FalseEdge { .. } |
466                     TerminatorKind::FalseUnwind { .. } => {
467                     }
468
469                     TerminatorKind::Return => {
470                         // `return` logically moves from the return place `_0`. Note that the place
471                         // cannot be changed by any visitor, though.
472                         let $($mutability)? local = RETURN_PLACE;
473                         self.visit_local(
474                             & $($mutability)? local,
475                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Move),
476                             location,
477                         );
478
479                         assert_eq!(
480                             local,
481                             RETURN_PLACE,
482                             "`MutVisitor` tried to mutate return place of `return` terminator"
483                         );
484                     }
485
486                     TerminatorKind::SwitchInt {
487                         discr,
488                         switch_ty,
489                         targets: _
490                     } => {
491                         self.visit_operand(discr, location);
492                         self.visit_ty(switch_ty, TyContext::Location(location));
493                     }
494
495                     TerminatorKind::Drop {
496                         place,
497                         target: _,
498                         unwind: _,
499                     } => {
500                         self.visit_place(
501                             place,
502                             PlaceContext::MutatingUse(MutatingUseContext::Drop),
503                             location
504                         );
505                     }
506
507                     TerminatorKind::DropAndReplace {
508                         place,
509                         value,
510                         target: _,
511                         unwind: _,
512                     } => {
513                         self.visit_place(
514                             place,
515                             PlaceContext::MutatingUse(MutatingUseContext::Drop),
516                             location
517                         );
518                         self.visit_operand(value, location);
519                     }
520
521                     TerminatorKind::Call {
522                         func,
523                         args,
524                         destination,
525                         cleanup: _,
526                         from_hir_call: _,
527                         fn_span: _
528                     } => {
529                         self.visit_operand(func, location);
530                         for arg in args {
531                             self.visit_operand(arg, location);
532                         }
533                         if let Some((destination, _)) = destination {
534                             self.visit_place(
535                                 destination,
536                                 PlaceContext::MutatingUse(MutatingUseContext::Call),
537                                 location
538                             );
539                         }
540                     }
541
542                     TerminatorKind::Assert {
543                         cond,
544                         expected: _,
545                         msg,
546                         target: _,
547                         cleanup: _,
548                     } => {
549                         self.visit_operand(cond, location);
550                         self.visit_assert_message(msg, location);
551                     }
552
553                     TerminatorKind::Yield {
554                         value,
555                         resume: _,
556                         resume_arg,
557                         drop: _,
558                     } => {
559                         self.visit_operand(value, location);
560                         self.visit_place(
561                             resume_arg,
562                             PlaceContext::MutatingUse(MutatingUseContext::Yield),
563                             location,
564                         );
565                     }
566
567                     TerminatorKind::InlineAsm {
568                         template: _,
569                         operands,
570                         options: _,
571                         line_spans: _,
572                         destination: _,
573                     } => {
574                         for op in operands {
575                             match op {
576                                 InlineAsmOperand::In { value, .. }
577                                 | InlineAsmOperand::Const { value } => {
578                                     self.visit_operand(value, location);
579                                 }
580                                 InlineAsmOperand::Out { place, .. } => {
581                                     if let Some(place) = place {
582                                         self.visit_place(
583                                             place,
584                                             PlaceContext::MutatingUse(MutatingUseContext::Store),
585                                             location,
586                                         );
587                                     }
588                                 }
589                                 InlineAsmOperand::InOut { in_value, out_place, .. } => {
590                                     self.visit_operand(in_value, location);
591                                     if let Some(out_place) = out_place {
592                                         self.visit_place(
593                                             out_place,
594                                             PlaceContext::MutatingUse(MutatingUseContext::Store),
595                                             location,
596                                         );
597                                     }
598                                 }
599                                 InlineAsmOperand::SymFn { value } => {
600                                     self.visit_constant(value, location);
601                                 }
602                                 InlineAsmOperand::SymStatic { def_id: _ } => {}
603                             }
604                         }
605                     }
606                 }
607             }
608
609             fn super_assert_message(&mut self,
610                                     msg: & $($mutability)? AssertMessage<'tcx>,
611                                     location: Location) {
612                 use crate::mir::AssertKind::*;
613                 match msg {
614                     BoundsCheck { len, index } => {
615                         self.visit_operand(len, location);
616                         self.visit_operand(index, location);
617                     }
618                     Overflow(_, l, r) => {
619                         self.visit_operand(l, location);
620                         self.visit_operand(r, location);
621                     }
622                     OverflowNeg(op) | DivisionByZero(op) | RemainderByZero(op) => {
623                         self.visit_operand(op, location);
624                     }
625                     ResumedAfterReturn(_) | ResumedAfterPanic(_) => {
626                         // Nothing to visit
627                     }
628                 }
629             }
630
631             fn super_rvalue(&mut self,
632                             rvalue: & $($mutability)? Rvalue<'tcx>,
633                             location: Location) {
634                 match rvalue {
635                     Rvalue::Use(operand) => {
636                         self.visit_operand(operand, location);
637                     }
638
639                     Rvalue::Repeat(value, _) => {
640                         self.visit_operand(value, location);
641                     }
642
643                     Rvalue::ThreadLocalRef(_) => {}
644
645                     Rvalue::Ref(r, bk, path) => {
646                         self.visit_region(r, location);
647                         let ctx = match bk {
648                             BorrowKind::Shared => PlaceContext::NonMutatingUse(
649                                 NonMutatingUseContext::SharedBorrow
650                             ),
651                             BorrowKind::Shallow => PlaceContext::NonMutatingUse(
652                                 NonMutatingUseContext::ShallowBorrow
653                             ),
654                             BorrowKind::Unique => PlaceContext::NonMutatingUse(
655                                 NonMutatingUseContext::UniqueBorrow
656                             ),
657                             BorrowKind::Mut { .. } =>
658                                 PlaceContext::MutatingUse(MutatingUseContext::Borrow),
659                         };
660                         self.visit_place(path, ctx, location);
661                     }
662
663                     Rvalue::AddressOf(m, path) => {
664                         let ctx = match m {
665                             Mutability::Mut => PlaceContext::MutatingUse(
666                                 MutatingUseContext::AddressOf
667                             ),
668                             Mutability::Not => PlaceContext::NonMutatingUse(
669                                 NonMutatingUseContext::AddressOf
670                             ),
671                         };
672                         self.visit_place(path, ctx, location);
673                     }
674
675                     Rvalue::Len(path) => {
676                         self.visit_place(
677                             path,
678                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
679                             location
680                         );
681                     }
682
683                     Rvalue::Cast(_cast_kind, operand, ty) => {
684                         self.visit_operand(operand, location);
685                         self.visit_ty(ty, TyContext::Location(location));
686                     }
687
688                     Rvalue::BinaryOp(_bin_op, lhs, rhs)
689                     | Rvalue::CheckedBinaryOp(_bin_op, lhs, rhs) => {
690                         self.visit_operand(lhs, location);
691                         self.visit_operand(rhs, location);
692                     }
693
694                     Rvalue::UnaryOp(_un_op, op) => {
695                         self.visit_operand(op, location);
696                     }
697
698                     Rvalue::Discriminant(place) => {
699                         self.visit_place(
700                             place,
701                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
702                             location
703                         );
704                     }
705
706                     Rvalue::NullaryOp(_op, ty) => {
707                         self.visit_ty(ty, TyContext::Location(location));
708                     }
709
710                     Rvalue::Aggregate(kind, operands) => {
711                         let kind = &$($mutability)? **kind;
712                         match kind {
713                             AggregateKind::Array(ty) => {
714                                 self.visit_ty(ty, TyContext::Location(location));
715                             }
716                             AggregateKind::Tuple => {
717                             }
718                             AggregateKind::Adt(
719                                 _adt_def,
720                                 _variant_index,
721                                 substs,
722                                 _user_substs,
723                                 _active_field_index
724                             ) => {
725                                 self.visit_substs(substs, location);
726                             }
727                             AggregateKind::Closure(
728                                 _,
729                                 closure_substs
730                             ) => {
731                                 self.visit_substs(closure_substs, location);
732                             }
733                             AggregateKind::Generator(
734                                 _,
735                                 generator_substs,
736                                 _movability,
737                             ) => {
738                                 self.visit_substs(generator_substs, location);
739                             }
740                         }
741
742                         for operand in operands {
743                             self.visit_operand(operand, location);
744                         }
745                     }
746                 }
747             }
748
749             fn super_operand(&mut self,
750                              operand: & $($mutability)? Operand<'tcx>,
751                              location: Location) {
752                 match operand {
753                     Operand::Copy(place) => {
754                         self.visit_place(
755                             place,
756                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
757                             location
758                         );
759                     }
760                     Operand::Move(place) => {
761                         self.visit_place(
762                             place,
763                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Move),
764                             location
765                         );
766                     }
767                     Operand::Constant(constant) => {
768                         self.visit_constant(constant, location);
769                     }
770                 }
771             }
772
773             fn super_ascribe_user_ty(&mut self,
774                                      place: & $($mutability)? Place<'tcx>,
775                                      _variance: & $($mutability)? ty::Variance,
776                                      user_ty: & $($mutability)? UserTypeProjection,
777                                      location: Location) {
778                 self.visit_place(
779                     place,
780                     PlaceContext::NonUse(NonUseContext::AscribeUserTy),
781                     location
782                 );
783                 self.visit_user_type_projection(user_ty);
784             }
785
786             fn super_coverage(&mut self,
787                               _coverage: & $($mutability)? Coverage,
788                               _location: Location) {
789             }
790
791             fn super_retag(&mut self,
792                            _kind: & $($mutability)? RetagKind,
793                            place: & $($mutability)? Place<'tcx>,
794                            location: Location) {
795                 self.visit_place(
796                     place,
797                     PlaceContext::MutatingUse(MutatingUseContext::Retag),
798                     location,
799                 );
800             }
801
802             fn super_local_decl(&mut self,
803                                 local: Local,
804                                 local_decl: & $($mutability)? LocalDecl<'tcx>) {
805                 let LocalDecl {
806                     mutability: _,
807                     ty,
808                     user_ty,
809                     source_info,
810                     internal: _,
811                     local_info: _,
812                     is_block_tail: _,
813                 } = local_decl;
814
815                 self.visit_ty(ty, TyContext::LocalDecl {
816                     local,
817                     source_info: *source_info,
818                 });
819                 if let Some(user_ty) = user_ty {
820                     for (user_ty, _) in & $($mutability)? user_ty.contents {
821                         self.visit_user_type_projection(user_ty);
822                     }
823                 }
824                 self.visit_source_info(source_info);
825             }
826
827             fn super_var_debug_info(&mut self,
828                                     var_debug_info: & $($mutability)? VarDebugInfo<'tcx>) {
829                 let VarDebugInfo {
830                     name: _,
831                     source_info,
832                     value,
833                 } = var_debug_info;
834
835                 self.visit_source_info(source_info);
836                 let location = START_BLOCK.start_location();
837                 match value {
838                     VarDebugInfoContents::Const(c) => self.visit_constant(c, location),
839                     VarDebugInfoContents::Place(place) =>
840                         self.visit_place(
841                             place,
842                             PlaceContext::NonUse(NonUseContext::VarDebugInfo),
843                             location
844                         ),
845                 }
846             }
847
848             fn super_source_scope(&mut self,
849                                       _scope: & $($mutability)? SourceScope) {
850             }
851
852             fn super_constant(&mut self,
853                               constant: & $($mutability)? Constant<'tcx>,
854                               location: Location) {
855                 let Constant {
856                     span,
857                     user_ty,
858                     literal,
859                 } = constant;
860
861                 self.visit_span(span);
862                 drop(user_ty); // no visit method for this
863                 self.visit_const(literal, location);
864             }
865
866             fn super_span(&mut self, _span: & $($mutability)? Span) {
867             }
868
869             fn super_source_info(&mut self, source_info: & $($mutability)? SourceInfo) {
870                 let SourceInfo {
871                     span,
872                     scope,
873                 } = source_info;
874
875                 self.visit_span(span);
876                 self.visit_source_scope(scope);
877             }
878
879             fn super_user_type_projection(
880                 &mut self,
881                 _ty: & $($mutability)? UserTypeProjection,
882             ) {
883             }
884
885             fn super_user_type_annotation(
886                 &mut self,
887                 _index: UserTypeAnnotationIndex,
888                 ty: & $($mutability)? CanonicalUserTypeAnnotation<'tcx>,
889             ) {
890                 self.visit_span(& $($mutability)? ty.span);
891                 self.visit_ty(& $($mutability)? ty.inferred_ty, TyContext::UserTy(ty.span));
892             }
893
894             fn super_ty(&mut self, _ty: $(& $mutability)? Ty<'tcx>) {
895             }
896
897             fn super_region(&mut self, _region: & $($mutability)? ty::Region<'tcx>) {
898             }
899
900             fn super_const(&mut self, _const: & $($mutability)? &'tcx ty::Const<'tcx>) {
901             }
902
903             fn super_substs(&mut self, _substs: & $($mutability)? SubstsRef<'tcx>) {
904             }
905
906             // Convenience methods
907
908             fn visit_location(
909                 &mut self,
910                 body: &$($mutability)? Body<'tcx>,
911                 location: Location
912             ) {
913                 macro_rules! basic_blocks {
914                     (mut) => (body.basic_blocks_mut());
915                     () => (body.basic_blocks());
916                 }
917                 let basic_block = & $($mutability)? basic_blocks!($($mutability)?)[location.block];
918                 if basic_block.statements.len() == location.statement_index {
919                     if let Some(ref $($mutability)? terminator) = basic_block.terminator {
920                         self.visit_terminator(terminator, location)
921                     }
922                 } else {
923                     let statement = & $($mutability)?
924                         basic_block.statements[location.statement_index];
925                     self.visit_statement(statement, location)
926                 }
927             }
928         }
929     }
930 }
931
932 macro_rules! visit_place_fns {
933     (mut) => {
934         fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
935
936         fn super_place(
937             &mut self,
938             place: &mut Place<'tcx>,
939             context: PlaceContext,
940             location: Location,
941         ) {
942             self.visit_local(&mut place.local, context, location);
943
944             if let Some(new_projection) = self.process_projection(&place.projection, location) {
945                 place.projection = self.tcx().intern_place_elems(&new_projection);
946             }
947         }
948
949         fn process_projection(
950             &mut self,
951             projection: &'a [PlaceElem<'tcx>],
952             location: Location,
953         ) -> Option<Vec<PlaceElem<'tcx>>> {
954             let mut projection = Cow::Borrowed(projection);
955
956             for i in 0..projection.len() {
957                 if let Some(&elem) = projection.get(i) {
958                     if let Some(elem) = self.process_projection_elem(elem, location) {
959                         // This converts the borrowed projection into `Cow::Owned(_)` and returns a
960                         // clone of the projection so we can mutate and reintern later.
961                         let vec = projection.to_mut();
962                         vec[i] = elem;
963                     }
964                 }
965             }
966
967             match projection {
968                 Cow::Borrowed(_) => None,
969                 Cow::Owned(vec) => Some(vec),
970             }
971         }
972
973         fn process_projection_elem(
974             &mut self,
975             elem: PlaceElem<'tcx>,
976             location: Location,
977         ) -> Option<PlaceElem<'tcx>> {
978             match elem {
979                 PlaceElem::Index(local) => {
980                     let mut new_local = local;
981                     self.visit_local(
982                         &mut new_local,
983                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
984                         location,
985                     );
986
987                     if new_local == local { None } else { Some(PlaceElem::Index(new_local)) }
988                 }
989                 PlaceElem::Deref
990                 | PlaceElem::Field(..)
991                 | PlaceElem::ConstantIndex { .. }
992                 | PlaceElem::Subslice { .. }
993                 | PlaceElem::Downcast(..) => None,
994             }
995         }
996     };
997
998     () => {
999         fn visit_projection(
1000             &mut self,
1001             place_ref: PlaceRef<'tcx>,
1002             context: PlaceContext,
1003             location: Location,
1004         ) {
1005             self.super_projection(place_ref, context, location);
1006         }
1007
1008         fn visit_projection_elem(
1009             &mut self,
1010             local: Local,
1011             proj_base: &[PlaceElem<'tcx>],
1012             elem: PlaceElem<'tcx>,
1013             context: PlaceContext,
1014             location: Location,
1015         ) {
1016             self.super_projection_elem(local, proj_base, elem, context, location);
1017         }
1018
1019         fn super_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1020             let mut context = context;
1021
1022             if !place.projection.is_empty() {
1023                 if context.is_use() {
1024                     // ^ Only change the context if it is a real use, not a "use" in debuginfo.
1025                     context = if context.is_mutating_use() {
1026                         PlaceContext::MutatingUse(MutatingUseContext::Projection)
1027                     } else {
1028                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
1029                     };
1030                 }
1031             }
1032
1033             self.visit_local(&place.local, context, location);
1034
1035             self.visit_projection(place.as_ref(), context, location);
1036         }
1037
1038         fn super_projection(
1039             &mut self,
1040             place_ref: PlaceRef<'tcx>,
1041             context: PlaceContext,
1042             location: Location,
1043         ) {
1044             // FIXME: Use PlaceRef::iter_projections, once that exists.
1045             let mut cursor = place_ref.projection;
1046             while let &[ref proj_base @ .., elem] = cursor {
1047                 cursor = proj_base;
1048                 self.visit_projection_elem(place_ref.local, cursor, elem, context, location);
1049             }
1050         }
1051
1052         fn super_projection_elem(
1053             &mut self,
1054             _local: Local,
1055             _proj_base: &[PlaceElem<'tcx>],
1056             elem: PlaceElem<'tcx>,
1057             _context: PlaceContext,
1058             location: Location,
1059         ) {
1060             match elem {
1061                 ProjectionElem::Field(_field, ty) => {
1062                     self.visit_ty(ty, TyContext::Location(location));
1063                 }
1064                 ProjectionElem::Index(local) => {
1065                     self.visit_local(
1066                         &local,
1067                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
1068                         location,
1069                     );
1070                 }
1071                 ProjectionElem::Deref
1072                 | ProjectionElem::Subslice { from: _, to: _, from_end: _ }
1073                 | ProjectionElem::ConstantIndex { offset: _, min_length: _, from_end: _ }
1074                 | ProjectionElem::Downcast(_, _) => {}
1075             }
1076         }
1077     };
1078 }
1079
1080 make_mir_visitor!(Visitor,);
1081 make_mir_visitor!(MutVisitor, mut);
1082
1083 pub trait MirVisitable<'tcx> {
1084     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>);
1085 }
1086
1087 impl<'tcx> MirVisitable<'tcx> for Statement<'tcx> {
1088     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1089         visitor.visit_statement(self, location)
1090     }
1091 }
1092
1093 impl<'tcx> MirVisitable<'tcx> for Terminator<'tcx> {
1094     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1095         visitor.visit_terminator(self, location)
1096     }
1097 }
1098
1099 impl<'tcx> MirVisitable<'tcx> for Option<Terminator<'tcx>> {
1100     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1101         visitor.visit_terminator(self.as_ref().unwrap(), location)
1102     }
1103 }
1104
1105 /// Extra information passed to `visit_ty` and friends to give context
1106 /// about where the type etc appears.
1107 #[derive(Debug)]
1108 pub enum TyContext {
1109     LocalDecl {
1110         /// The index of the local variable we are visiting.
1111         local: Local,
1112
1113         /// The source location where this local variable was declared.
1114         source_info: SourceInfo,
1115     },
1116
1117     /// The inferred type of a user type annotation.
1118     UserTy(Span),
1119
1120     /// The return type of the function.
1121     ReturnTy(SourceInfo),
1122
1123     YieldTy(SourceInfo),
1124
1125     /// A type found at some location.
1126     Location(Location),
1127 }
1128
1129 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1130 pub enum NonMutatingUseContext {
1131     /// Being inspected in some way, like loading a len.
1132     Inspect,
1133     /// Consumed as part of an operand.
1134     Copy,
1135     /// Consumed as part of an operand.
1136     Move,
1137     /// Shared borrow.
1138     SharedBorrow,
1139     /// Shallow borrow.
1140     ShallowBorrow,
1141     /// Unique borrow.
1142     UniqueBorrow,
1143     /// AddressOf for *const pointer.
1144     AddressOf,
1145     /// Used as base for another place, e.g., `x` in `x.y`. Will not mutate the place.
1146     /// For example, the projection `x.y` is not marked as a mutation in these cases:
1147     ///
1148     ///     z = x.y;
1149     ///     f(&x.y);
1150     ///
1151     Projection,
1152 }
1153
1154 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1155 pub enum MutatingUseContext {
1156     /// Appears as LHS of an assignment.
1157     Store,
1158     /// Can often be treated as a `Store`, but needs to be separate because
1159     /// ASM is allowed to read outputs as well, so a `Store`-`AsmOutput` sequence
1160     /// cannot be simplified the way a `Store`-`Store` can be.
1161     AsmOutput,
1162     /// Destination of a call.
1163     Call,
1164     /// Destination of a yield.
1165     Yield,
1166     /// Being dropped.
1167     Drop,
1168     /// Mutable borrow.
1169     Borrow,
1170     /// AddressOf for *mut pointer.
1171     AddressOf,
1172     /// Used as base for another place, e.g., `x` in `x.y`. Could potentially mutate the place.
1173     /// For example, the projection `x.y` is marked as a mutation in these cases:
1174     ///
1175     ///     x.y = ...;
1176     ///     f(&mut x.y);
1177     ///
1178     Projection,
1179     /// Retagging, a "Stacked Borrows" shadow state operation
1180     Retag,
1181 }
1182
1183 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1184 pub enum NonUseContext {
1185     /// Starting a storage live range.
1186     StorageLive,
1187     /// Ending a storage live range.
1188     StorageDead,
1189     /// User type annotation assertions for NLL.
1190     AscribeUserTy,
1191     /// The data of an user variable, for debug info.
1192     VarDebugInfo,
1193 }
1194
1195 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1196 pub enum PlaceContext {
1197     NonMutatingUse(NonMutatingUseContext),
1198     MutatingUse(MutatingUseContext),
1199     NonUse(NonUseContext),
1200 }
1201
1202 impl PlaceContext {
1203     /// Returns `true` if this place context represents a drop.
1204     pub fn is_drop(&self) -> bool {
1205         matches!(self, PlaceContext::MutatingUse(MutatingUseContext::Drop))
1206     }
1207
1208     /// Returns `true` if this place context represents a borrow.
1209     pub fn is_borrow(&self) -> bool {
1210         matches!(
1211             self,
1212             PlaceContext::NonMutatingUse(
1213                 NonMutatingUseContext::SharedBorrow
1214                     | NonMutatingUseContext::ShallowBorrow
1215                     | NonMutatingUseContext::UniqueBorrow
1216             ) | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
1217         )
1218     }
1219
1220     /// Returns `true` if this place context represents a storage live or storage dead marker.
1221     pub fn is_storage_marker(&self) -> bool {
1222         matches!(
1223             self,
1224             PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead)
1225         )
1226     }
1227
1228     /// Returns `true` if this place context represents a use that potentially changes the value.
1229     pub fn is_mutating_use(&self) -> bool {
1230         matches!(self, PlaceContext::MutatingUse(..))
1231     }
1232
1233     /// Returns `true` if this place context represents a use that does not change the value.
1234     pub fn is_nonmutating_use(&self) -> bool {
1235         matches!(self, PlaceContext::NonMutatingUse(..))
1236     }
1237
1238     /// Returns `true` if this place context represents a use.
1239     pub fn is_use(&self) -> bool {
1240         !matches!(self, PlaceContext::NonUse(..))
1241     }
1242
1243     /// Returns `true` if this place context represents an assignment statement.
1244     pub fn is_place_assignment(&self) -> bool {
1245         matches!(
1246             self,
1247             PlaceContext::MutatingUse(
1248                 MutatingUseContext::Store
1249                     | MutatingUseContext::Call
1250                     | MutatingUseContext::AsmOutput,
1251             )
1252         )
1253     }
1254 }