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