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