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