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