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