]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
Merge remote-tracking branch 'rust-lang/master' into hermit
[rust.git] / src / librustc / mir / mod.rs
1 // ignore-tidy-filelength
2
3 //! MIR datatypes and passes. See the [rustc guide] for more info.
4 //!
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
6
7 use crate::hir::def::{CtorKind, Namespace};
8 use crate::hir::def_id::DefId;
9 use crate::hir::{self, InlineAsm as HirInlineAsm};
10 use crate::mir::interpret::{ConstValue, PanicInfo, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use crate::ty::adjustment::PointerCast;
13 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
14 use crate::ty::layout::VariantIdx;
15 use crate::ty::print::{FmtPrinter, Printer};
16 use crate::ty::subst::{Subst, SubstsRef};
17 use crate::ty::{
18     self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
19 };
20
21 use polonius_engine::Atom;
22 use rustc_index::bit_set::BitMatrix;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::{dominators, Dominators};
25 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_data_structures::sync::Lrc;
28 use rustc_data_structures::sync::MappedReadGuard;
29 use rustc_macros::HashStable;
30 use rustc_serialize::{Encodable, Decodable};
31 use smallvec::SmallVec;
32 use std::borrow::Cow;
33 use std::fmt::{self, Debug, Display, Formatter, Write};
34 use std::ops::{Index, IndexMut};
35 use std::slice;
36 use std::vec::IntoIter;
37 use std::{iter, mem, option, u32};
38 use syntax::ast::Name;
39 use syntax::symbol::Symbol;
40 use syntax_pos::{Span, DUMMY_SP};
41
42 pub use crate::mir::interpret::AssertMessage;
43
44 mod cache;
45 pub mod interpret;
46 pub mod mono;
47 pub mod tcx;
48 pub mod traversal;
49 pub mod visit;
50
51 /// Types for locals
52 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
53
54 pub trait HasLocalDecls<'tcx> {
55     fn local_decls(&self) -> &LocalDecls<'tcx>;
56 }
57
58 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
59     fn local_decls(&self) -> &LocalDecls<'tcx> {
60         self
61     }
62 }
63
64 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
65     fn local_decls(&self) -> &LocalDecls<'tcx> {
66         &self.local_decls
67     }
68 }
69
70 /// The various "big phases" that MIR goes through.
71 ///
72 /// Warning: ordering of variants is significant.
73 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
74 pub enum MirPhase {
75     Build = 0,
76     Const = 1,
77     Validated = 2,
78     Optimized = 3,
79 }
80
81 impl MirPhase {
82     /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
83     pub fn phase_index(&self) -> usize {
84         *self as usize
85     }
86 }
87
88 /// The lowered representation of a single function.
89 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
90 pub struct Body<'tcx> {
91     /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
92     /// that indexes into this vector.
93     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
94
95     /// Records how far through the "desugaring and optimization" process this particular
96     /// MIR has traversed. This is particularly useful when inlining, since in that context
97     /// we instantiate the promoted constants and add them to our promoted vector -- but those
98     /// promoted items have already been optimized, whereas ours have not. This field allows
99     /// us to see the difference and forego optimization on the inlined promoted items.
100     pub phase: MirPhase,
101
102     /// A list of source scopes; these are referenced by statements
103     /// and used for debuginfo. Indexed by a `SourceScope`.
104     pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
105
106     /// Crate-local information for each source scope, that can't (and
107     /// needn't) be tracked across crates.
108     pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
109
110     /// The yield type of the function, if it is a generator.
111     pub yield_ty: Option<Ty<'tcx>>,
112
113     /// Generator drop glue.
114     pub generator_drop: Option<Box<Body<'tcx>>>,
115
116     /// The layout of a generator. Produced by the state transformation.
117     pub generator_layout: Option<GeneratorLayout<'tcx>>,
118
119     /// Declarations of locals.
120     ///
121     /// The first local is the return value pointer, followed by `arg_count`
122     /// locals for the function arguments, followed by any user-declared
123     /// variables and temporaries.
124     pub local_decls: LocalDecls<'tcx>,
125
126     /// User type annotations.
127     pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
128
129     /// The number of arguments this function takes.
130     ///
131     /// Starting at local 1, `arg_count` locals will be provided by the caller
132     /// and can be assumed to be initialized.
133     ///
134     /// If this MIR was built for a constant, this will be 0.
135     pub arg_count: usize,
136
137     /// Mark an argument local (which must be a tuple) as getting passed as
138     /// its individual components at the LLVM level.
139     ///
140     /// This is used for the "rust-call" ABI.
141     pub spread_arg: Option<Local>,
142
143     /// Names and capture modes of all the closure upvars, assuming
144     /// the first argument is either the closure or a reference to it.
145     //
146     // NOTE(eddyb) This is *strictly* a temporary hack for codegen
147     // debuginfo generation, and will be removed at some point.
148     // Do **NOT** use it for anything else; upvar information should not be
149     // in the MIR, so please rely on local crate HIR or other side-channels.
150     pub __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
151
152     /// Mark this MIR of a const context other than const functions as having converted a `&&` or
153     /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
154     /// this conversion from happening and use short circuiting, we will cause the following code
155     /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
156     ///
157     /// List of places where control flow was destroyed. Used for error reporting.
158     pub control_flow_destroyed: Vec<(Span, String)>,
159
160     /// A span representing this MIR, for error reporting.
161     pub span: Span,
162
163     /// A cache for various calculations.
164     cache: cache::Cache,
165 }
166
167 impl<'tcx> Body<'tcx> {
168     pub fn new(
169         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
170         source_scopes: IndexVec<SourceScope, SourceScopeData>,
171         source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
172         yield_ty: Option<Ty<'tcx>>,
173         local_decls: LocalDecls<'tcx>,
174         user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
175         arg_count: usize,
176         __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
177         span: Span,
178         control_flow_destroyed: Vec<(Span, String)>,
179     ) -> Self {
180         // We need `arg_count` locals, and one for the return place.
181         assert!(
182             local_decls.len() >= arg_count + 1,
183             "expected at least {} locals, got {}",
184             arg_count + 1,
185             local_decls.len()
186         );
187
188         Body {
189             phase: MirPhase::Build,
190             basic_blocks,
191             source_scopes,
192             source_scope_local_data,
193             yield_ty,
194             generator_drop: None,
195             generator_layout: None,
196             local_decls,
197             user_type_annotations,
198             arg_count,
199             __upvar_debuginfo_codegen_only_do_not_use,
200             spread_arg: None,
201             span,
202             cache: cache::Cache::new(),
203             control_flow_destroyed,
204         }
205     }
206
207     #[inline]
208     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
209         &self.basic_blocks
210     }
211
212     #[inline]
213     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
214         self.cache.invalidate();
215         &mut self.basic_blocks
216     }
217
218     #[inline]
219     pub fn basic_blocks_and_local_decls_mut(
220         &mut self,
221     ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
222         self.cache.invalidate();
223         (&mut self.basic_blocks, &mut self.local_decls)
224     }
225
226     #[inline]
227     pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
228         self.cache.predecessors(self)
229     }
230
231     #[inline]
232     pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
233         MappedReadGuard::map(self.predecessors(), |p| &p[bb])
234     }
235
236     #[inline]
237     pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
238         let if_zero_locations = if loc.statement_index == 0 {
239             let predecessor_blocks = self.predecessors_for(loc.block);
240             let num_predecessor_blocks = predecessor_blocks.len();
241             Some(
242                 (0..num_predecessor_blocks)
243                     .map(move |i| predecessor_blocks[i])
244                     .map(move |bb| self.terminator_loc(bb)),
245             )
246         } else {
247             None
248         };
249
250         let if_not_zero_locations = if loc.statement_index == 0 {
251             None
252         } else {
253             Some(Location { block: loc.block, statement_index: loc.statement_index - 1 })
254         };
255
256         if_zero_locations.into_iter().flatten().chain(if_not_zero_locations)
257     }
258
259     #[inline]
260     pub fn dominators(&self) -> Dominators<BasicBlock> {
261         dominators(self)
262     }
263
264     /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
265     /// `START_BLOCK`.
266     pub fn is_cfg_cyclic(&self) -> bool {
267         graph::is_cyclic(self)
268     }
269
270     #[inline]
271     pub fn local_kind(&self, local: Local) -> LocalKind {
272         let index = local.as_usize();
273         if index == 0 {
274             debug_assert!(
275                 self.local_decls[local].mutability == Mutability::Mut,
276                 "return place should be mutable"
277             );
278
279             LocalKind::ReturnPointer
280         } else if index < self.arg_count + 1 {
281             LocalKind::Arg
282         } else if self.local_decls[local].name.is_some() {
283             LocalKind::Var
284         } else {
285             LocalKind::Temp
286         }
287     }
288
289     /// Returns an iterator over all temporaries.
290     #[inline]
291     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
292         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
293             let local = Local::new(index);
294             if self.local_decls[local].is_user_variable.is_some() {
295                 None
296             } else {
297                 Some(local)
298             }
299         })
300     }
301
302     /// Returns an iterator over all user-declared locals.
303     #[inline]
304     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
305         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
306             let local = Local::new(index);
307             if self.local_decls[local].is_user_variable.is_some() {
308                 Some(local)
309             } else {
310                 None
311             }
312         })
313     }
314
315     /// Returns an iterator over all user-declared mutable locals.
316     #[inline]
317     pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
318         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
319             let local = Local::new(index);
320             let decl = &self.local_decls[local];
321             if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
322                 Some(local)
323             } else {
324                 None
325             }
326         })
327     }
328
329     /// Returns an iterator over all user-declared mutable arguments and locals.
330     #[inline]
331     pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
332         (1..self.local_decls.len()).filter_map(move |index| {
333             let local = Local::new(index);
334             let decl = &self.local_decls[local];
335             if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
336                 && decl.mutability == Mutability::Mut
337             {
338                 Some(local)
339             } else {
340                 None
341             }
342         })
343     }
344
345     /// Returns an iterator over all function arguments.
346     #[inline]
347     pub fn args_iter(&self) -> impl Iterator<Item = Local> {
348         let arg_count = self.arg_count;
349         (1..=arg_count).map(Local::new)
350     }
351
352     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
353     /// locals that are neither arguments nor the return place).
354     #[inline]
355     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
356         let arg_count = self.arg_count;
357         let local_count = self.local_decls.len();
358         (arg_count + 1..local_count).map(Local::new)
359     }
360
361     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
362     /// invalidating statement indices in `Location`s.
363     pub fn make_statement_nop(&mut self, location: Location) {
364         let block = &mut self[location.block];
365         debug_assert!(location.statement_index < block.statements.len());
366         block.statements[location.statement_index].make_nop()
367     }
368
369     /// Returns the source info associated with `location`.
370     pub fn source_info(&self, location: Location) -> &SourceInfo {
371         let block = &self[location.block];
372         let stmts = &block.statements;
373         let idx = location.statement_index;
374         if idx < stmts.len() {
375             &stmts[idx].source_info
376         } else {
377             assert_eq!(idx, stmts.len());
378             &block.terminator().source_info
379         }
380     }
381
382     /// Checks if `sub` is a sub scope of `sup`
383     pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
384         while sub != sup {
385             match self.source_scopes[sub].parent_scope {
386                 None => return false,
387                 Some(p) => sub = p,
388             }
389         }
390         true
391     }
392
393     /// Returns the return type; it always return first element from `local_decls` array.
394     pub fn return_ty(&self) -> Ty<'tcx> {
395         self.local_decls[RETURN_PLACE].ty
396     }
397
398     /// Gets the location of the terminator for the given block.
399     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
400         Location { block: bb, statement_index: self[bb].statements.len() }
401     }
402 }
403
404 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
405 pub enum Safety {
406     Safe,
407     /// Unsafe because of a PushUnsafeBlock
408     BuiltinUnsafe,
409     /// Unsafe because of an unsafe fn
410     FnUnsafe,
411     /// Unsafe because of an `unsafe` block
412     ExplicitUnsafe(hir::HirId),
413 }
414
415 impl_stable_hash_for!(struct Body<'tcx> {
416     phase,
417     basic_blocks,
418     source_scopes,
419     source_scope_local_data,
420     yield_ty,
421     generator_drop,
422     generator_layout,
423     local_decls,
424     user_type_annotations,
425     arg_count,
426     __upvar_debuginfo_codegen_only_do_not_use,
427     spread_arg,
428     control_flow_destroyed,
429     span,
430     cache
431 });
432
433 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
434     type Output = BasicBlockData<'tcx>;
435
436     #[inline]
437     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
438         &self.basic_blocks()[index]
439     }
440 }
441
442 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
443     #[inline]
444     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
445         &mut self.basic_blocks_mut()[index]
446     }
447 }
448
449 #[derive(Copy, Clone, Debug, HashStable)]
450 pub enum ClearCrossCrate<T> {
451     Clear,
452     Set(T),
453 }
454
455 impl<T> ClearCrossCrate<T> {
456     pub fn assert_crate_local(self) -> T {
457         match self {
458             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
459             ClearCrossCrate::Set(v) => v,
460         }
461     }
462 }
463
464 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
465 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
466
467 /// Grouped information about the source code origin of a MIR entity.
468 /// Intended to be inspected by diagnostics and debuginfo.
469 /// Most passes can work with it as a whole, within a single function.
470 // The unoffical Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
471 // `Hash`. Please ping @bjorn3 if removing them.
472 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
473 pub struct SourceInfo {
474     /// The source span for the AST pertaining to this MIR entity.
475     pub span: Span,
476
477     /// The source scope, keeping track of which bindings can be
478     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
479     pub scope: SourceScope,
480 }
481
482 ///////////////////////////////////////////////////////////////////////////
483 // Mutability and borrow kinds
484
485 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
486 pub enum Mutability {
487     Mut,
488     Not,
489 }
490
491 impl From<Mutability> for hir::Mutability {
492     fn from(m: Mutability) -> Self {
493         match m {
494             Mutability::Mut => hir::Mutability::Mutable,
495             Mutability::Not => hir::Mutability::Immutable,
496         }
497     }
498 }
499
500 #[derive(
501     Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
502 )]
503 pub enum BorrowKind {
504     /// Data must be immutable and is aliasable.
505     Shared,
506
507     /// The immediately borrowed place must be immutable, but projections from
508     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
509     /// conflict with a mutable borrow of `a.b.c`.
510     ///
511     /// This is used when lowering matches: when matching on a place we want to
512     /// ensure that place have the same value from the start of the match until
513     /// an arm is selected. This prevents this code from compiling:
514     ///
515     ///     let mut x = &Some(0);
516     ///     match *x {
517     ///         None => (),
518     ///         Some(_) if { x = &None; false } => (),
519     ///         Some(_) => (),
520     ///     }
521     ///
522     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
523     /// should not prevent `if let None = x { ... }`, for example, because the
524     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
525     /// We can also report errors with this kind of borrow differently.
526     Shallow,
527
528     /// Data must be immutable but not aliasable. This kind of borrow
529     /// cannot currently be expressed by the user and is used only in
530     /// implicit closure bindings. It is needed when the closure is
531     /// borrowing or mutating a mutable referent, e.g.:
532     ///
533     ///     let x: &mut isize = ...;
534     ///     let y = || *x += 5;
535     ///
536     /// If we were to try to translate this closure into a more explicit
537     /// form, we'd encounter an error with the code as written:
538     ///
539     ///     struct Env { x: & &mut isize }
540     ///     let x: &mut isize = ...;
541     ///     let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
542     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
543     ///
544     /// This is then illegal because you cannot mutate an `&mut` found
545     /// in an aliasable location. To solve, you'd have to translate with
546     /// an `&mut` borrow:
547     ///
548     ///     struct Env { x: & &mut isize }
549     ///     let x: &mut isize = ...;
550     ///     let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
551     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
552     ///
553     /// Now the assignment to `**env.x` is legal, but creating a
554     /// mutable pointer to `x` is not because `x` is not mutable. We
555     /// could fix this by declaring `x` as `let mut x`. This is ok in
556     /// user code, if awkward, but extra weird for closures, since the
557     /// borrow is hidden.
558     ///
559     /// So we introduce a "unique imm" borrow -- the referent is
560     /// immutable, but not aliasable. This solves the problem. For
561     /// simplicity, we don't give users the way to express this
562     /// borrow, it's just used when translating closures.
563     Unique,
564
565     /// Data is mutable and not aliasable.
566     Mut {
567         /// `true` if this borrow arose from method-call auto-ref
568         /// (i.e., `adjustment::Adjust::Borrow`).
569         allow_two_phase_borrow: bool,
570     },
571 }
572
573 impl BorrowKind {
574     pub fn allows_two_phase_borrow(&self) -> bool {
575         match *self {
576             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
577             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
578         }
579     }
580 }
581
582 ///////////////////////////////////////////////////////////////////////////
583 // Variables and temps
584
585 rustc_index::newtype_index! {
586     pub struct Local {
587         derive [HashStable]
588         DEBUG_FORMAT = "_{}",
589         const RETURN_PLACE = 0,
590     }
591 }
592
593 impl Atom for Local {
594     fn index(self) -> usize {
595         Idx::index(self)
596     }
597 }
598
599 /// Classifies locals into categories. See `Body::local_kind`.
600 #[derive(PartialEq, Eq, Debug, HashStable)]
601 pub enum LocalKind {
602     /// User-declared variable binding.
603     Var,
604     /// Compiler-introduced temporary.
605     Temp,
606     /// Function argument.
607     Arg,
608     /// Location of function's return value.
609     ReturnPointer,
610 }
611
612 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
613 pub struct VarBindingForm<'tcx> {
614     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
615     pub binding_mode: ty::BindingMode,
616     /// If an explicit type was provided for this variable binding,
617     /// this holds the source Span of that type.
618     ///
619     /// NOTE: if you want to change this to a `HirId`, be wary that
620     /// doing so breaks incremental compilation (as of this writing),
621     /// while a `Span` does not cause our tests to fail.
622     pub opt_ty_info: Option<Span>,
623     /// Place of the RHS of the =, or the subject of the `match` where this
624     /// variable is initialized. None in the case of `let PATTERN;`.
625     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
626     /// (a) the right-hand side isn't evaluated as a place expression.
627     /// (b) it gives a way to separate this case from the remaining cases
628     ///     for diagnostics.
629     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
630     /// The span of the pattern in which this variable was bound.
631     pub pat_span: Span,
632 }
633
634 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
635 pub enum BindingForm<'tcx> {
636     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
637     Var(VarBindingForm<'tcx>),
638     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
639     ImplicitSelf(ImplicitSelfKind),
640     /// Reference used in a guard expression to ensure immutability.
641     RefForGuard,
642 }
643
644 /// Represents what type of implicit self a function has, if any.
645 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable)]
646 pub enum ImplicitSelfKind {
647     /// Represents a `fn x(self);`.
648     Imm,
649     /// Represents a `fn x(mut self);`.
650     Mut,
651     /// Represents a `fn x(&self);`.
652     ImmRef,
653     /// Represents a `fn x(&mut self);`.
654     MutRef,
655     /// Represents when a function does not have a self argument or
656     /// when a function has a `self: X` argument.
657     None,
658 }
659
660 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
661
662 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
663     binding_mode,
664     opt_ty_info,
665     opt_match_place,
666     pat_span
667 });
668
669 impl_stable_hash_for!(enum self::ImplicitSelfKind {
670     Imm,
671     Mut,
672     ImmRef,
673     MutRef,
674     None
675 });
676
677 impl_stable_hash_for!(enum self::MirPhase {
678     Build,
679     Const,
680     Validated,
681     Optimized,
682 });
683
684 mod binding_form_impl {
685     use crate::ich::StableHashingContext;
686     use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
687
688     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
689         fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
690             use super::BindingForm::*;
691             ::std::mem::discriminant(self).hash_stable(hcx, hasher);
692
693             match self {
694                 Var(binding) => binding.hash_stable(hcx, hasher),
695                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
696                 RefForGuard => (),
697             }
698         }
699     }
700 }
701
702 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
703 /// created during evaluation of expressions in a block tail
704 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
705 ///
706 /// It is used to improve diagnostics when such temporaries are
707 /// involved in borrow_check errors, e.g., explanations of where the
708 /// temporaries come from, when their destructors are run, and/or how
709 /// one might revise the code to satisfy the borrow checker's rules.
710 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
711 pub struct BlockTailInfo {
712     /// If `true`, then the value resulting from evaluating this tail
713     /// expression is ignored by the block's expression context.
714     ///
715     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
716     /// but not e.g., `let _x = { ...; tail };`
717     pub tail_result_is_ignored: bool,
718 }
719
720 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
721
722 /// A MIR local.
723 ///
724 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
725 /// argument, or the return place.
726 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
727 pub struct LocalDecl<'tcx> {
728     /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
729     ///
730     /// Temporaries and the return place are always mutable.
731     pub mutability: Mutability,
732
733     /// `Some(binding_mode)` if this corresponds to a user-declared local variable.
734     ///
735     /// This is solely used for local diagnostics when generating
736     /// warnings/errors when compiling the current crate, and
737     /// therefore it need not be visible across crates. pnkfelix
738     /// currently hypothesized we *need* to wrap this in a
739     /// `ClearCrossCrate` as long as it carries as `HirId`.
740     pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
741
742     /// `true` if this is an internal local.
743     ///
744     /// These locals are not based on types in the source code and are only used
745     /// for a few desugarings at the moment.
746     ///
747     /// The generator transformation will sanity check the locals which are live
748     /// across a suspension point against the type components of the generator
749     /// which type checking knows are live across a suspension point. We need to
750     /// flag drop flags to avoid triggering this check as they are introduced
751     /// after typeck.
752     ///
753     /// Unsafety checking will also ignore dereferences of these locals,
754     /// so they can be used for raw pointers only used in a desugaring.
755     ///
756     /// This should be sound because the drop flags are fully algebraic, and
757     /// therefore don't affect the OIBIT or outlives properties of the
758     /// generator.
759     pub internal: bool,
760
761     /// If this local is a temporary and `is_block_tail` is `Some`,
762     /// then it is a temporary created for evaluation of some
763     /// subexpression of some block's tail expression (with no
764     /// intervening statement context).
765     pub is_block_tail: Option<BlockTailInfo>,
766
767     /// The type of this local.
768     pub ty: Ty<'tcx>,
769
770     /// If the user manually ascribed a type to this variable,
771     /// e.g., via `let x: T`, then we carry that type here. The MIR
772     /// borrow checker needs this information since it can affect
773     /// region inference.
774     pub user_ty: UserTypeProjections,
775
776     /// The name of the local, used in debuginfo and pretty-printing.
777     ///
778     /// Note that function arguments can also have this set to `Some(_)`
779     /// to generate better debuginfo.
780     pub name: Option<Name>,
781
782     /// The *syntactic* (i.e., not visibility) source scope the local is defined
783     /// in. If the local was defined in a let-statement, this
784     /// is *within* the let-statement, rather than outside
785     /// of it.
786     ///
787     /// This is needed because the visibility source scope of locals within
788     /// a let-statement is weird.
789     ///
790     /// The reason is that we want the local to be *within* the let-statement
791     /// for lint purposes, but we want the local to be *after* the let-statement
792     /// for names-in-scope purposes.
793     ///
794     /// That's it, if we have a let-statement like the one in this
795     /// function:
796     ///
797     /// ```
798     /// fn foo(x: &str) {
799     ///     #[allow(unused_mut)]
800     ///     let mut x: u32 = { // <- one unused mut
801     ///         let mut y: u32 = x.parse().unwrap();
802     ///         y + 2
803     ///     };
804     ///     drop(x);
805     /// }
806     /// ```
807     ///
808     /// Then, from a lint point of view, the declaration of `x: u32`
809     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
810     /// lint scopes are the same as the AST/HIR nesting.
811     ///
812     /// However, from a name lookup point of view, the scopes look more like
813     /// as if the let-statements were `match` expressions:
814     ///
815     /// ```
816     /// fn foo(x: &str) {
817     ///     match {
818     ///         match x.parse().unwrap() {
819     ///             y => y + 2
820     ///         }
821     ///     } {
822     ///         x => drop(x)
823     ///     };
824     /// }
825     /// ```
826     ///
827     /// We care about the name-lookup scopes for debuginfo - if the
828     /// debuginfo instruction pointer is at the call to `x.parse()`, we
829     /// want `x` to refer to `x: &str`, but if it is at the call to
830     /// `drop(x)`, we want it to refer to `x: u32`.
831     ///
832     /// To allow both uses to work, we need to have more than a single scope
833     /// for a local. We have the `source_info.scope` represent the
834     /// "syntactic" lint scope (with a variable being under its let
835     /// block) while the `visibility_scope` represents the "local variable"
836     /// scope (where the "rest" of a block is under all prior let-statements).
837     ///
838     /// The end result looks like this:
839     ///
840     /// ```text
841     /// ROOT SCOPE
842     ///  │{ argument x: &str }
843     ///  │
844     ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
845     ///  │ │                         // in practice because I'm lazy.
846     ///  │ │
847     ///  │ │← x.source_info.scope
848     ///  │ │← `x.parse().unwrap()`
849     ///  │ │
850     ///  │ │ │← y.source_info.scope
851     ///  │ │
852     ///  │ │ │{ let y: u32 }
853     ///  │ │ │
854     ///  │ │ │← y.visibility_scope
855     ///  │ │ │← `y + 2`
856     ///  │
857     ///  │ │{ let x: u32 }
858     ///  │ │← x.visibility_scope
859     ///  │ │← `drop(x)` // This accesses `x: u32`.
860     /// ```
861     pub source_info: SourceInfo,
862
863     /// Source scope within which the local is visible (for debuginfo)
864     /// (see `source_info` for more details).
865     pub visibility_scope: SourceScope,
866 }
867
868 impl<'tcx> LocalDecl<'tcx> {
869     /// Returns `true` only if local is a binding that can itself be
870     /// made mutable via the addition of the `mut` keyword, namely
871     /// something like the occurrences of `x` in:
872     /// - `fn foo(x: Type) { ... }`,
873     /// - `let x = ...`,
874     /// - or `match ... { C(x) => ... }`
875     pub fn can_be_made_mutable(&self) -> bool {
876         match self.is_user_variable {
877             Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
878                 binding_mode: ty::BindingMode::BindByValue(_),
879                 opt_ty_info: _,
880                 opt_match_place: _,
881                 pat_span: _,
882             }))) => true,
883
884             Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm))) => true,
885
886             _ => false,
887         }
888     }
889
890     /// Returns `true` if local is definitely not a `ref ident` or
891     /// `ref mut ident` binding. (Such bindings cannot be made into
892     /// mutable bindings, but the inverse does not necessarily hold).
893     pub fn is_nonref_binding(&self) -> bool {
894         match self.is_user_variable {
895             Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
896                 binding_mode: ty::BindingMode::BindByValue(_),
897                 opt_ty_info: _,
898                 opt_match_place: _,
899                 pat_span: _,
900             }))) => true,
901
902             Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
903
904             _ => false,
905         }
906     }
907
908     /// Returns `true` if this is a reference to a variable bound in a `match`
909     /// expression that is used to access said variable for the guard of the
910     /// match arm.
911     pub fn is_ref_for_guard(&self) -> bool {
912         match self.is_user_variable {
913             Some(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
914             _ => false,
915         }
916     }
917
918     /// Returns `true` is the local is from a compiler desugaring, e.g.,
919     /// `__next` from a `for` loop.
920     #[inline]
921     pub fn from_compiler_desugaring(&self) -> bool {
922         self.source_info.span.desugaring_kind().is_some()
923     }
924
925     /// Creates a new `LocalDecl` for a temporary.
926     #[inline]
927     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
928         Self::new_local(ty, Mutability::Mut, false, span)
929     }
930
931     /// Converts `self` into same `LocalDecl` except tagged as immutable.
932     #[inline]
933     pub fn immutable(mut self) -> Self {
934         self.mutability = Mutability::Not;
935         self
936     }
937
938     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
939     #[inline]
940     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
941         assert!(self.is_block_tail.is_none());
942         self.is_block_tail = Some(info);
943         self
944     }
945
946     /// Creates a new `LocalDecl` for a internal temporary.
947     #[inline]
948     pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
949         Self::new_local(ty, Mutability::Mut, true, span)
950     }
951
952     #[inline]
953     fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
954         LocalDecl {
955             mutability,
956             ty,
957             user_ty: UserTypeProjections::none(),
958             name: None,
959             source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
960             visibility_scope: OUTERMOST_SOURCE_SCOPE,
961             internal,
962             is_user_variable: None,
963             is_block_tail: None,
964         }
965     }
966
967     /// Builds a `LocalDecl` for the return place.
968     ///
969     /// This must be inserted into the `local_decls` list as the first local.
970     #[inline]
971     pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
972         LocalDecl {
973             mutability: Mutability::Mut,
974             ty: return_ty,
975             user_ty: UserTypeProjections::none(),
976             source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
977             visibility_scope: OUTERMOST_SOURCE_SCOPE,
978             internal: false,
979             is_block_tail: None,
980             name: None, // FIXME maybe we do want some name here?
981             is_user_variable: None,
982         }
983     }
984 }
985
986 /// A closure capture, with its name and mode.
987 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
988 pub struct UpvarDebuginfo {
989     pub debug_name: Name,
990
991     /// If true, the capture is behind a reference.
992     pub by_ref: bool,
993 }
994
995 ///////////////////////////////////////////////////////////////////////////
996 // BasicBlock
997
998 rustc_index::newtype_index! {
999     pub struct BasicBlock {
1000         derive [HashStable]
1001         DEBUG_FORMAT = "bb{}",
1002         const START_BLOCK = 0,
1003     }
1004 }
1005
1006 impl BasicBlock {
1007     pub fn start_location(self) -> Location {
1008         Location { block: self, statement_index: 0 }
1009     }
1010 }
1011
1012 ///////////////////////////////////////////////////////////////////////////
1013 // BasicBlockData and Terminator
1014
1015 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1016 pub struct BasicBlockData<'tcx> {
1017     /// List of statements in this block.
1018     pub statements: Vec<Statement<'tcx>>,
1019
1020     /// Terminator for this block.
1021     ///
1022     /// N.B., this should generally ONLY be `None` during construction.
1023     /// Therefore, you should generally access it via the
1024     /// `terminator()` or `terminator_mut()` methods. The only
1025     /// exception is that certain passes, such as `simplify_cfg`, swap
1026     /// out the terminator temporarily with `None` while they continue
1027     /// to recurse over the set of basic blocks.
1028     pub terminator: Option<Terminator<'tcx>>,
1029
1030     /// If true, this block lies on an unwind path. This is used
1031     /// during codegen where distinct kinds of basic blocks may be
1032     /// generated (particularly for MSVC cleanup). Unwind blocks must
1033     /// only branch to other unwind blocks.
1034     pub is_cleanup: bool,
1035 }
1036
1037 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1038 pub struct Terminator<'tcx> {
1039     pub source_info: SourceInfo,
1040     pub kind: TerminatorKind<'tcx>,
1041 }
1042
1043 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1044 pub enum TerminatorKind<'tcx> {
1045     /// Block should have one successor in the graph; we jump there.
1046     Goto { target: BasicBlock },
1047
1048     /// Operand evaluates to an integer; jump depending on its value
1049     /// to one of the targets, and otherwise fallback to `otherwise`.
1050     SwitchInt {
1051         /// The discriminant value being tested.
1052         discr: Operand<'tcx>,
1053
1054         /// The type of value being tested.
1055         switch_ty: Ty<'tcx>,
1056
1057         /// Possible values. The locations to branch to in each case
1058         /// are found in the corresponding indices from the `targets` vector.
1059         values: Cow<'tcx, [u128]>,
1060
1061         /// Possible branch sites. The last element of this vector is used
1062         /// for the otherwise branch, so targets.len() == values.len() + 1
1063         /// should hold.
1064         //
1065         // This invariant is quite non-obvious and also could be improved.
1066         // One way to make this invariant is to have something like this instead:
1067         //
1068         // branches: Vec<(ConstInt, BasicBlock)>,
1069         // otherwise: Option<BasicBlock> // exhaustive if None
1070         //
1071         // However we’ve decided to keep this as-is until we figure a case
1072         // where some other approach seems to be strictly better than other.
1073         targets: Vec<BasicBlock>,
1074     },
1075
1076     /// Indicates that the landing pad is finished and unwinding should
1077     /// continue. Emitted by `build::scope::diverge_cleanup`.
1078     Resume,
1079
1080     /// Indicates that the landing pad is finished and that the process
1081     /// should abort. Used to prevent unwinding for foreign items.
1082     Abort,
1083
1084     /// Indicates a normal return. The return place should have
1085     /// been filled in by now. This should occur at most once.
1086     Return,
1087
1088     /// Indicates a terminator that can never be reached.
1089     Unreachable,
1090
1091     /// Drop the `Place`.
1092     Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1093
1094     /// Drop the `Place` and assign the new value over it. This ensures
1095     /// that the assignment to `P` occurs *even if* the destructor for
1096     /// place unwinds. Its semantics are best explained by the
1097     /// elaboration:
1098     ///
1099     /// ```
1100     /// BB0 {
1101     ///   DropAndReplace(P <- V, goto BB1, unwind BB2)
1102     /// }
1103     /// ```
1104     ///
1105     /// becomes
1106     ///
1107     /// ```
1108     /// BB0 {
1109     ///   Drop(P, goto BB1, unwind BB2)
1110     /// }
1111     /// BB1 {
1112     ///   // P is now uninitialized
1113     ///   P <- V
1114     /// }
1115     /// BB2 {
1116     ///   // P is now uninitialized -- its dtor panicked
1117     ///   P <- V
1118     /// }
1119     /// ```
1120     DropAndReplace {
1121         location: Place<'tcx>,
1122         value: Operand<'tcx>,
1123         target: BasicBlock,
1124         unwind: Option<BasicBlock>,
1125     },
1126
1127     /// Block ends with a call of a converging function.
1128     Call {
1129         /// The function that’s being called.
1130         func: Operand<'tcx>,
1131         /// Arguments the function is called with.
1132         /// These are owned by the callee, which is free to modify them.
1133         /// This allows the memory occupied by "by-value" arguments to be
1134         /// reused across function calls without duplicating the contents.
1135         args: Vec<Operand<'tcx>>,
1136         /// Destination for the return value. If some, the call is converging.
1137         destination: Option<(Place<'tcx>, BasicBlock)>,
1138         /// Cleanups to be done if the call unwinds.
1139         cleanup: Option<BasicBlock>,
1140         /// `true` if this is from a call in HIR rather than from an overloaded
1141         /// operator. True for overloaded function call.
1142         from_hir_call: bool,
1143     },
1144
1145     /// Jump to the target if the condition has the expected value,
1146     /// otherwise panic with a message and a cleanup target.
1147     Assert {
1148         cond: Operand<'tcx>,
1149         expected: bool,
1150         msg: AssertMessage<'tcx>,
1151         target: BasicBlock,
1152         cleanup: Option<BasicBlock>,
1153     },
1154
1155     /// A suspend point.
1156     Yield {
1157         /// The value to return.
1158         value: Operand<'tcx>,
1159         /// Where to resume to.
1160         resume: BasicBlock,
1161         /// Cleanup to be done if the generator is dropped at this suspend point.
1162         drop: Option<BasicBlock>,
1163     },
1164
1165     /// Indicates the end of the dropping of a generator.
1166     GeneratorDrop,
1167
1168     /// A block where control flow only ever takes one real path, but borrowck
1169     /// needs to be more conservative.
1170     FalseEdges {
1171         /// The target normal control flow will take.
1172         real_target: BasicBlock,
1173         /// A block control flow could conceptually jump to, but won't in
1174         /// practice.
1175         imaginary_target: BasicBlock,
1176     },
1177     /// A terminator for blocks that only take one path in reality, but where we
1178     /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1179     /// This can arise in infinite loops with no function calls for example.
1180     FalseUnwind {
1181         /// The target normal control flow will take.
1182         real_target: BasicBlock,
1183         /// The imaginary cleanup block link. This particular path will never be taken
1184         /// in practice, but in order to avoid fragility we want to always
1185         /// consider it in borrowck. We don't want to accept programs which
1186         /// pass borrowck only when `panic=abort` or some assertions are disabled
1187         /// due to release vs. debug mode builds. This needs to be an `Option` because
1188         /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1189         unwind: Option<BasicBlock>,
1190     },
1191 }
1192
1193 pub type Successors<'a> =
1194     iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1195 pub type SuccessorsMut<'a> =
1196     iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1197
1198 impl<'tcx> Terminator<'tcx> {
1199     pub fn successors(&self) -> Successors<'_> {
1200         self.kind.successors()
1201     }
1202
1203     pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1204         self.kind.successors_mut()
1205     }
1206
1207     pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1208         self.kind.unwind()
1209     }
1210
1211     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1212         self.kind.unwind_mut()
1213     }
1214 }
1215
1216 impl<'tcx> TerminatorKind<'tcx> {
1217     pub fn if_(
1218         tcx: TyCtxt<'tcx>,
1219         cond: Operand<'tcx>,
1220         t: BasicBlock,
1221         f: BasicBlock,
1222     ) -> TerminatorKind<'tcx> {
1223         static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1224         TerminatorKind::SwitchInt {
1225             discr: cond,
1226             switch_ty: tcx.types.bool,
1227             values: From::from(BOOL_SWITCH_FALSE),
1228             targets: vec![f, t],
1229         }
1230     }
1231
1232     pub fn successors(&self) -> Successors<'_> {
1233         use self::TerminatorKind::*;
1234         match *self {
1235             Resume
1236             | Abort
1237             | GeneratorDrop
1238             | Return
1239             | Unreachable
1240             | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1241             Goto { target: ref t }
1242             | Call { destination: None, cleanup: Some(ref t), .. }
1243             | Call { destination: Some((_, ref t)), cleanup: None, .. }
1244             | Yield { resume: ref t, drop: None, .. }
1245             | DropAndReplace { target: ref t, unwind: None, .. }
1246             | Drop { target: ref t, unwind: None, .. }
1247             | Assert { target: ref t, cleanup: None, .. }
1248             | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1249             Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1250             | Yield { resume: ref t, drop: Some(ref u), .. }
1251             | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1252             | Drop { target: ref t, unwind: Some(ref u), .. }
1253             | Assert { target: ref t, cleanup: Some(ref u), .. }
1254             | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1255                 Some(t).into_iter().chain(slice::from_ref(u))
1256             }
1257             SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1258             FalseEdges { ref real_target, ref imaginary_target } => {
1259                 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1260             }
1261         }
1262     }
1263
1264     pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1265         use self::TerminatorKind::*;
1266         match *self {
1267             Resume
1268             | Abort
1269             | GeneratorDrop
1270             | Return
1271             | Unreachable
1272             | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1273             Goto { target: ref mut t }
1274             | Call { destination: None, cleanup: Some(ref mut t), .. }
1275             | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1276             | Yield { resume: ref mut t, drop: None, .. }
1277             | DropAndReplace { target: ref mut t, unwind: None, .. }
1278             | Drop { target: ref mut t, unwind: None, .. }
1279             | Assert { target: ref mut t, cleanup: None, .. }
1280             | FalseUnwind { real_target: ref mut t, unwind: None } => {
1281                 Some(t).into_iter().chain(&mut [])
1282             }
1283             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1284             | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1285             | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1286             | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1287             | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1288             | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1289                 Some(t).into_iter().chain(slice::from_mut(u))
1290             }
1291             SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1292             FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1293                 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1294             }
1295         }
1296     }
1297
1298     pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1299         match *self {
1300             TerminatorKind::Goto { .. }
1301             | TerminatorKind::Resume
1302             | TerminatorKind::Abort
1303             | TerminatorKind::Return
1304             | TerminatorKind::Unreachable
1305             | TerminatorKind::GeneratorDrop
1306             | TerminatorKind::Yield { .. }
1307             | TerminatorKind::SwitchInt { .. }
1308             | TerminatorKind::FalseEdges { .. } => None,
1309             TerminatorKind::Call { cleanup: ref unwind, .. }
1310             | TerminatorKind::Assert { cleanup: ref unwind, .. }
1311             | TerminatorKind::DropAndReplace { ref unwind, .. }
1312             | TerminatorKind::Drop { ref unwind, .. }
1313             | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1314         }
1315     }
1316
1317     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1318         match *self {
1319             TerminatorKind::Goto { .. }
1320             | TerminatorKind::Resume
1321             | TerminatorKind::Abort
1322             | TerminatorKind::Return
1323             | TerminatorKind::Unreachable
1324             | TerminatorKind::GeneratorDrop
1325             | TerminatorKind::Yield { .. }
1326             | TerminatorKind::SwitchInt { .. }
1327             | TerminatorKind::FalseEdges { .. } => None,
1328             TerminatorKind::Call { cleanup: ref mut unwind, .. }
1329             | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1330             | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1331             | TerminatorKind::Drop { ref mut unwind, .. }
1332             | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1333         }
1334     }
1335 }
1336
1337 impl<'tcx> BasicBlockData<'tcx> {
1338     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1339         BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1340     }
1341
1342     /// Accessor for terminator.
1343     ///
1344     /// Terminator may not be None after construction of the basic block is complete. This accessor
1345     /// provides a convenience way to reach the terminator.
1346     pub fn terminator(&self) -> &Terminator<'tcx> {
1347         self.terminator.as_ref().expect("invalid terminator state")
1348     }
1349
1350     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1351         self.terminator.as_mut().expect("invalid terminator state")
1352     }
1353
1354     pub fn retain_statements<F>(&mut self, mut f: F)
1355     where
1356         F: FnMut(&mut Statement<'_>) -> bool,
1357     {
1358         for s in &mut self.statements {
1359             if !f(s) {
1360                 s.make_nop();
1361             }
1362         }
1363     }
1364
1365     pub fn expand_statements<F, I>(&mut self, mut f: F)
1366     where
1367         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1368         I: iter::TrustedLen<Item = Statement<'tcx>>,
1369     {
1370         // Gather all the iterators we'll need to splice in, and their positions.
1371         let mut splices: Vec<(usize, I)> = vec![];
1372         let mut extra_stmts = 0;
1373         for (i, s) in self.statements.iter_mut().enumerate() {
1374             if let Some(mut new_stmts) = f(s) {
1375                 if let Some(first) = new_stmts.next() {
1376                     // We can already store the first new statement.
1377                     *s = first;
1378
1379                     // Save the other statements for optimized splicing.
1380                     let remaining = new_stmts.size_hint().0;
1381                     if remaining > 0 {
1382                         splices.push((i + 1 + extra_stmts, new_stmts));
1383                         extra_stmts += remaining;
1384                     }
1385                 } else {
1386                     s.make_nop();
1387                 }
1388             }
1389         }
1390
1391         // Splice in the new statements, from the end of the block.
1392         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1393         // where a range of elements ("gap") is left uninitialized, with
1394         // splicing adding new elements to the end of that gap and moving
1395         // existing elements from before the gap to the end of the gap.
1396         // For now, this is safe code, emulating a gap but initializing it.
1397         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1398         self.statements.resize(
1399             gap.end,
1400             Statement {
1401                 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1402                 kind: StatementKind::Nop,
1403             },
1404         );
1405         for (splice_start, new_stmts) in splices.into_iter().rev() {
1406             let splice_end = splice_start + new_stmts.size_hint().0;
1407             while gap.end > splice_end {
1408                 gap.start -= 1;
1409                 gap.end -= 1;
1410                 self.statements.swap(gap.start, gap.end);
1411             }
1412             self.statements.splice(splice_start..splice_end, new_stmts);
1413             gap.end = splice_start;
1414         }
1415     }
1416
1417     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1418         if index < self.statements.len() {
1419             &self.statements[index]
1420         } else {
1421             &self.terminator
1422         }
1423     }
1424 }
1425
1426 impl<'tcx> Debug for TerminatorKind<'tcx> {
1427     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1428         self.fmt_head(fmt)?;
1429         let successor_count = self.successors().count();
1430         let labels = self.fmt_successor_labels();
1431         assert_eq!(successor_count, labels.len());
1432
1433         match successor_count {
1434             0 => Ok(()),
1435
1436             1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1437
1438             _ => {
1439                 write!(fmt, " -> [")?;
1440                 for (i, target) in self.successors().enumerate() {
1441                     if i > 0 {
1442                         write!(fmt, ", ")?;
1443                     }
1444                     write!(fmt, "{}: {:?}", labels[i], target)?;
1445                 }
1446                 write!(fmt, "]")
1447             }
1448         }
1449     }
1450 }
1451
1452 impl<'tcx> TerminatorKind<'tcx> {
1453     /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1454     /// successor basic block, if any. The only information not included is the list of possible
1455     /// successors, which may be rendered differently between the text and the graphviz format.
1456     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1457         use self::TerminatorKind::*;
1458         match *self {
1459             Goto { .. } => write!(fmt, "goto"),
1460             SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1461             Return => write!(fmt, "return"),
1462             GeneratorDrop => write!(fmt, "generator_drop"),
1463             Resume => write!(fmt, "resume"),
1464             Abort => write!(fmt, "abort"),
1465             Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1466             Unreachable => write!(fmt, "unreachable"),
1467             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1468             DropAndReplace { ref location, ref value, .. } => {
1469                 write!(fmt, "replace({:?} <- {:?})", location, value)
1470             }
1471             Call { ref func, ref args, ref destination, .. } => {
1472                 if let Some((ref destination, _)) = *destination {
1473                     write!(fmt, "{:?} = ", destination)?;
1474                 }
1475                 write!(fmt, "{:?}(", func)?;
1476                 for (index, arg) in args.iter().enumerate() {
1477                     if index > 0 {
1478                         write!(fmt, ", ")?;
1479                     }
1480                     write!(fmt, "{:?}", arg)?;
1481                 }
1482                 write!(fmt, ")")
1483             }
1484             Assert { ref cond, expected, ref msg, .. } => {
1485                 write!(fmt, "assert(")?;
1486                 if !expected {
1487                     write!(fmt, "!")?;
1488                 }
1489                 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1490             }
1491             FalseEdges { .. } => write!(fmt, "falseEdges"),
1492             FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1493         }
1494     }
1495
1496     /// Returns the list of labels for the edges to the successor basic blocks.
1497     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1498         use self::TerminatorKind::*;
1499         match *self {
1500             Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1501             Goto { .. } => vec!["".into()],
1502             SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1503                 let param_env = ty::ParamEnv::empty();
1504                 let switch_ty = tcx.lift(&switch_ty).unwrap();
1505                 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1506                 values
1507                     .iter()
1508                     .map(|&u| {
1509                         tcx.mk_const(ty::Const {
1510                             val: ConstValue::Scalar(Scalar::from_uint(u, size).into()),
1511                             ty: switch_ty,
1512                         })
1513                         .to_string()
1514                         .into()
1515                     })
1516                     .chain(iter::once("otherwise".into()))
1517                     .collect()
1518             }),
1519             Call { destination: Some(_), cleanup: Some(_), .. } => {
1520                 vec!["return".into(), "unwind".into()]
1521             }
1522             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1523             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1524             Call { destination: None, cleanup: None, .. } => vec![],
1525             Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1526             Yield { drop: None, .. } => vec!["resume".into()],
1527             DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1528                 vec!["return".into()]
1529             }
1530             DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1531                 vec!["return".into(), "unwind".into()]
1532             }
1533             Assert { cleanup: None, .. } => vec!["".into()],
1534             Assert { .. } => vec!["success".into(), "unwind".into()],
1535             FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1536             FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1537             FalseUnwind { unwind: None, .. } => vec!["real".into()],
1538         }
1539     }
1540 }
1541
1542 ///////////////////////////////////////////////////////////////////////////
1543 // Statements
1544
1545 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
1546 pub struct Statement<'tcx> {
1547     pub source_info: SourceInfo,
1548     pub kind: StatementKind<'tcx>,
1549 }
1550
1551 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1552 #[cfg(target_arch = "x86_64")]
1553 static_assert_size!(Statement<'_>, 32);
1554
1555 impl Statement<'_> {
1556     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1557     /// invalidating statement indices in `Location`s.
1558     pub fn make_nop(&mut self) {
1559         self.kind = StatementKind::Nop
1560     }
1561
1562     /// Changes a statement to a nop and returns the original statement.
1563     pub fn replace_nop(&mut self) -> Self {
1564         Statement {
1565             source_info: self.source_info,
1566             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1567         }
1568     }
1569 }
1570
1571 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1572 pub enum StatementKind<'tcx> {
1573     /// Write the RHS Rvalue to the LHS Place.
1574     Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1575
1576     /// This represents all the reading that a pattern match may do
1577     /// (e.g., inspecting constants and discriminant values), and the
1578     /// kind of pattern it comes from. This is in order to adapt potential
1579     /// error messages to these specific patterns.
1580     ///
1581     /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1582     /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1583     FakeRead(FakeReadCause, Box<Place<'tcx>>),
1584
1585     /// Write the discriminant for a variant to the enum Place.
1586     SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1587
1588     /// Start a live range for the storage of the local.
1589     StorageLive(Local),
1590
1591     /// End the current live range for the storage of the local.
1592     StorageDead(Local),
1593
1594     /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1595     /// of `StatementKind` low.
1596     InlineAsm(Box<InlineAsm<'tcx>>),
1597
1598     /// Retag references in the given place, ensuring they got fresh tags. This is
1599     /// part of the Stacked Borrows model. These statements are currently only interpreted
1600     /// by miri and only generated when "-Z mir-emit-retag" is passed.
1601     /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1602     /// for more details.
1603     Retag(RetagKind, Box<Place<'tcx>>),
1604
1605     /// Encodes a user's type ascription. These need to be preserved
1606     /// intact so that NLL can respect them. For example:
1607     ///
1608     ///     let a: T = y;
1609     ///
1610     /// The effect of this annotation is to relate the type `T_y` of the place `y`
1611     /// to the user-given type `T`. The effect depends on the specified variance:
1612     ///
1613     /// - `Covariant` -- requires that `T_y <: T`
1614     /// - `Contravariant` -- requires that `T_y :> T`
1615     /// - `Invariant` -- requires that `T_y == T`
1616     /// - `Bivariant` -- no effect
1617     AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1618
1619     /// No-op. Useful for deleting instructions without affecting statement indices.
1620     Nop,
1621 }
1622
1623 /// Describes what kind of retag is to be performed.
1624 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1625 pub enum RetagKind {
1626     /// The initial retag when entering a function.
1627     FnEntry,
1628     /// Retag preparing for a two-phase borrow.
1629     TwoPhase,
1630     /// Retagging raw pointers.
1631     Raw,
1632     /// A "normal" retag.
1633     Default,
1634 }
1635
1636 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1637 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
1638 pub enum FakeReadCause {
1639     /// Inject a fake read of the borrowed input at the end of each guards
1640     /// code.
1641     ///
1642     /// This should ensure that you cannot change the variant for an enum while
1643     /// you are in the midst of matching on it.
1644     ForMatchGuard,
1645
1646     /// `let x: !; match x {}` doesn't generate any read of x so we need to
1647     /// generate a read of x to check that it is initialized and safe.
1648     ForMatchedPlace,
1649
1650     /// A fake read of the RefWithinGuard version of a bind-by-value variable
1651     /// in a match guard to ensure that it's value hasn't change by the time
1652     /// we create the OutsideGuard version.
1653     ForGuardBinding,
1654
1655     /// Officially, the semantics of
1656     ///
1657     /// `let pattern = <expr>;`
1658     ///
1659     /// is that `<expr>` is evaluated into a temporary and then this temporary is
1660     /// into the pattern.
1661     ///
1662     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1663     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1664     /// but in some cases it can affect the borrow checker, as in #53695.
1665     /// Therefore, we insert a "fake read" here to ensure that we get
1666     /// appropriate errors.
1667     ForLet,
1668
1669     /// If we have an index expression like
1670     ///
1671     /// (*x)[1][{ x = y; 4}]
1672     ///
1673     /// then the first bounds check is invalidated when we evaluate the second
1674     /// index expression. Thus we create a fake borrow of `x` across the second
1675     /// indexer, which will cause a borrow check error.
1676     ForIndex,
1677 }
1678
1679 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1680 pub struct InlineAsm<'tcx> {
1681     pub asm: HirInlineAsm,
1682     pub outputs: Box<[Place<'tcx>]>,
1683     pub inputs: Box<[(Span, Operand<'tcx>)]>,
1684 }
1685
1686 impl Debug for Statement<'_> {
1687     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1688         use self::StatementKind::*;
1689         match self.kind {
1690             Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1691             FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1692             Retag(ref kind, ref place) => write!(
1693                 fmt,
1694                 "Retag({}{:?})",
1695                 match kind {
1696                     RetagKind::FnEntry => "[fn entry] ",
1697                     RetagKind::TwoPhase => "[2phase] ",
1698                     RetagKind::Raw => "[raw] ",
1699                     RetagKind::Default => "",
1700                 },
1701                 place,
1702             ),
1703             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1704             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1705             SetDiscriminant { ref place, variant_index } => {
1706                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1707             }
1708             InlineAsm(ref asm) => {
1709                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1710             }
1711             AscribeUserType(box(ref place, ref c_ty), ref variance) => {
1712                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1713             }
1714             Nop => write!(fmt, "nop"),
1715         }
1716     }
1717 }
1718
1719 ///////////////////////////////////////////////////////////////////////////
1720 // Places
1721
1722 /// A path to a value; something that can be evaluated without
1723 /// changing or disturbing program state.
1724 #[derive(
1725     Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable,
1726 )]
1727 pub struct Place<'tcx> {
1728     pub base: PlaceBase<'tcx>,
1729
1730     /// projection out of a place (access a field, deref a pointer, etc)
1731     pub projection: &'tcx List<PlaceElem<'tcx>>,
1732 }
1733
1734 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1735
1736 #[derive(
1737     Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1738 )]
1739 pub enum PlaceBase<'tcx> {
1740     /// local variable
1741     Local(Local),
1742
1743     /// static or static mut variable
1744     Static(Box<Static<'tcx>>),
1745 }
1746
1747 /// We store the normalized type to avoid requiring normalization when reading MIR
1748 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1749 pub struct Static<'tcx> {
1750     pub ty: Ty<'tcx>,
1751     pub kind: StaticKind<'tcx>,
1752     /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1753     /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1754     /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1755     /// into the calling frame.
1756     pub def_id: DefId,
1757 }
1758
1759 #[derive(
1760     Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1761 )]
1762 pub enum StaticKind<'tcx> {
1763     /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1764     /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1765     /// will adjust these substs when it inlines a function based on the substs at the callsite.
1766     Promoted(Promoted, SubstsRef<'tcx>),
1767     Static,
1768 }
1769
1770 impl_stable_hash_for!(struct Static<'tcx> {
1771     ty,
1772     kind,
1773     def_id
1774 });
1775
1776 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1777 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1778 pub enum ProjectionElem<V, T> {
1779     Deref,
1780     Field(Field, T),
1781     Index(V),
1782
1783     /// These indices are generated by slice patterns. Easiest to explain
1784     /// by example:
1785     ///
1786     /// ```
1787     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1788     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1789     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1790     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1791     /// ```
1792     ConstantIndex {
1793         /// index or -index (in Python terms), depending on from_end
1794         offset: u32,
1795         /// thing being indexed must be at least this long
1796         min_length: u32,
1797         /// counting backwards from end?
1798         from_end: bool,
1799     },
1800
1801     /// These indices are generated by slice patterns.
1802     ///
1803     /// slice[from:-to] in Python terms.
1804     Subslice {
1805         from: u32,
1806         to: u32,
1807     },
1808
1809     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1810     /// this for ADTs with more than one variant. It may be better to
1811     /// just introduce it always, or always for enums.
1812     ///
1813     /// The included Symbol is the name of the variant, used for printing MIR.
1814     Downcast(Option<Symbol>, VariantIdx),
1815 }
1816
1817 impl<V, T> ProjectionElem<V, T> {
1818     /// Returns `true` if the target of this projection may refer to a different region of memory
1819     /// than the base.
1820     fn is_indirect(&self) -> bool {
1821         match self {
1822             Self::Deref => true,
1823
1824             | Self::Field(_, _)
1825             | Self::Index(_)
1826             | Self::ConstantIndex { .. }
1827             | Self::Subslice { .. }
1828             | Self::Downcast(_, _)
1829             => false
1830         }
1831     }
1832 }
1833
1834 /// Alias for projections as they appear in places, where the base is a place
1835 /// and the index is a local.
1836 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1837
1838 impl<'tcx> Copy for PlaceElem<'tcx> { }
1839
1840 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1841 #[cfg(target_arch = "x86_64")]
1842 static_assert_size!(PlaceElem<'_>, 16);
1843
1844 /// Alias for projections as they appear in `UserTypeProjection`, where we
1845 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1846 pub type ProjectionKind = ProjectionElem<(), ()>;
1847
1848 rustc_index::newtype_index! {
1849     pub struct Field {
1850         derive [HashStable]
1851         DEBUG_FORMAT = "field[{}]"
1852     }
1853 }
1854
1855 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1856 pub struct PlaceRef<'a, 'tcx> {
1857     pub base: &'a PlaceBase<'tcx>,
1858     pub projection: &'a [PlaceElem<'tcx>],
1859 }
1860
1861 impl<'tcx> Place<'tcx> {
1862     // FIXME change this to a const fn by also making List::empty a const fn.
1863     pub fn return_place() -> Place<'tcx> {
1864         Place {
1865             base: PlaceBase::Local(RETURN_PLACE),
1866             projection: List::empty(),
1867         }
1868     }
1869
1870     /// Returns `true` if this `Place` contains a `Deref` projection.
1871     ///
1872     /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1873     /// same region of memory as its base.
1874     pub fn is_indirect(&self) -> bool {
1875         self.projection.iter().any(|elem| elem.is_indirect())
1876     }
1877
1878     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1879     /// a single deref of a local.
1880     //
1881     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1882     pub fn local_or_deref_local(&self) -> Option<Local> {
1883         match self.as_ref() {
1884             PlaceRef {
1885                 base: &PlaceBase::Local(local),
1886                 projection: &[],
1887             } |
1888             PlaceRef {
1889                 base: &PlaceBase::Local(local),
1890                 projection: &[ProjectionElem::Deref],
1891             } => Some(local),
1892             _ => None,
1893         }
1894     }
1895
1896     /// If this place represents a local variable like `_X` with no
1897     /// projections, return `Some(_X)`.
1898     pub fn as_local(&self) -> Option<Local> {
1899         self.as_ref().as_local()
1900     }
1901
1902     pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1903         PlaceRef {
1904             base: &self.base,
1905             projection: &self.projection,
1906         }
1907     }
1908 }
1909
1910 impl From<Local> for Place<'_> {
1911     fn from(local: Local) -> Self {
1912         Place {
1913             base: local.into(),
1914             projection: List::empty(),
1915         }
1916     }
1917 }
1918
1919 impl From<Local> for PlaceBase<'_> {
1920     fn from(local: Local) -> Self {
1921         PlaceBase::Local(local)
1922     }
1923 }
1924
1925 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1926     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1927     /// a single deref of a local.
1928     //
1929     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1930     pub fn local_or_deref_local(&self) -> Option<Local> {
1931         match self {
1932             PlaceRef {
1933                 base: PlaceBase::Local(local),
1934                 projection: [],
1935             } |
1936             PlaceRef {
1937                 base: PlaceBase::Local(local),
1938                 projection: [ProjectionElem::Deref],
1939             } => Some(*local),
1940             _ => None,
1941         }
1942     }
1943
1944     /// If this place represents a local variable like `_X` with no
1945     /// projections, return `Some(_X)`.
1946     pub fn as_local(&self) -> Option<Local> {
1947         match self {
1948             PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1949             _ => None,
1950         }
1951     }
1952 }
1953
1954 impl Debug for Place<'_> {
1955     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1956         for elem in self.projection.iter().rev() {
1957             match elem {
1958                 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1959                     write!(fmt, "(").unwrap();
1960                 }
1961                 ProjectionElem::Deref => {
1962                     write!(fmt, "(*").unwrap();
1963                 }
1964                 ProjectionElem::Index(_)
1965                 | ProjectionElem::ConstantIndex { .. }
1966                 | ProjectionElem::Subslice { .. } => {}
1967             }
1968         }
1969
1970         write!(fmt, "{:?}", self.base)?;
1971
1972         for elem in self.projection.iter() {
1973             match elem {
1974                 ProjectionElem::Downcast(Some(name), _index) => {
1975                     write!(fmt, " as {})", name)?;
1976                 }
1977                 ProjectionElem::Downcast(None, index) => {
1978                     write!(fmt, " as variant#{:?})", index)?;
1979                 }
1980                 ProjectionElem::Deref => {
1981                     write!(fmt, ")")?;
1982                 }
1983                 ProjectionElem::Field(field, ty) => {
1984                     write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1985                 }
1986                 ProjectionElem::Index(ref index) => {
1987                     write!(fmt, "[{:?}]", index)?;
1988                 }
1989                 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1990                     write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1991                 }
1992                 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1993                     write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1994                 }
1995                 ProjectionElem::Subslice { from, to } if *to == 0 => {
1996                     write!(fmt, "[{:?}:]", from)?;
1997                 }
1998                 ProjectionElem::Subslice { from, to } if *from == 0 => {
1999                     write!(fmt, "[:-{:?}]", to)?;
2000                 }
2001                 ProjectionElem::Subslice { from, to } => {
2002                     write!(fmt, "[{:?}:-{:?}]", from, to)?;
2003                 }
2004             }
2005         }
2006
2007         Ok(())
2008     }
2009 }
2010
2011 impl Debug for PlaceBase<'_> {
2012     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2013         match *self {
2014             PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2015             PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
2016                 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
2017             }
2018             PlaceBase::Static(box self::Static {
2019                 ty, kind: StaticKind::Promoted(promoted, _), def_id: _
2020             }) => {
2021                 write!(fmt, "({:?}: {:?})", promoted, ty)
2022             }
2023         }
2024     }
2025 }
2026
2027 ///////////////////////////////////////////////////////////////////////////
2028 // Scopes
2029
2030 rustc_index::newtype_index! {
2031     pub struct SourceScope {
2032         derive [HashStable]
2033         DEBUG_FORMAT = "scope[{}]",
2034         const OUTERMOST_SOURCE_SCOPE = 0,
2035     }
2036 }
2037
2038 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2039 pub struct SourceScopeData {
2040     pub span: Span,
2041     pub parent_scope: Option<SourceScope>,
2042 }
2043
2044 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2045 pub struct SourceScopeLocalData {
2046     /// An `HirId` with lint levels equivalent to this scope's lint levels.
2047     pub lint_root: hir::HirId,
2048     /// The unsafe block that contains this node.
2049     pub safety: Safety,
2050 }
2051
2052 ///////////////////////////////////////////////////////////////////////////
2053 // Operands
2054
2055 /// These are values that can appear inside an rvalue. They are intentionally
2056 /// limited to prevent rvalues from being nested in one another.
2057 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2058 pub enum Operand<'tcx> {
2059     /// Copy: The value must be available for use afterwards.
2060     ///
2061     /// This implies that the type of the place must be `Copy`; this is true
2062     /// by construction during build, but also checked by the MIR type checker.
2063     Copy(Place<'tcx>),
2064
2065     /// Move: The value (including old borrows of it) will not be used again.
2066     ///
2067     /// Safe for values of all types (modulo future developments towards `?Move`).
2068     /// Correct usage patterns are enforced by the borrow checker for safe code.
2069     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2070     Move(Place<'tcx>),
2071
2072     /// Synthesizes a constant value.
2073     Constant(Box<Constant<'tcx>>),
2074 }
2075
2076 impl<'tcx> Debug for Operand<'tcx> {
2077     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2078         use self::Operand::*;
2079         match *self {
2080             Constant(ref a) => write!(fmt, "{:?}", a),
2081             Copy(ref place) => write!(fmt, "{:?}", place),
2082             Move(ref place) => write!(fmt, "move {:?}", place),
2083         }
2084     }
2085 }
2086
2087 impl<'tcx> Operand<'tcx> {
2088     /// Convenience helper to make a constant that refers to the fn
2089     /// with given `DefId` and substs. Since this is used to synthesize
2090     /// MIR, assumes `user_ty` is None.
2091     pub fn function_handle(
2092         tcx: TyCtxt<'tcx>,
2093         def_id: DefId,
2094         substs: SubstsRef<'tcx>,
2095         span: Span,
2096     ) -> Self {
2097         let ty = tcx.type_of(def_id).subst(tcx, substs);
2098         Operand::Constant(box Constant {
2099             span,
2100             user_ty: None,
2101             literal: ty::Const::zero_sized(tcx, ty),
2102         })
2103     }
2104
2105     pub fn to_copy(&self) -> Self {
2106         match *self {
2107             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2108             Operand::Move(ref place) => Operand::Copy(place.clone()),
2109         }
2110     }
2111 }
2112
2113 ///////////////////////////////////////////////////////////////////////////
2114 /// Rvalues
2115
2116 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2117 pub enum Rvalue<'tcx> {
2118     /// x (either a move or copy, depending on type of x)
2119     Use(Operand<'tcx>),
2120
2121     /// [x; 32]
2122     Repeat(Operand<'tcx>, u64),
2123
2124     /// &x or &mut x
2125     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2126
2127     /// length of a [X] or [X;n] value
2128     Len(Place<'tcx>),
2129
2130     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2131
2132     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2133     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2134
2135     NullaryOp(NullOp, Ty<'tcx>),
2136     UnaryOp(UnOp, Operand<'tcx>),
2137
2138     /// Read the discriminant of an ADT.
2139     ///
2140     /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2141     /// be defined to return, say, a 0) if ADT is not an enum.
2142     Discriminant(Place<'tcx>),
2143
2144     /// Creates an aggregate value, like a tuple or struct. This is
2145     /// only needed because we want to distinguish `dest = Foo { x:
2146     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2147     /// that `Foo` has a destructor. These rvalues can be optimized
2148     /// away after type-checking and before lowering.
2149     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2150 }
2151
2152 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2153 pub enum CastKind {
2154     Misc,
2155     Pointer(PointerCast),
2156 }
2157
2158 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2159 pub enum AggregateKind<'tcx> {
2160     /// The type is of the element
2161     Array(Ty<'tcx>),
2162     Tuple,
2163
2164     /// The second field is the variant index. It's equal to 0 for struct
2165     /// and union expressions. The fourth field is
2166     /// active field number and is present only for union expressions
2167     /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2168     /// active field index would identity the field `c`
2169     Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2170
2171     Closure(DefId, SubstsRef<'tcx>),
2172     Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2173 }
2174
2175 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2176 pub enum BinOp {
2177     /// The `+` operator (addition)
2178     Add,
2179     /// The `-` operator (subtraction)
2180     Sub,
2181     /// The `*` operator (multiplication)
2182     Mul,
2183     /// The `/` operator (division)
2184     Div,
2185     /// The `%` operator (modulus)
2186     Rem,
2187     /// The `^` operator (bitwise xor)
2188     BitXor,
2189     /// The `&` operator (bitwise and)
2190     BitAnd,
2191     /// The `|` operator (bitwise or)
2192     BitOr,
2193     /// The `<<` operator (shift left)
2194     Shl,
2195     /// The `>>` operator (shift right)
2196     Shr,
2197     /// The `==` operator (equality)
2198     Eq,
2199     /// The `<` operator (less than)
2200     Lt,
2201     /// The `<=` operator (less than or equal to)
2202     Le,
2203     /// The `!=` operator (not equal to)
2204     Ne,
2205     /// The `>=` operator (greater than or equal to)
2206     Ge,
2207     /// The `>` operator (greater than)
2208     Gt,
2209     /// The `ptr.offset` operator
2210     Offset,
2211 }
2212
2213 impl BinOp {
2214     pub fn is_checkable(self) -> bool {
2215         use self::BinOp::*;
2216         match self {
2217             Add | Sub | Mul | Shl | Shr => true,
2218             _ => false,
2219         }
2220     }
2221 }
2222
2223 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2224 pub enum NullOp {
2225     /// Returns the size of a value of that type
2226     SizeOf,
2227     /// Creates a new uninitialized box for a value of that type
2228     Box,
2229 }
2230
2231 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2232 pub enum UnOp {
2233     /// The `!` operator for logical inversion
2234     Not,
2235     /// The `-` operator for negation
2236     Neg,
2237 }
2238
2239 impl<'tcx> Debug for Rvalue<'tcx> {
2240     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2241         use self::Rvalue::*;
2242
2243         match *self {
2244             Use(ref place) => write!(fmt, "{:?}", place),
2245             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2246             Len(ref a) => write!(fmt, "Len({:?})", a),
2247             Cast(ref kind, ref place, ref ty) => {
2248                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2249             }
2250             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2251             CheckedBinaryOp(ref op, ref a, ref b) => {
2252                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2253             }
2254             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2255             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2256             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2257             Ref(region, borrow_kind, ref place) => {
2258                 let kind_str = match borrow_kind {
2259                     BorrowKind::Shared => "",
2260                     BorrowKind::Shallow => "shallow ",
2261                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2262                 };
2263
2264                 // When printing regions, add trailing space if necessary.
2265                 let print_region = ty::tls::with(|tcx| {
2266                     tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2267                 });
2268                 let region = if print_region {
2269                     let mut region = region.to_string();
2270                     if region.len() > 0 {
2271                         region.push(' ');
2272                     }
2273                     region
2274                 } else {
2275                     // Do not even print 'static
2276                     String::new()
2277                 };
2278                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2279             }
2280
2281             Aggregate(ref kind, ref places) => {
2282                 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2283                     let mut tuple_fmt = fmt.debug_tuple("");
2284                     for place in places {
2285                         tuple_fmt.field(place);
2286                     }
2287                     tuple_fmt.finish()
2288                 }
2289
2290                 match **kind {
2291                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2292
2293                     AggregateKind::Tuple => match places.len() {
2294                         0 => write!(fmt, "()"),
2295                         1 => write!(fmt, "({:?},)", places[0]),
2296                         _ => fmt_tuple(fmt, places),
2297                     },
2298
2299                     AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2300                         let variant_def = &adt_def.variants[variant];
2301
2302                         let f = &mut *fmt;
2303                         ty::tls::with(|tcx| {
2304                             let substs = tcx.lift(&substs).expect("could not lift for printing");
2305                             FmtPrinter::new(tcx, f, Namespace::ValueNS)
2306                                 .print_def_path(variant_def.def_id, substs)?;
2307                             Ok(())
2308                         })?;
2309
2310                         match variant_def.ctor_kind {
2311                             CtorKind::Const => Ok(()),
2312                             CtorKind::Fn => fmt_tuple(fmt, places),
2313                             CtorKind::Fictive => {
2314                                 let mut struct_fmt = fmt.debug_struct("");
2315                                 for (field, place) in variant_def.fields.iter().zip(places) {
2316                                     struct_fmt.field(&field.ident.as_str(), place);
2317                                 }
2318                                 struct_fmt.finish()
2319                             }
2320                         }
2321                     }
2322
2323                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2324                         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2325                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2326                                 format!("[closure@{:?}]", hir_id)
2327                             } else {
2328                                 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2329                             };
2330                             let mut struct_fmt = fmt.debug_struct(&name);
2331
2332                             if let Some(upvars) = tcx.upvars(def_id) {
2333                                 for (&var_id, place) in upvars.keys().zip(places) {
2334                                     let var_name = tcx.hir().name(var_id);
2335                                     struct_fmt.field(&var_name.as_str(), place);
2336                                 }
2337                             }
2338
2339                             struct_fmt.finish()
2340                         } else {
2341                             write!(fmt, "[closure]")
2342                         }
2343                     }),
2344
2345                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2346                         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2347                             let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2348                             let mut struct_fmt = fmt.debug_struct(&name);
2349
2350                             if let Some(upvars) = tcx.upvars(def_id) {
2351                                 for (&var_id, place) in upvars.keys().zip(places) {
2352                                     let var_name = tcx.hir().name(var_id);
2353                                     struct_fmt.field(&var_name.as_str(), place);
2354                                 }
2355                             }
2356
2357                             struct_fmt.finish()
2358                         } else {
2359                             write!(fmt, "[generator]")
2360                         }
2361                     }),
2362                 }
2363             }
2364         }
2365     }
2366 }
2367
2368 ///////////////////////////////////////////////////////////////////////////
2369 /// Constants
2370 ///
2371 /// Two constants are equal if they are the same constant. Note that
2372 /// this does not necessarily mean that they are "==" in Rust -- in
2373 /// particular one must be wary of `NaN`!
2374
2375 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2376 pub struct Constant<'tcx> {
2377     pub span: Span,
2378
2379     /// Optional user-given type: for something like
2380     /// `collect::<Vec<_>>`, this would be present and would
2381     /// indicate that `Vec<_>` was explicitly specified.
2382     ///
2383     /// Needed for NLL to impose user-given type constraints.
2384     pub user_ty: Option<UserTypeAnnotationIndex>,
2385
2386     pub literal: &'tcx ty::Const<'tcx>,
2387 }
2388
2389 /// A collection of projections into user types.
2390 ///
2391 /// They are projections because a binding can occur a part of a
2392 /// parent pattern that has been ascribed a type.
2393 ///
2394 /// Its a collection because there can be multiple type ascriptions on
2395 /// the path from the root of the pattern down to the binding itself.
2396 ///
2397 /// An example:
2398 ///
2399 /// ```rust
2400 /// struct S<'a>((i32, &'a str), String);
2401 /// let S((_, w): (i32, &'static str), _): S = ...;
2402 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
2403 /// //  ---------------------------------  ^ (2)
2404 /// ```
2405 ///
2406 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2407 /// ascribed the type `(i32, &'static str)`.
2408 ///
2409 /// The highlights labelled `(2)` show the whole pattern being
2410 /// ascribed the type `S`.
2411 ///
2412 /// In this example, when we descend to `w`, we will have built up the
2413 /// following two projected types:
2414 ///
2415 ///   * base: `S`,                   projection: `(base.0).1`
2416 ///   * base: `(i32, &'static str)`, projection: `base.1`
2417 ///
2418 /// The first will lead to the constraint `w: &'1 str` (for some
2419 /// inferred region `'1`). The second will lead to the constraint `w:
2420 /// &'static str`.
2421 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2422 pub struct UserTypeProjections {
2423     pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2424 }
2425
2426 BraceStructTypeFoldableImpl! {
2427     impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections {
2428         contents
2429     }
2430 }
2431
2432 impl<'tcx> UserTypeProjections {
2433     pub fn none() -> Self {
2434         UserTypeProjections { contents: vec![] }
2435     }
2436
2437     pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2438         UserTypeProjections { contents: projs.collect() }
2439     }
2440
2441     pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2442         self.contents.iter()
2443     }
2444
2445     pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2446         self.contents.iter().map(|&(ref user_type, _span)| user_type)
2447     }
2448
2449     pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2450         self.contents.push((user_ty.clone(), span));
2451         self
2452     }
2453
2454     fn map_projections(
2455         mut self,
2456         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2457     ) -> Self {
2458         self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2459         self
2460     }
2461
2462     pub fn index(self) -> Self {
2463         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2464     }
2465
2466     pub fn subslice(self, from: u32, to: u32) -> Self {
2467         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2468     }
2469
2470     pub fn deref(self) -> Self {
2471         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2472     }
2473
2474     pub fn leaf(self, field: Field) -> Self {
2475         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2476     }
2477
2478     pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2479         self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2480     }
2481 }
2482
2483 /// Encodes the effect of a user-supplied type annotation on the
2484 /// subcomponents of a pattern. The effect is determined by applying the
2485 /// given list of proejctions to some underlying base type. Often,
2486 /// the projection element list `projs` is empty, in which case this
2487 /// directly encodes a type in `base`. But in the case of complex patterns with
2488 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2489 /// in which case the `projs` vector is used.
2490 ///
2491 /// Examples:
2492 ///
2493 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2494 ///
2495 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2496 ///   `field[0]` (aka `.0`), indicating that the type of `s` is
2497 ///   determined by finding the type of the `.0` field from `T`.
2498 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2499 pub struct UserTypeProjection {
2500     pub base: UserTypeAnnotationIndex,
2501     pub projs: Vec<ProjectionKind>,
2502 }
2503
2504 impl Copy for ProjectionKind {}
2505
2506 impl UserTypeProjection {
2507     pub(crate) fn index(mut self) -> Self {
2508         self.projs.push(ProjectionElem::Index(()));
2509         self
2510     }
2511
2512     pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2513         self.projs.push(ProjectionElem::Subslice { from, to });
2514         self
2515     }
2516
2517     pub(crate) fn deref(mut self) -> Self {
2518         self.projs.push(ProjectionElem::Deref);
2519         self
2520     }
2521
2522     pub(crate) fn leaf(mut self, field: Field) -> Self {
2523         self.projs.push(ProjectionElem::Field(field, ()));
2524         self
2525     }
2526
2527     pub(crate) fn variant(
2528         mut self,
2529         adt_def: &'tcx AdtDef,
2530         variant_index: VariantIdx,
2531         field: Field,
2532     ) -> Self {
2533         self.projs.push(ProjectionElem::Downcast(
2534             Some(adt_def.variants[variant_index].ident.name),
2535             variant_index,
2536         ));
2537         self.projs.push(ProjectionElem::Field(field, ()));
2538         self
2539     }
2540 }
2541
2542 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2543
2544 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2545     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2546         use crate::mir::ProjectionElem::*;
2547
2548         let base = self.base.fold_with(folder);
2549         let projs: Vec<_> = self
2550             .projs
2551             .iter()
2552             .map(|elem| match elem {
2553                 Deref => Deref,
2554                 Field(f, ()) => Field(f.clone(), ()),
2555                 Index(()) => Index(()),
2556                 elem => elem.clone(),
2557             })
2558             .collect();
2559
2560         UserTypeProjection { base, projs }
2561     }
2562
2563     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2564         self.base.visit_with(visitor)
2565         // Note: there's nothing in `self.proj` to visit.
2566     }
2567 }
2568
2569 rustc_index::newtype_index! {
2570     pub struct Promoted {
2571         derive [HashStable]
2572         DEBUG_FORMAT = "promoted[{}]"
2573     }
2574 }
2575
2576 impl<'tcx> Debug for Constant<'tcx> {
2577     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2578         write!(fmt, "{}", self)
2579     }
2580 }
2581
2582 impl<'tcx> Display for Constant<'tcx> {
2583     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2584         write!(fmt, "const ")?;
2585         // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2586         // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2587         // detailed and just not '{pointer}'.
2588         if let ty::RawPtr(_) = self.literal.ty.kind {
2589             write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2590         } else {
2591             write!(fmt, "{}", self.literal)
2592         }
2593     }
2594 }
2595
2596 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2597     type Node = BasicBlock;
2598 }
2599
2600 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2601     fn num_nodes(&self) -> usize {
2602         self.basic_blocks.len()
2603     }
2604 }
2605
2606 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2607     fn start_node(&self) -> Self::Node {
2608         START_BLOCK
2609     }
2610 }
2611
2612 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2613     fn predecessors(
2614         &self,
2615         node: Self::Node,
2616     ) -> <Self as GraphPredecessors<'_>>::Iter {
2617         self.predecessors_for(node).clone().into_iter()
2618     }
2619 }
2620
2621 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2622     fn successors(
2623         &self,
2624         node: Self::Node,
2625     ) -> <Self as GraphSuccessors<'_>>::Iter {
2626         self.basic_blocks[node].terminator().successors().cloned()
2627     }
2628 }
2629
2630 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2631     type Item = BasicBlock;
2632     type Iter = IntoIter<BasicBlock>;
2633 }
2634
2635 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2636     type Item = BasicBlock;
2637     type Iter = iter::Cloned<Successors<'b>>;
2638 }
2639
2640 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2641 pub struct Location {
2642     /// The block that the location is within.
2643     pub block: BasicBlock,
2644
2645     /// The location is the position of the start of the statement; or, if
2646     /// `statement_index` equals the number of statements, then the start of the
2647     /// terminator.
2648     pub statement_index: usize,
2649 }
2650
2651 impl fmt::Debug for Location {
2652     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2653         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2654     }
2655 }
2656
2657 impl Location {
2658     pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2659
2660     /// Returns the location immediately after this one within the enclosing block.
2661     ///
2662     /// Note that if this location represents a terminator, then the
2663     /// resulting location would be out of bounds and invalid.
2664     pub fn successor_within_block(&self) -> Location {
2665         Location { block: self.block, statement_index: self.statement_index + 1 }
2666     }
2667
2668     /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2669     pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2670         // If we are in the same block as the other location and are an earlier statement
2671         // then we are a predecessor of `other`.
2672         if self.block == other.block && self.statement_index < other.statement_index {
2673             return true;
2674         }
2675
2676         // If we're in another block, then we want to check that block is a predecessor of `other`.
2677         let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).clone();
2678         let mut visited = FxHashSet::default();
2679
2680         while let Some(block) = queue.pop() {
2681             // If we haven't visited this block before, then make sure we visit it's predecessors.
2682             if visited.insert(block) {
2683                 queue.append(&mut body.predecessors_for(block).clone());
2684             } else {
2685                 continue;
2686             }
2687
2688             // If we found the block that `self` is in, then we are a predecessor of `other` (since
2689             // we found that block by looking at the predecessors of `other`).
2690             if self.block == block {
2691                 return true;
2692             }
2693         }
2694
2695         false
2696     }
2697
2698     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2699         if self.block == other.block {
2700             self.statement_index <= other.statement_index
2701         } else {
2702             dominators.is_dominated_by(other.block, self.block)
2703         }
2704     }
2705 }
2706
2707 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2708 pub enum UnsafetyViolationKind {
2709     General,
2710     /// Permitted both in `const fn`s and regular `fn`s.
2711     GeneralAndConstFn,
2712     BorrowPacked(hir::HirId),
2713 }
2714
2715 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2716 pub struct UnsafetyViolation {
2717     pub source_info: SourceInfo,
2718     pub description: Symbol,
2719     pub details: Symbol,
2720     pub kind: UnsafetyViolationKind,
2721 }
2722
2723 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2724 pub struct UnsafetyCheckResult {
2725     /// Violations that are propagated *upwards* from this function.
2726     pub violations: Lrc<[UnsafetyViolation]>,
2727     /// `unsafe` blocks in this function, along with whether they are used. This is
2728     /// used for the "unused_unsafe" lint.
2729     pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2730 }
2731
2732 rustc_index::newtype_index! {
2733     pub struct GeneratorSavedLocal {
2734         derive [HashStable]
2735         DEBUG_FORMAT = "_{}",
2736     }
2737 }
2738
2739 /// The layout of generator state.
2740 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2741 pub struct GeneratorLayout<'tcx> {
2742     /// The type of every local stored inside the generator.
2743     pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2744
2745     /// Which of the above fields are in each variant. Note that one field may
2746     /// be stored in multiple variants.
2747     pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2748
2749     /// Which saved locals are storage-live at the same time. Locals that do not
2750     /// have conflicts with each other are allowed to overlap in the computed
2751     /// layout.
2752     pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2753
2754     /// The names and scopes of all the stored generator locals.
2755     ///
2756     /// N.B., this is *strictly* a temporary hack for codegen
2757     /// debuginfo generation, and will be removed at some point.
2758     /// Do **NOT** use it for anything else, local information should not be
2759     /// in the MIR, please rely on local crate HIR or other side-channels.
2760     //
2761     // FIXME(tmandry): see above.
2762     pub __local_debuginfo_codegen_only_do_not_use: IndexVec<GeneratorSavedLocal, LocalDecl<'tcx>>,
2763 }
2764
2765 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2766 pub struct BorrowCheckResult<'tcx> {
2767     pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2768     pub used_mut_upvars: SmallVec<[Field; 8]>,
2769 }
2770
2771 /// After we borrow check a closure, we are left with various
2772 /// requirements that we have inferred between the free regions that
2773 /// appear in the closure's signature or on its field types. These
2774 /// requirements are then verified and proved by the closure's
2775 /// creating function. This struct encodes those requirements.
2776 ///
2777 /// The requirements are listed as being between various
2778 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2779 /// vids refer to the free regions that appear in the closure (or
2780 /// generator's) type, in order of appearance. (This numbering is
2781 /// actually defined by the `UniversalRegions` struct in the NLL
2782 /// region checker. See for example
2783 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2784 /// regions in the closure's type "as if" they were erased, so their
2785 /// precise identity is not important, only their position.
2786 ///
2787 /// Example: If type check produces a closure with the closure substs:
2788 ///
2789 /// ```text
2790 /// ClosureSubsts = [
2791 ///     i8,                                  // the "closure kind"
2792 ///     for<'x> fn(&'a &'x u32) -> &'x u32,  // the "closure signature"
2793 ///     &'a String,                          // some upvar
2794 /// ]
2795 /// ```
2796 ///
2797 /// here, there is one unique free region (`'a`) but it appears
2798 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2799 ///
2800 /// ```text
2801 /// ClosureSubsts = [
2802 ///     i8,                                  // the "closure kind"
2803 ///     for<'x> fn(&'1 &'x u32) -> &'x u32,  // the "closure signature"
2804 ///     &'2 String,                          // some upvar
2805 /// ]
2806 /// ```
2807 ///
2808 /// Now the code might impose a requirement like `'1: '2`. When an
2809 /// instance of the closure is created, the corresponding free regions
2810 /// can be extracted from its type and constrained to have the given
2811 /// outlives relationship.
2812 ///
2813 /// In some cases, we have to record outlives requirements between
2814 /// types and regions as well. In that case, if those types include
2815 /// any regions, those regions are recorded as `ReClosureBound`
2816 /// instances assigned one of these same indices. Those regions will
2817 /// be substituted away by the creator. We use `ReClosureBound` in
2818 /// that case because the regions must be allocated in the global
2819 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2820 /// internally within the rest of the NLL code).
2821 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2822 pub struct ClosureRegionRequirements<'tcx> {
2823     /// The number of external regions defined on the closure. In our
2824     /// example above, it would be 3 -- one for `'static`, then `'1`
2825     /// and `'2`. This is just used for a sanity check later on, to
2826     /// make sure that the number of regions we see at the callsite
2827     /// matches.
2828     pub num_external_vids: usize,
2829
2830     /// Requirements between the various free regions defined in
2831     /// indices.
2832     pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2833 }
2834
2835 /// Indicates an outlives-constraint between a type or between two
2836 /// free regions declared on the closure.
2837 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2838 pub struct ClosureOutlivesRequirement<'tcx> {
2839     // This region or type ...
2840     pub subject: ClosureOutlivesSubject<'tcx>,
2841
2842     // ... must outlive this one.
2843     pub outlived_free_region: ty::RegionVid,
2844
2845     // If not, report an error here ...
2846     pub blame_span: Span,
2847
2848     // ... due to this reason.
2849     pub category: ConstraintCategory,
2850 }
2851
2852 /// Outlives-constraints can be categorized to determine whether and why they
2853 /// are interesting (for error reporting). Order of variants indicates sort
2854 /// order of the category, thereby influencing diagnostic output.
2855 ///
2856 /// See also [rustc_mir::borrow_check::nll::constraints].
2857 #[derive(
2858     Copy,
2859     Clone,
2860     Debug,
2861     Eq,
2862     PartialEq,
2863     PartialOrd,
2864     Ord,
2865     Hash,
2866     RustcEncodable,
2867     RustcDecodable,
2868     HashStable,
2869 )]
2870 pub enum ConstraintCategory {
2871     Return,
2872     Yield,
2873     UseAsConst,
2874     UseAsStatic,
2875     TypeAnnotation,
2876     Cast,
2877
2878     /// A constraint that came from checking the body of a closure.
2879     ///
2880     /// We try to get the category that the closure used when reporting this.
2881     ClosureBounds,
2882     CallArgument,
2883     CopyBound,
2884     SizedBound,
2885     Assignment,
2886     OpaqueType,
2887
2888     /// A "boring" constraint (caused by the given location) is one that
2889     /// the user probably doesn't want to see described in diagnostics,
2890     /// because it is kind of an artifact of the type system setup.
2891     /// Example: `x = Foo { field: y }` technically creates
2892     /// intermediate regions representing the "type of `Foo { field: y
2893     /// }`", and data flows from `y` into those variables, but they
2894     /// are not very interesting. The assignment into `x` on the other
2895     /// hand might be.
2896     Boring,
2897     // Boring and applicable everywhere.
2898     BoringNoLocation,
2899
2900     /// A constraint that doesn't correspond to anything the user sees.
2901     Internal,
2902 }
2903
2904 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2905 /// that must outlive some region.
2906 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2907 pub enum ClosureOutlivesSubject<'tcx> {
2908     /// Subject is a type, typically a type parameter, but could also
2909     /// be a projection. Indicates a requirement like `T: 'a` being
2910     /// passed to the caller, where the type here is `T`.
2911     ///
2912     /// The type here is guaranteed not to contain any free regions at
2913     /// present.
2914     Ty(Ty<'tcx>),
2915
2916     /// Subject is a free region from the closure. Indicates a requirement
2917     /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2918     Region(ty::RegionVid),
2919 }
2920
2921 /*
2922  * `TypeFoldable` implementations for MIR types
2923 */
2924
2925 CloneTypeFoldableAndLiftImpls! {
2926     BlockTailInfo,
2927     MirPhase,
2928     Mutability,
2929     SourceInfo,
2930     UpvarDebuginfo,
2931     FakeReadCause,
2932     RetagKind,
2933     SourceScope,
2934     SourceScopeData,
2935     SourceScopeLocalData,
2936     UserTypeAnnotationIndex,
2937 }
2938
2939 BraceStructTypeFoldableImpl! {
2940     impl<'tcx> TypeFoldable<'tcx> for Body<'tcx> {
2941         phase,
2942         basic_blocks,
2943         source_scopes,
2944         source_scope_local_data,
2945         yield_ty,
2946         generator_drop,
2947         generator_layout,
2948         local_decls,
2949         user_type_annotations,
2950         arg_count,
2951         __upvar_debuginfo_codegen_only_do_not_use,
2952         spread_arg,
2953         control_flow_destroyed,
2954         span,
2955         cache,
2956     }
2957 }
2958
2959 BraceStructTypeFoldableImpl! {
2960     impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2961         field_tys,
2962         variant_fields,
2963         storage_conflicts,
2964         __local_debuginfo_codegen_only_do_not_use,
2965     }
2966 }
2967
2968 BraceStructTypeFoldableImpl! {
2969     impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
2970         mutability,
2971         is_user_variable,
2972         internal,
2973         ty,
2974         user_ty,
2975         name,
2976         source_info,
2977         is_block_tail,
2978         visibility_scope,
2979     }
2980 }
2981
2982 BraceStructTypeFoldableImpl! {
2983     impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
2984         statements,
2985         terminator,
2986         is_cleanup,
2987     }
2988 }
2989
2990 BraceStructTypeFoldableImpl! {
2991     impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
2992         source_info, kind
2993     }
2994 }
2995
2996 EnumTypeFoldableImpl! {
2997     impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
2998         (StatementKind::Assign)(a),
2999         (StatementKind::FakeRead)(cause, place),
3000         (StatementKind::SetDiscriminant) { place, variant_index },
3001         (StatementKind::StorageLive)(a),
3002         (StatementKind::StorageDead)(a),
3003         (StatementKind::InlineAsm)(a),
3004         (StatementKind::Retag)(kind, place),
3005         (StatementKind::AscribeUserType)(a, v),
3006         (StatementKind::Nop),
3007     }
3008 }
3009
3010 BraceStructTypeFoldableImpl! {
3011     impl<'tcx> TypeFoldable<'tcx> for InlineAsm<'tcx> {
3012         asm,
3013         outputs,
3014         inputs,
3015     }
3016 }
3017
3018 EnumTypeFoldableImpl! {
3019     impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3020         (ClearCrossCrate::Clear),
3021         (ClearCrossCrate::Set)(a),
3022     } where T: TypeFoldable<'tcx>
3023 }
3024
3025 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3026     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3027         use crate::mir::TerminatorKind::*;
3028
3029         let kind = match self.kind {
3030             Goto { target } => Goto { target },
3031             SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
3032                 discr: discr.fold_with(folder),
3033                 switch_ty: switch_ty.fold_with(folder),
3034                 values: values.clone(),
3035                 targets: targets.clone(),
3036             },
3037             Drop { ref location, target, unwind } => {
3038                 Drop { location: location.fold_with(folder), target, unwind }
3039             }
3040             DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
3041                 location: location.fold_with(folder),
3042                 value: value.fold_with(folder),
3043                 target,
3044                 unwind,
3045             },
3046             Yield { ref value, resume, drop } => {
3047                 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
3048             }
3049             Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
3050                 let dest =
3051                     destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3052
3053                 Call {
3054                     func: func.fold_with(folder),
3055                     args: args.fold_with(folder),
3056                     destination: dest,
3057                     cleanup,
3058                     from_hir_call,
3059                 }
3060             }
3061             Assert { ref cond, expected, ref msg, target, cleanup } => {
3062                 use PanicInfo::*;
3063                 let msg = match msg {
3064                     BoundsCheck { ref len, ref index } =>
3065                         BoundsCheck {
3066                             len: len.fold_with(folder),
3067                             index: index.fold_with(folder),
3068                         },
3069                     Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
3070                     GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
3071                         msg.clone(),
3072                 };
3073                 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
3074             }
3075             GeneratorDrop => GeneratorDrop,
3076             Resume => Resume,
3077             Abort => Abort,
3078             Return => Return,
3079             Unreachable => Unreachable,
3080             FalseEdges { real_target, imaginary_target } => {
3081                 FalseEdges { real_target, imaginary_target }
3082             }
3083             FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
3084         };
3085         Terminator { source_info: self.source_info, kind }
3086     }
3087
3088     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3089         use crate::mir::TerminatorKind::*;
3090
3091         match self.kind {
3092             SwitchInt { ref discr, switch_ty, .. } => {
3093                 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
3094             }
3095             Drop { ref location, .. } => location.visit_with(visitor),
3096             DropAndReplace { ref location, ref value, .. } => {
3097                 location.visit_with(visitor) || value.visit_with(visitor)
3098             }
3099             Yield { ref value, .. } => value.visit_with(visitor),
3100             Call { ref func, ref args, ref destination, .. } => {
3101                 let dest = if let Some((ref loc, _)) = *destination {
3102                     loc.visit_with(visitor)
3103                 } else {
3104                     false
3105                 };
3106                 dest || func.visit_with(visitor) || args.visit_with(visitor)
3107             }
3108             Assert { ref cond, ref msg, .. } => {
3109                 if cond.visit_with(visitor) {
3110                     use PanicInfo::*;
3111                     match msg {
3112                         BoundsCheck { ref len, ref index } =>
3113                             len.visit_with(visitor) || index.visit_with(visitor),
3114                         Panic { .. } | Overflow(_) | OverflowNeg |
3115                         DivisionByZero | RemainderByZero |
3116                         GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
3117                             false
3118                     }
3119                 } else {
3120                     false
3121                 }
3122             }
3123             Goto { .. }
3124             | Resume
3125             | Abort
3126             | Return
3127             | GeneratorDrop
3128             | Unreachable
3129             | FalseEdges { .. }
3130             | FalseUnwind { .. } => false,
3131         }
3132     }
3133 }
3134
3135 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3136     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3137         Place {
3138             base: self.base.fold_with(folder),
3139             projection: self.projection.fold_with(folder),
3140         }
3141     }
3142
3143     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3144         self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3145     }
3146 }
3147
3148 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3149     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3150         match self {
3151             PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3152             PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3153         }
3154     }
3155
3156     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3157         match self {
3158             PlaceBase::Local(local) => local.visit_with(visitor),
3159             PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3160         }
3161     }
3162 }
3163
3164 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3165     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3166         let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3167         folder.tcx().intern_place_elems(&v)
3168     }
3169
3170     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3171         self.iter().any(|t| t.visit_with(visitor))
3172     }
3173 }
3174
3175 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3176     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3177         Static {
3178             ty: self.ty.fold_with(folder),
3179             kind: self.kind.fold_with(folder),
3180             def_id: self.def_id,
3181         }
3182     }
3183
3184     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3185         let Static { ty, kind, def_id: _ } = self;
3186
3187         ty.visit_with(visitor) || kind.visit_with(visitor)
3188     }
3189 }
3190
3191 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3192     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3193         match self {
3194             StaticKind::Promoted(promoted, substs) =>
3195                 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)),
3196             StaticKind::Static => StaticKind::Static
3197         }
3198     }
3199
3200     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3201         match self {
3202             StaticKind::Promoted(promoted, substs) =>
3203                 promoted.visit_with(visitor) || substs.visit_with(visitor),
3204             StaticKind::Static => { false }
3205         }
3206     }
3207 }
3208
3209 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3210     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3211         use crate::mir::Rvalue::*;
3212         match *self {
3213             Use(ref op) => Use(op.fold_with(folder)),
3214             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3215             Ref(region, bk, ref place) => {
3216                 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3217             }
3218             Len(ref place) => Len(place.fold_with(folder)),
3219             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3220             BinaryOp(op, ref rhs, ref lhs) => {
3221                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3222             }
3223             CheckedBinaryOp(op, ref rhs, ref lhs) => {
3224                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3225             }
3226             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3227             Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3228             NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3229             Aggregate(ref kind, ref fields) => {
3230                 let kind = box match **kind {
3231                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3232                     AggregateKind::Tuple => AggregateKind::Tuple,
3233                     AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3234                         def,
3235                         v,
3236                         substs.fold_with(folder),
3237                         user_ty.fold_with(folder),
3238                         n,
3239                     ),
3240                     AggregateKind::Closure(id, substs) => {
3241                         AggregateKind::Closure(id, substs.fold_with(folder))
3242                     }
3243                     AggregateKind::Generator(id, substs, movablity) => {
3244                         AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3245                     }
3246                 };
3247                 Aggregate(kind, fields.fold_with(folder))
3248             }
3249         }
3250     }
3251
3252     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3253         use crate::mir::Rvalue::*;
3254         match *self {
3255             Use(ref op) => op.visit_with(visitor),
3256             Repeat(ref op, _) => op.visit_with(visitor),
3257             Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3258             Len(ref place) => place.visit_with(visitor),
3259             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3260             BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3261                 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3262             }
3263             UnaryOp(_, ref val) => val.visit_with(visitor),
3264             Discriminant(ref place) => place.visit_with(visitor),
3265             NullaryOp(_, ty) => ty.visit_with(visitor),
3266             Aggregate(ref kind, ref fields) => {
3267                 (match **kind {
3268                     AggregateKind::Array(ty) => ty.visit_with(visitor),
3269                     AggregateKind::Tuple => false,
3270                     AggregateKind::Adt(_, _, substs, user_ty, _) => {
3271                         substs.visit_with(visitor) || user_ty.visit_with(visitor)
3272                     }
3273                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3274                     AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3275                 }) || fields.visit_with(visitor)
3276             }
3277         }
3278     }
3279 }
3280
3281 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3282     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3283         match *self {
3284             Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3285             Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3286             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3287         }
3288     }
3289
3290     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3291         match *self {
3292             Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3293             Operand::Constant(ref c) => c.visit_with(visitor),
3294         }
3295     }
3296 }
3297
3298 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3299     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3300         use crate::mir::ProjectionElem::*;
3301
3302         match self {
3303             Deref => Deref,
3304             Field(f, ty) => Field(*f, ty.fold_with(folder)),
3305             Index(v) => Index(v.fold_with(folder)),
3306             elem => elem.clone(),
3307         }
3308     }
3309
3310     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3311         use crate::mir::ProjectionElem::*;
3312
3313         match self {
3314             Field(_, ty) => ty.visit_with(visitor),
3315             Index(v) => v.visit_with(visitor),
3316             _ => false,
3317         }
3318     }
3319 }
3320
3321 impl<'tcx> TypeFoldable<'tcx> for Field {
3322     fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3323         *self
3324     }
3325     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3326         false
3327     }
3328 }
3329
3330 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3331     fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3332         *self
3333     }
3334     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3335         false
3336     }
3337 }
3338
3339 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3340     fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3341         self.clone()
3342     }
3343     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3344         false
3345     }
3346 }
3347
3348 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3349     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3350         Constant {
3351             span: self.span.clone(),
3352             user_ty: self.user_ty.fold_with(folder),
3353             literal: self.literal.fold_with(folder),
3354         }
3355     }
3356     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3357         self.literal.visit_with(visitor)
3358     }
3359 }