]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/visit.rs
Rollup merge of #91884 - woppopo:const_box, r=oli-obk
[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(gen) = &$($mutability)? body.generator {
245                     if let Some(yield_ty) = &$($mutability)? gen.yield_ty {
246                         self.visit_ty(
247                             yield_ty,
248                             TyContext::YieldTy(SourceInfo::outermost(span))
249                         );
250                     }
251                 }
252
253                 // for best performance, we want to use an iterator rather
254                 // than a for-loop, to avoid calling `body::Body::invalidate` for
255                 // each basic block.
256                 macro_rules! basic_blocks {
257                     (mut) => (body.basic_blocks_mut().iter_enumerated_mut());
258                     () => (body.basic_blocks().iter_enumerated());
259                 }
260                 for (bb, data) in basic_blocks!($($mutability)?) {
261                     self.visit_basic_block_data(bb, data);
262                 }
263
264                 for scope in &$($mutability)? body.source_scopes {
265                     self.visit_source_scope_data(scope);
266                 }
267
268                 self.visit_ty(
269                     &$($mutability)? body.return_ty(),
270                     TyContext::ReturnTy(SourceInfo::outermost(body.span))
271                 );
272
273                 for local in body.local_decls.indices() {
274                     self.visit_local_decl(local, & $($mutability)? body.local_decls[local]);
275                 }
276
277                 macro_rules! type_annotations {
278                     (mut) => (body.user_type_annotations.iter_enumerated_mut());
279                     () => (body.user_type_annotations.iter_enumerated());
280                 }
281
282                 for (index, annotation) in type_annotations!($($mutability)?) {
283                     self.visit_user_type_annotation(
284                         index, annotation
285                     );
286                 }
287
288                 for var_debug_info in &$($mutability)? body.var_debug_info {
289                     self.visit_var_debug_info(var_debug_info);
290                 }
291
292                 self.visit_span(&$($mutability)? body.span);
293
294                 for const_ in &$($mutability)? body.required_consts {
295                     let location = START_BLOCK.start_location();
296                     self.visit_constant(const_, location);
297                 }
298             }
299
300             fn super_basic_block_data(&mut self,
301                                       block: BasicBlock,
302                                       data: & $($mutability)? BasicBlockData<'tcx>) {
303                 let BasicBlockData {
304                     statements,
305                     terminator,
306                     is_cleanup: _
307                 } = data;
308
309                 let mut index = 0;
310                 for statement in statements {
311                     let location = Location { block, statement_index: index };
312                     self.visit_statement(statement, location);
313                     index += 1;
314                 }
315
316                 if let Some(terminator) = terminator {
317                     let location = Location { block, statement_index: index };
318                     self.visit_terminator(terminator, location);
319                 }
320             }
321
322             fn super_source_scope_data(
323                 &mut self,
324                 scope_data: & $($mutability)? SourceScopeData<'tcx>,
325             ) {
326                 let SourceScopeData {
327                     span,
328                     parent_scope,
329                     inlined,
330                     inlined_parent_scope,
331                     local_data: _,
332                 } = scope_data;
333
334                 self.visit_span(span);
335                 if let Some(parent_scope) = parent_scope {
336                     self.visit_source_scope(parent_scope);
337                 }
338                 if let Some((callee, callsite_span)) = inlined {
339                     let location = START_BLOCK.start_location();
340
341                     self.visit_span(callsite_span);
342
343                     let ty::Instance { def: callee_def, substs: callee_substs } = callee;
344                     match callee_def {
345                         ty::InstanceDef::Item(_def_id) => {}
346
347                         ty::InstanceDef::Intrinsic(_def_id) |
348                         ty::InstanceDef::VtableShim(_def_id) |
349                         ty::InstanceDef::ReifyShim(_def_id) |
350                         ty::InstanceDef::Virtual(_def_id, _) |
351                         ty::InstanceDef::ClosureOnceShim { call_once: _def_id, track_caller: _ } |
352                         ty::InstanceDef::DropGlue(_def_id, None) => {}
353
354                         ty::InstanceDef::FnPtrShim(_def_id, ty) |
355                         ty::InstanceDef::DropGlue(_def_id, Some(ty)) |
356                         ty::InstanceDef::CloneShim(_def_id, ty) => {
357                             // FIXME(eddyb) use a better `TyContext` here.
358                             self.visit_ty(ty, TyContext::Location(location));
359                         }
360                     }
361                     self.visit_substs(callee_substs, location);
362                 }
363                 if let Some(inlined_parent_scope) = inlined_parent_scope {
364                     self.visit_source_scope(inlined_parent_scope);
365                 }
366             }
367
368             fn super_statement(&mut self,
369                                statement: & $($mutability)? Statement<'tcx>,
370                                location: Location) {
371                 let Statement {
372                     source_info,
373                     kind,
374                 } = statement;
375
376                 self.visit_source_info(source_info);
377                 match kind {
378                     StatementKind::Assign(
379                         box(ref $($mutability)? place, ref $($mutability)? rvalue)
380                     ) => {
381                         self.visit_assign(place, rvalue, location);
382                     }
383                     StatementKind::FakeRead(box (_, place)) => {
384                         self.visit_place(
385                             place,
386                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
387                             location
388                         );
389                     }
390                     StatementKind::SetDiscriminant { place, .. } => {
391                         self.visit_place(
392                             place,
393                             PlaceContext::MutatingUse(MutatingUseContext::Store),
394                             location
395                         );
396                     }
397                     StatementKind::StorageLive(local) => {
398                         self.visit_local(
399                             local,
400                             PlaceContext::NonUse(NonUseContext::StorageLive),
401                             location
402                         );
403                     }
404                     StatementKind::StorageDead(local) => {
405                         self.visit_local(
406                             local,
407                             PlaceContext::NonUse(NonUseContext::StorageDead),
408                             location
409                         );
410                     }
411                     StatementKind::LlvmInlineAsm(asm) => {
412                         for output in & $($mutability)? asm.outputs[..] {
413                             self.visit_place(
414                                 output,
415                                 PlaceContext::MutatingUse(MutatingUseContext::LlvmAsmOutput),
416                                 location
417                             );
418                         }
419                         for (span, input) in & $($mutability)? asm.inputs[..] {
420                             self.visit_span(span);
421                             self.visit_operand(input, location);
422                         }
423                     }
424                     StatementKind::Retag(kind, place) => {
425                         self.visit_retag(kind, place, location);
426                     }
427                     StatementKind::AscribeUserType(
428                         box(ref $($mutability)? place, ref $($mutability)? user_ty),
429                         variance
430                     ) => {
431                         self.visit_ascribe_user_ty(place, variance, user_ty, location);
432                     }
433                     StatementKind::Coverage(coverage) => {
434                         self.visit_coverage(
435                             coverage,
436                             location
437                         )
438                     }
439                     StatementKind::CopyNonOverlapping(box crate::mir::CopyNonOverlapping{
440                       ref $($mutability)? src,
441                       ref $($mutability)? dst,
442                       ref $($mutability)? count,
443                     }) => {
444                       self.visit_operand(src, location);
445                       self.visit_operand(dst, location);
446                       self.visit_operand(count, location)
447                     }
448                     StatementKind::Nop => {}
449                 }
450             }
451
452             fn super_assign(&mut self,
453                             place: &$($mutability)? Place<'tcx>,
454                             rvalue: &$($mutability)? Rvalue<'tcx>,
455                             location: Location) {
456                 self.visit_place(
457                     place,
458                     PlaceContext::MutatingUse(MutatingUseContext::Store),
459                     location
460                 );
461                 self.visit_rvalue(rvalue, location);
462             }
463
464             fn super_terminator(&mut self,
465                                 terminator: &$($mutability)? Terminator<'tcx>,
466                                 location: Location) {
467                 let Terminator { source_info, kind } = terminator;
468
469                 self.visit_source_info(source_info);
470                 match kind {
471                     TerminatorKind::Goto { .. } |
472                     TerminatorKind::Resume |
473                     TerminatorKind::Abort |
474                     TerminatorKind::GeneratorDrop |
475                     TerminatorKind::Unreachable |
476                     TerminatorKind::FalseEdge { .. } |
477                     TerminatorKind::FalseUnwind { .. } => {
478                     }
479
480                     TerminatorKind::Return => {
481                         // `return` logically moves from the return place `_0`. Note that the place
482                         // cannot be changed by any visitor, though.
483                         let $($mutability)? local = RETURN_PLACE;
484                         self.visit_local(
485                             & $($mutability)? local,
486                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Move),
487                             location,
488                         );
489
490                         assert_eq!(
491                             local,
492                             RETURN_PLACE,
493                             "`MutVisitor` tried to mutate return place of `return` terminator"
494                         );
495                     }
496
497                     TerminatorKind::SwitchInt {
498                         discr,
499                         switch_ty,
500                         targets: _
501                     } => {
502                         self.visit_operand(discr, location);
503                         self.visit_ty(switch_ty, TyContext::Location(location));
504                     }
505
506                     TerminatorKind::Drop {
507                         place,
508                         target: _,
509                         unwind: _,
510                     } => {
511                         self.visit_place(
512                             place,
513                             PlaceContext::MutatingUse(MutatingUseContext::Drop),
514                             location
515                         );
516                     }
517
518                     TerminatorKind::DropAndReplace {
519                         place,
520                         value,
521                         target: _,
522                         unwind: _,
523                     } => {
524                         self.visit_place(
525                             place,
526                             PlaceContext::MutatingUse(MutatingUseContext::Drop),
527                             location
528                         );
529                         self.visit_operand(value, location);
530                     }
531
532                     TerminatorKind::Call {
533                         func,
534                         args,
535                         destination,
536                         cleanup: _,
537                         from_hir_call: _,
538                         fn_span: _
539                     } => {
540                         self.visit_operand(func, location);
541                         for arg in args {
542                             self.visit_operand(arg, location);
543                         }
544                         if let Some((destination, _)) = destination {
545                             self.visit_place(
546                                 destination,
547                                 PlaceContext::MutatingUse(MutatingUseContext::Call),
548                                 location
549                             );
550                         }
551                     }
552
553                     TerminatorKind::Assert {
554                         cond,
555                         expected: _,
556                         msg,
557                         target: _,
558                         cleanup: _,
559                     } => {
560                         self.visit_operand(cond, location);
561                         self.visit_assert_message(msg, location);
562                     }
563
564                     TerminatorKind::Yield {
565                         value,
566                         resume: _,
567                         resume_arg,
568                         drop: _,
569                     } => {
570                         self.visit_operand(value, location);
571                         self.visit_place(
572                             resume_arg,
573                             PlaceContext::MutatingUse(MutatingUseContext::Yield),
574                             location,
575                         );
576                     }
577
578                     TerminatorKind::InlineAsm {
579                         template: _,
580                         operands,
581                         options: _,
582                         line_spans: _,
583                         destination: _,
584                         cleanup: _,
585                     } => {
586                         for op in operands {
587                             match op {
588                                 InlineAsmOperand::In { value, .. } => {
589                                     self.visit_operand(value, location);
590                                 }
591                                 InlineAsmOperand::Out { place: Some(place), .. } => {
592                                     self.visit_place(
593                                         place,
594                                         PlaceContext::MutatingUse(MutatingUseContext::AsmOutput),
595                                         location,
596                                     );
597                                 }
598                                 InlineAsmOperand::InOut { in_value, out_place, .. } => {
599                                     self.visit_operand(in_value, location);
600                                     if let Some(out_place) = out_place {
601                                         self.visit_place(
602                                             out_place,
603                                             PlaceContext::MutatingUse(MutatingUseContext::AsmOutput),
604                                             location,
605                                         );
606                                     }
607                                 }
608                                 InlineAsmOperand::Const { value }
609                                 | InlineAsmOperand::SymFn { value } => {
610                                     self.visit_constant(value, location);
611                                 }
612                                 InlineAsmOperand::Out { place: None, .. }
613                                 | InlineAsmOperand::SymStatic { def_id: _ } => {}
614                             }
615                         }
616                     }
617                 }
618             }
619
620             fn super_assert_message(&mut self,
621                                     msg: & $($mutability)? AssertMessage<'tcx>,
622                                     location: Location) {
623                 use crate::mir::AssertKind::*;
624                 match msg {
625                     BoundsCheck { len, index } => {
626                         self.visit_operand(len, location);
627                         self.visit_operand(index, location);
628                     }
629                     Overflow(_, l, r) => {
630                         self.visit_operand(l, location);
631                         self.visit_operand(r, location);
632                     }
633                     OverflowNeg(op) | DivisionByZero(op) | RemainderByZero(op) => {
634                         self.visit_operand(op, location);
635                     }
636                     ResumedAfterReturn(_) | ResumedAfterPanic(_) => {
637                         // Nothing to visit
638                     }
639                 }
640             }
641
642             fn super_rvalue(&mut self,
643                             rvalue: & $($mutability)? Rvalue<'tcx>,
644                             location: Location) {
645                 match rvalue {
646                     Rvalue::Use(operand) => {
647                         self.visit_operand(operand, location);
648                     }
649
650                     Rvalue::Repeat(value, _) => {
651                         self.visit_operand(value, location);
652                     }
653
654                     Rvalue::ThreadLocalRef(_) => {}
655
656                     Rvalue::Ref(r, bk, path) => {
657                         self.visit_region(r, location);
658                         let ctx = match bk {
659                             BorrowKind::Shared => PlaceContext::NonMutatingUse(
660                                 NonMutatingUseContext::SharedBorrow
661                             ),
662                             BorrowKind::Shallow => PlaceContext::NonMutatingUse(
663                                 NonMutatingUseContext::ShallowBorrow
664                             ),
665                             BorrowKind::Unique => PlaceContext::NonMutatingUse(
666                                 NonMutatingUseContext::UniqueBorrow
667                             ),
668                             BorrowKind::Mut { .. } =>
669                                 PlaceContext::MutatingUse(MutatingUseContext::Borrow),
670                         };
671                         self.visit_place(path, ctx, location);
672                     }
673
674                     Rvalue::AddressOf(m, path) => {
675                         let ctx = match m {
676                             Mutability::Mut => PlaceContext::MutatingUse(
677                                 MutatingUseContext::AddressOf
678                             ),
679                             Mutability::Not => PlaceContext::NonMutatingUse(
680                                 NonMutatingUseContext::AddressOf
681                             ),
682                         };
683                         self.visit_place(path, ctx, location);
684                     }
685
686                     Rvalue::Len(path) => {
687                         self.visit_place(
688                             path,
689                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
690                             location
691                         );
692                     }
693
694                     Rvalue::Cast(_cast_kind, operand, ty) => {
695                         self.visit_operand(operand, location);
696                         self.visit_ty(ty, TyContext::Location(location));
697                     }
698
699                     Rvalue::BinaryOp(_bin_op, box(lhs, rhs))
700                     | Rvalue::CheckedBinaryOp(_bin_op, box(lhs, rhs)) => {
701                         self.visit_operand(lhs, location);
702                         self.visit_operand(rhs, location);
703                     }
704
705                     Rvalue::UnaryOp(_un_op, op) => {
706                         self.visit_operand(op, location);
707                     }
708
709                     Rvalue::Discriminant(place) => {
710                         self.visit_place(
711                             place,
712                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
713                             location
714                         );
715                     }
716
717                     Rvalue::NullaryOp(_op, ty) => {
718                         self.visit_ty(ty, TyContext::Location(location));
719                     }
720
721                     Rvalue::Aggregate(kind, operands) => {
722                         let kind = &$($mutability)? **kind;
723                         match kind {
724                             AggregateKind::Array(ty) => {
725                                 self.visit_ty(ty, TyContext::Location(location));
726                             }
727                             AggregateKind::Tuple => {
728                             }
729                             AggregateKind::Adt(
730                                 _adt_def,
731                                 _variant_index,
732                                 substs,
733                                 _user_substs,
734                                 _active_field_index
735                             ) => {
736                                 self.visit_substs(substs, location);
737                             }
738                             AggregateKind::Closure(
739                                 _,
740                                 closure_substs
741                             ) => {
742                                 self.visit_substs(closure_substs, location);
743                             }
744                             AggregateKind::Generator(
745                                 _,
746                                 generator_substs,
747                                 _movability,
748                             ) => {
749                                 self.visit_substs(generator_substs, location);
750                             }
751                         }
752
753                         for operand in operands {
754                             self.visit_operand(operand, location);
755                         }
756                     }
757
758                     Rvalue::ShallowInitBox(operand, ty) => {
759                         self.visit_operand(operand, location);
760                         self.visit_ty(ty, TyContext::Location(location));
761                     }
762                 }
763             }
764
765             fn super_operand(&mut self,
766                              operand: & $($mutability)? Operand<'tcx>,
767                              location: Location) {
768                 match operand {
769                     Operand::Copy(place) => {
770                         self.visit_place(
771                             place,
772                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
773                             location
774                         );
775                     }
776                     Operand::Move(place) => {
777                         self.visit_place(
778                             place,
779                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Move),
780                             location
781                         );
782                     }
783                     Operand::Constant(constant) => {
784                         self.visit_constant(constant, location);
785                     }
786                 }
787             }
788
789             fn super_ascribe_user_ty(&mut self,
790                                      place: & $($mutability)? Place<'tcx>,
791                                      _variance: & $($mutability)? ty::Variance,
792                                      user_ty: & $($mutability)? UserTypeProjection,
793                                      location: Location) {
794                 self.visit_place(
795                     place,
796                     PlaceContext::NonUse(NonUseContext::AscribeUserTy),
797                     location
798                 );
799                 self.visit_user_type_projection(user_ty);
800             }
801
802             fn super_coverage(&mut self,
803                               _coverage: & $($mutability)? Coverage,
804                               _location: Location) {
805             }
806
807             fn super_retag(&mut self,
808                            _kind: & $($mutability)? RetagKind,
809                            place: & $($mutability)? Place<'tcx>,
810                            location: Location) {
811                 self.visit_place(
812                     place,
813                     PlaceContext::MutatingUse(MutatingUseContext::Retag),
814                     location,
815                 );
816             }
817
818             fn super_local_decl(&mut self,
819                                 local: Local,
820                                 local_decl: & $($mutability)? LocalDecl<'tcx>) {
821                 let LocalDecl {
822                     mutability: _,
823                     ty,
824                     user_ty,
825                     source_info,
826                     internal: _,
827                     local_info: _,
828                     is_block_tail: _,
829                 } = local_decl;
830
831                 self.visit_ty(ty, TyContext::LocalDecl {
832                     local,
833                     source_info: *source_info,
834                 });
835                 if let Some(user_ty) = user_ty {
836                     for (user_ty, _) in & $($mutability)? user_ty.contents {
837                         self.visit_user_type_projection(user_ty);
838                     }
839                 }
840                 self.visit_source_info(source_info);
841             }
842
843             fn super_var_debug_info(&mut self,
844                                     var_debug_info: & $($mutability)? VarDebugInfo<'tcx>) {
845                 let VarDebugInfo {
846                     name: _,
847                     source_info,
848                     value,
849                 } = var_debug_info;
850
851                 self.visit_source_info(source_info);
852                 let location = START_BLOCK.start_location();
853                 match value {
854                     VarDebugInfoContents::Const(c) => self.visit_constant(c, location),
855                     VarDebugInfoContents::Place(place) =>
856                         self.visit_place(
857                             place,
858                             PlaceContext::NonUse(NonUseContext::VarDebugInfo),
859                             location
860                         ),
861                 }
862             }
863
864             fn super_source_scope(&mut self,
865                                       _scope: & $($mutability)? SourceScope) {
866             }
867
868             fn super_constant(&mut self,
869                               constant: & $($mutability)? Constant<'tcx>,
870                               location: Location) {
871                 let Constant {
872                     span,
873                     user_ty,
874                     literal,
875                 } = constant;
876
877                 self.visit_span(span);
878                 drop(user_ty); // no visit method for this
879                 match literal {
880                     ConstantKind::Ty(ct) => self.visit_const(ct, location),
881                     ConstantKind::Val(_, t) => self.visit_ty(t, TyContext::Location(location)),
882                 }
883             }
884
885             fn super_span(&mut self, _span: & $($mutability)? Span) {
886             }
887
888             fn super_source_info(&mut self, source_info: & $($mutability)? SourceInfo) {
889                 let SourceInfo {
890                     span,
891                     scope,
892                 } = source_info;
893
894                 self.visit_span(span);
895                 self.visit_source_scope(scope);
896             }
897
898             fn super_user_type_projection(
899                 &mut self,
900                 _ty: & $($mutability)? UserTypeProjection,
901             ) {
902             }
903
904             fn super_user_type_annotation(
905                 &mut self,
906                 _index: UserTypeAnnotationIndex,
907                 ty: & $($mutability)? CanonicalUserTypeAnnotation<'tcx>,
908             ) {
909                 self.visit_span(& $($mutability)? ty.span);
910                 self.visit_ty(& $($mutability)? ty.inferred_ty, TyContext::UserTy(ty.span));
911             }
912
913             fn super_ty(&mut self, _ty: $(& $mutability)? Ty<'tcx>) {
914             }
915
916             fn super_region(&mut self, _region: & $($mutability)? ty::Region<'tcx>) {
917             }
918
919             fn super_const(&mut self, _const: & $($mutability)? &'tcx ty::Const<'tcx>) {
920             }
921
922             fn super_substs(&mut self, _substs: & $($mutability)? SubstsRef<'tcx>) {
923             }
924
925             // Convenience methods
926
927             fn visit_location(
928                 &mut self,
929                 body: &$($mutability)? Body<'tcx>,
930                 location: Location
931             ) {
932                 macro_rules! basic_blocks {
933                     (mut) => (body.basic_blocks_mut());
934                     () => (body.basic_blocks());
935                 }
936                 let basic_block = & $($mutability)? basic_blocks!($($mutability)?)[location.block];
937                 if basic_block.statements.len() == location.statement_index {
938                     if let Some(ref $($mutability)? terminator) = basic_block.terminator {
939                         self.visit_terminator(terminator, location)
940                     }
941                 } else {
942                     let statement = & $($mutability)?
943                         basic_block.statements[location.statement_index];
944                     self.visit_statement(statement, location)
945                 }
946             }
947         }
948     }
949 }
950
951 macro_rules! visit_place_fns {
952     (mut) => {
953         fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
954
955         fn super_place(
956             &mut self,
957             place: &mut Place<'tcx>,
958             context: PlaceContext,
959             location: Location,
960         ) {
961             self.visit_local(&mut place.local, context, location);
962
963             if let Some(new_projection) = self.process_projection(&place.projection, location) {
964                 place.projection = self.tcx().intern_place_elems(&new_projection);
965             }
966         }
967
968         fn process_projection<'a>(
969             &mut self,
970             projection: &'a [PlaceElem<'tcx>],
971             location: Location,
972         ) -> Option<Vec<PlaceElem<'tcx>>> {
973             let mut projection = Cow::Borrowed(projection);
974
975             for i in 0..projection.len() {
976                 if let Some(&elem) = projection.get(i) {
977                     if let Some(elem) = self.process_projection_elem(elem, location) {
978                         // This converts the borrowed projection into `Cow::Owned(_)` and returns a
979                         // clone of the projection so we can mutate and reintern later.
980                         let vec = projection.to_mut();
981                         vec[i] = elem;
982                     }
983                 }
984             }
985
986             match projection {
987                 Cow::Borrowed(_) => None,
988                 Cow::Owned(vec) => Some(vec),
989             }
990         }
991
992         fn process_projection_elem(
993             &mut self,
994             elem: PlaceElem<'tcx>,
995             location: Location,
996         ) -> Option<PlaceElem<'tcx>> {
997             match elem {
998                 PlaceElem::Index(local) => {
999                     let mut new_local = local;
1000                     self.visit_local(
1001                         &mut new_local,
1002                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
1003                         location,
1004                     );
1005
1006                     if new_local == local { None } else { Some(PlaceElem::Index(new_local)) }
1007                 }
1008                 PlaceElem::Field(field, ty) => {
1009                     let mut new_ty = ty;
1010                     self.visit_ty(&mut new_ty, TyContext::Location(location));
1011                     if ty != new_ty { Some(PlaceElem::Field(field, new_ty)) } else { None }
1012                 }
1013                 PlaceElem::Deref
1014                 | PlaceElem::ConstantIndex { .. }
1015                 | PlaceElem::Subslice { .. }
1016                 | PlaceElem::Downcast(..) => None,
1017             }
1018         }
1019     };
1020
1021     () => {
1022         fn visit_projection(
1023             &mut self,
1024             place_ref: PlaceRef<'tcx>,
1025             context: PlaceContext,
1026             location: Location,
1027         ) {
1028             self.super_projection(place_ref, context, location);
1029         }
1030
1031         fn visit_projection_elem(
1032             &mut self,
1033             local: Local,
1034             proj_base: &[PlaceElem<'tcx>],
1035             elem: PlaceElem<'tcx>,
1036             context: PlaceContext,
1037             location: Location,
1038         ) {
1039             self.super_projection_elem(local, proj_base, elem, context, location);
1040         }
1041
1042         fn super_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1043             let mut context = context;
1044
1045             if !place.projection.is_empty() {
1046                 if context.is_use() {
1047                     // ^ Only change the context if it is a real use, not a "use" in debuginfo.
1048                     context = if context.is_mutating_use() {
1049                         PlaceContext::MutatingUse(MutatingUseContext::Projection)
1050                     } else {
1051                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
1052                     };
1053                 }
1054             }
1055
1056             self.visit_local(&place.local, context, location);
1057
1058             self.visit_projection(place.as_ref(), context, location);
1059         }
1060
1061         fn super_projection(
1062             &mut self,
1063             place_ref: PlaceRef<'tcx>,
1064             context: PlaceContext,
1065             location: Location,
1066         ) {
1067             // FIXME: Use PlaceRef::iter_projections, once that exists.
1068             let mut cursor = place_ref.projection;
1069             while let &[ref proj_base @ .., elem] = cursor {
1070                 cursor = proj_base;
1071                 self.visit_projection_elem(place_ref.local, cursor, elem, context, location);
1072             }
1073         }
1074
1075         fn super_projection_elem(
1076             &mut self,
1077             _local: Local,
1078             _proj_base: &[PlaceElem<'tcx>],
1079             elem: PlaceElem<'tcx>,
1080             _context: PlaceContext,
1081             location: Location,
1082         ) {
1083             match elem {
1084                 ProjectionElem::Field(_field, ty) => {
1085                     self.visit_ty(ty, TyContext::Location(location));
1086                 }
1087                 ProjectionElem::Index(local) => {
1088                     self.visit_local(
1089                         &local,
1090                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
1091                         location,
1092                     );
1093                 }
1094                 ProjectionElem::Deref
1095                 | ProjectionElem::Subslice { from: _, to: _, from_end: _ }
1096                 | ProjectionElem::ConstantIndex { offset: _, min_length: _, from_end: _ }
1097                 | ProjectionElem::Downcast(_, _) => {}
1098             }
1099         }
1100     };
1101 }
1102
1103 make_mir_visitor!(Visitor,);
1104 make_mir_visitor!(MutVisitor, mut);
1105
1106 pub trait MirVisitable<'tcx> {
1107     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>);
1108 }
1109
1110 impl<'tcx> MirVisitable<'tcx> for Statement<'tcx> {
1111     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1112         visitor.visit_statement(self, location)
1113     }
1114 }
1115
1116 impl<'tcx> MirVisitable<'tcx> for Terminator<'tcx> {
1117     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1118         visitor.visit_terminator(self, location)
1119     }
1120 }
1121
1122 impl<'tcx> MirVisitable<'tcx> for Option<Terminator<'tcx>> {
1123     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1124         visitor.visit_terminator(self.as_ref().unwrap(), location)
1125     }
1126 }
1127
1128 /// Extra information passed to `visit_ty` and friends to give context
1129 /// about where the type etc appears.
1130 #[derive(Debug)]
1131 pub enum TyContext {
1132     LocalDecl {
1133         /// The index of the local variable we are visiting.
1134         local: Local,
1135
1136         /// The source location where this local variable was declared.
1137         source_info: SourceInfo,
1138     },
1139
1140     /// The inferred type of a user type annotation.
1141     UserTy(Span),
1142
1143     /// The return type of the function.
1144     ReturnTy(SourceInfo),
1145
1146     YieldTy(SourceInfo),
1147
1148     /// A type found at some location.
1149     Location(Location),
1150 }
1151
1152 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1153 pub enum NonMutatingUseContext {
1154     /// Being inspected in some way, like loading a len.
1155     Inspect,
1156     /// Consumed as part of an operand.
1157     Copy,
1158     /// Consumed as part of an operand.
1159     Move,
1160     /// Shared borrow.
1161     SharedBorrow,
1162     /// Shallow borrow.
1163     ShallowBorrow,
1164     /// Unique borrow.
1165     UniqueBorrow,
1166     /// AddressOf for *const pointer.
1167     AddressOf,
1168     /// Used as base for another place, e.g., `x` in `x.y`. Will not mutate the place.
1169     /// For example, the projection `x.y` is not marked as a mutation in these cases:
1170     ///
1171     ///     z = x.y;
1172     ///     f(&x.y);
1173     ///
1174     Projection,
1175 }
1176
1177 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1178 pub enum MutatingUseContext {
1179     /// Appears as LHS of an assignment.
1180     Store,
1181     /// Can often be treated as a `Store`, but needs to be separate because
1182     /// ASM is allowed to read outputs as well, so a `Store`-`LlvmAsmOutput` sequence
1183     /// cannot be simplified the way a `Store`-`Store` can be.
1184     LlvmAsmOutput,
1185     /// Output operand of an inline assembly block.
1186     AsmOutput,
1187     /// Destination of a call.
1188     Call,
1189     /// Destination of a yield.
1190     Yield,
1191     /// Being dropped.
1192     Drop,
1193     /// Mutable borrow.
1194     Borrow,
1195     /// AddressOf for *mut pointer.
1196     AddressOf,
1197     /// Used as base for another place, e.g., `x` in `x.y`. Could potentially mutate the place.
1198     /// For example, the projection `x.y` is marked as a mutation in these cases:
1199     ///
1200     ///     x.y = ...;
1201     ///     f(&mut x.y);
1202     ///
1203     Projection,
1204     /// Retagging, a "Stacked Borrows" shadow state operation
1205     Retag,
1206 }
1207
1208 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1209 pub enum NonUseContext {
1210     /// Starting a storage live range.
1211     StorageLive,
1212     /// Ending a storage live range.
1213     StorageDead,
1214     /// User type annotation assertions for NLL.
1215     AscribeUserTy,
1216     /// The data of a user variable, for debug info.
1217     VarDebugInfo,
1218 }
1219
1220 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1221 pub enum PlaceContext {
1222     NonMutatingUse(NonMutatingUseContext),
1223     MutatingUse(MutatingUseContext),
1224     NonUse(NonUseContext),
1225 }
1226
1227 impl PlaceContext {
1228     /// Returns `true` if this place context represents a drop.
1229     #[inline]
1230     pub fn is_drop(&self) -> bool {
1231         matches!(self, PlaceContext::MutatingUse(MutatingUseContext::Drop))
1232     }
1233
1234     /// Returns `true` if this place context represents a borrow.
1235     pub fn is_borrow(&self) -> bool {
1236         matches!(
1237             self,
1238             PlaceContext::NonMutatingUse(
1239                 NonMutatingUseContext::SharedBorrow
1240                     | NonMutatingUseContext::ShallowBorrow
1241                     | NonMutatingUseContext::UniqueBorrow
1242             ) | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
1243         )
1244     }
1245
1246     /// Returns `true` if this place context represents a storage live or storage dead marker.
1247     #[inline]
1248     pub fn is_storage_marker(&self) -> bool {
1249         matches!(
1250             self,
1251             PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead)
1252         )
1253     }
1254
1255     /// Returns `true` if this place context represents a use that potentially changes the value.
1256     #[inline]
1257     pub fn is_mutating_use(&self) -> bool {
1258         matches!(self, PlaceContext::MutatingUse(..))
1259     }
1260
1261     /// Returns `true` if this place context represents a use.
1262     #[inline]
1263     pub fn is_use(&self) -> bool {
1264         !matches!(self, PlaceContext::NonUse(..))
1265     }
1266
1267     /// Returns `true` if this place context represents an assignment statement.
1268     pub fn is_place_assignment(&self) -> bool {
1269         matches!(
1270             self,
1271             PlaceContext::MutatingUse(
1272                 MutatingUseContext::Store
1273                     | MutatingUseContext::Call
1274                     | MutatingUseContext::LlvmAsmOutput
1275                     | MutatingUseContext::AsmOutput,
1276             )
1277         )
1278     }
1279 }