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