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