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