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