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