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