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