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