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