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