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