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