]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mod.rs
ad48c3510484b03bb7a731443838809ec425fd57
[rust.git] / compiler / rustc_middle / src / mir / mod.rs
1 //! MIR datatypes and passes. See the [rustc dev guide] for more info.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html
4
5 use crate::mir::coverage::{CodeRegion, CoverageKind};
6 use crate::mir::interpret::{Allocation, GlobalAlloc, Scalar};
7 use crate::mir::visit::MirVisitable;
8 use crate::ty::adjustment::PointerCast;
9 use crate::ty::codec::{TyDecoder, TyEncoder};
10 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
11 use crate::ty::print::{FmtPrinter, Printer};
12 use crate::ty::subst::{Subst, SubstsRef};
13 use crate::ty::{self, List, Ty, TyCtxt};
14 use crate::ty::{AdtDef, InstanceDef, Region, UserTypeAnnotationIndex};
15 use rustc_hir as hir;
16 use rustc_hir::def::{CtorKind, Namespace};
17 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
18 use rustc_hir::{self, GeneratorKind};
19 use rustc_target::abi::VariantIdx;
20
21 use polonius_engine::Atom;
22 pub use rustc_ast::Mutability;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::{dominators, Dominators};
25 use rustc_data_structures::graph::{self, GraphSuccessors};
26 use rustc_index::bit_set::BitMatrix;
27 use rustc_index::vec::{Idx, IndexVec};
28 use rustc_serialize::{Decodable, Encodable};
29 use rustc_span::symbol::Symbol;
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::asm::InlineAsmRegOrRegClass;
32 use std::borrow::Cow;
33 use std::fmt::{self, Debug, Display, Formatter, Write};
34 use std::ops::{ControlFlow, Index, IndexMut};
35 use std::slice;
36 use std::{iter, mem, option};
37
38 use self::predecessors::{PredecessorCache, Predecessors};
39 pub use self::query::*;
40
41 pub mod abstract_const;
42 pub mod coverage;
43 pub mod interpret;
44 pub mod mono;
45 mod predecessors;
46 mod query;
47 pub mod tcx;
48 pub mod terminator;
49 pub use terminator::*;
50 pub mod traversal;
51 mod type_foldable;
52 pub mod visit;
53
54 /// Types for locals
55 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
56
57 pub trait HasLocalDecls<'tcx> {
58     fn local_decls(&self) -> &LocalDecls<'tcx>;
59 }
60
61 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
62     fn local_decls(&self) -> &LocalDecls<'tcx> {
63         self
64     }
65 }
66
67 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
68     fn local_decls(&self) -> &LocalDecls<'tcx> {
69         &self.local_decls
70     }
71 }
72
73 /// The various "big phases" that MIR goes through.
74 ///
75 /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the
76 /// dialects forbid certain variants or values in certain phases.
77 ///
78 /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase
79 /// that changes the dialect documents what invariants must be upheld *after* that phase finishes.
80 ///
81 /// Warning: ordering of variants is significant.
82 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
83 #[derive(HashStable)]
84 pub enum MirPhase {
85     Build = 0,
86     // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query).
87     // We used to have this for pre-miri MIR based const eval.
88     Const = 1,
89     /// This phase checks the MIR for promotable elements and takes them out of the main MIR body
90     /// by creating a new MIR body per promoted element. After this phase (and thus the termination
91     /// of the `mir_promoted` query), these promoted elements are available in the `promoted_mir`
92     /// query.
93     ConstPromotion = 2,
94     /// After this phase
95     /// * the only `AggregateKind`s allowed are `Array` and `Generator`,
96     /// * `DropAndReplace` is gone for good
97     /// * `Drop` now uses explicit drop flags visible in the MIR and reaching a `Drop` terminator
98     ///   means that the auto-generated drop glue will be invoked.
99     DropLowering = 3,
100     /// After this phase, generators are explicit state machines (no more `Yield`).
101     /// `AggregateKind::Generator` is gone for good.
102     GeneratorLowering = 4,
103     Optimization = 5,
104 }
105
106 impl MirPhase {
107     /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
108     pub fn phase_index(&self) -> usize {
109         *self as usize
110     }
111 }
112
113 /// Where a specific `mir::Body` comes from.
114 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
115 #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)]
116 pub struct MirSource<'tcx> {
117     pub instance: InstanceDef<'tcx>,
118
119     /// If `Some`, this is a promoted rvalue within the parent function.
120     pub promoted: Option<Promoted>,
121 }
122
123 impl<'tcx> MirSource<'tcx> {
124     pub fn item(def_id: DefId) -> Self {
125         MirSource {
126             instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
127             promoted: None,
128         }
129     }
130
131     pub fn from_instance(instance: InstanceDef<'tcx>) -> Self {
132         MirSource { instance, promoted: None }
133     }
134
135     pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
136         self.instance.with_opt_param()
137     }
138
139     #[inline]
140     pub fn def_id(&self) -> DefId {
141         self.instance.def_id()
142     }
143 }
144
145 /// The lowered representation of a single function.
146 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)]
147 pub struct Body<'tcx> {
148     /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`]
149     /// that indexes into this vector.
150     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
151
152     /// Records how far through the "desugaring and optimization" process this particular
153     /// MIR has traversed. This is particularly useful when inlining, since in that context
154     /// we instantiate the promoted constants and add them to our promoted vector -- but those
155     /// promoted items have already been optimized, whereas ours have not. This field allows
156     /// us to see the difference and forego optimization on the inlined promoted items.
157     pub phase: MirPhase,
158
159     pub source: MirSource<'tcx>,
160
161     /// A list of source scopes; these are referenced by statements
162     /// and used for debuginfo. Indexed by a `SourceScope`.
163     pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
164
165     /// The yield type of the function, if it is a generator.
166     pub yield_ty: Option<Ty<'tcx>>,
167
168     /// Generator drop glue.
169     pub generator_drop: Option<Box<Body<'tcx>>>,
170
171     /// The layout of a generator. Produced by the state transformation.
172     pub generator_layout: Option<GeneratorLayout<'tcx>>,
173
174     /// If this is a generator then record the type of source expression that caused this generator
175     /// to be created.
176     pub generator_kind: Option<GeneratorKind>,
177
178     /// Declarations of locals.
179     ///
180     /// The first local is the return value pointer, followed by `arg_count`
181     /// locals for the function arguments, followed by any user-declared
182     /// variables and temporaries.
183     pub local_decls: LocalDecls<'tcx>,
184
185     /// User type annotations.
186     pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
187
188     /// The number of arguments this function takes.
189     ///
190     /// Starting at local 1, `arg_count` locals will be provided by the caller
191     /// and can be assumed to be initialized.
192     ///
193     /// If this MIR was built for a constant, this will be 0.
194     pub arg_count: usize,
195
196     /// Mark an argument local (which must be a tuple) as getting passed as
197     /// its individual components at the LLVM level.
198     ///
199     /// This is used for the "rust-call" ABI.
200     pub spread_arg: Option<Local>,
201
202     /// Debug information pertaining to user variables, including captures.
203     pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
204
205     /// A span representing this MIR, for error reporting.
206     pub span: Span,
207
208     /// Constants that are required to evaluate successfully for this MIR to be well-formed.
209     /// We hold in this field all the constants we are not able to evaluate yet.
210     pub required_consts: Vec<Constant<'tcx>>,
211
212     /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check.
213     ///
214     /// Note that this does not actually mean that this body is not computable right now.
215     /// The repeat count in the following example is polymorphic, but can still be evaluated
216     /// without knowing anything about the type parameter `T`.
217     ///
218     /// ```rust
219     /// fn test<T>() {
220     ///     let _ = [0; std::mem::size_of::<*mut T>()];
221     /// }
222     /// ```
223     ///
224     /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization
225     /// removed the last mention of all generic params. We do not want to rely on optimizations and
226     /// potentially allow things like `[u8; std::mem::size_of::<T>() * 0]` due to this.
227     pub is_polymorphic: bool,
228
229     predecessor_cache: PredecessorCache,
230 }
231
232 impl<'tcx> Body<'tcx> {
233     pub fn new(
234         source: MirSource<'tcx>,
235         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
236         source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
237         local_decls: LocalDecls<'tcx>,
238         user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
239         arg_count: usize,
240         var_debug_info: Vec<VarDebugInfo<'tcx>>,
241         span: Span,
242         generator_kind: Option<GeneratorKind>,
243     ) -> Self {
244         // We need `arg_count` locals, and one for the return place.
245         assert!(
246             local_decls.len() > arg_count,
247             "expected at least {} locals, got {}",
248             arg_count + 1,
249             local_decls.len()
250         );
251
252         let mut body = Body {
253             phase: MirPhase::Build,
254             source,
255             basic_blocks,
256             source_scopes,
257             yield_ty: None,
258             generator_drop: None,
259             generator_layout: None,
260             generator_kind,
261             local_decls,
262             user_type_annotations,
263             arg_count,
264             spread_arg: None,
265             var_debug_info,
266             span,
267             required_consts: Vec::new(),
268             is_polymorphic: false,
269             predecessor_cache: PredecessorCache::new(),
270         };
271         body.is_polymorphic = body.has_param_types_or_consts();
272         body
273     }
274
275     /// Returns a partially initialized MIR body containing only a list of basic blocks.
276     ///
277     /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It
278     /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different
279     /// crate.
280     pub fn new_cfg_only(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>) -> Self {
281         let mut body = Body {
282             phase: MirPhase::Build,
283             source: MirSource::item(DefId::local(CRATE_DEF_INDEX)),
284             basic_blocks,
285             source_scopes: IndexVec::new(),
286             yield_ty: None,
287             generator_drop: None,
288             generator_layout: None,
289             local_decls: IndexVec::new(),
290             user_type_annotations: IndexVec::new(),
291             arg_count: 0,
292             spread_arg: None,
293             span: DUMMY_SP,
294             required_consts: Vec::new(),
295             generator_kind: None,
296             var_debug_info: Vec::new(),
297             is_polymorphic: false,
298             predecessor_cache: PredecessorCache::new(),
299         };
300         body.is_polymorphic = body.has_param_types_or_consts();
301         body
302     }
303
304     #[inline]
305     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
306         &self.basic_blocks
307     }
308
309     #[inline]
310     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
311         // Because the user could mutate basic block terminators via this reference, we need to
312         // invalidate the predecessor cache.
313         //
314         // FIXME: Use a finer-grained API for this, so only transformations that alter terminators
315         // invalidate the predecessor cache.
316         self.predecessor_cache.invalidate();
317         &mut self.basic_blocks
318     }
319
320     #[inline]
321     pub fn basic_blocks_and_local_decls_mut(
322         &mut self,
323     ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
324         self.predecessor_cache.invalidate();
325         (&mut self.basic_blocks, &mut self.local_decls)
326     }
327
328     #[inline]
329     pub fn basic_blocks_local_decls_mut_and_var_debug_info(
330         &mut self,
331     ) -> (
332         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
333         &mut LocalDecls<'tcx>,
334         &mut Vec<VarDebugInfo<'tcx>>,
335     ) {
336         self.predecessor_cache.invalidate();
337         (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info)
338     }
339
340     /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
341     /// `START_BLOCK`.
342     pub fn is_cfg_cyclic(&self) -> bool {
343         graph::is_cyclic(self)
344     }
345
346     #[inline]
347     pub fn local_kind(&self, local: Local) -> LocalKind {
348         let index = local.as_usize();
349         if index == 0 {
350             debug_assert!(
351                 self.local_decls[local].mutability == Mutability::Mut,
352                 "return place should be mutable"
353             );
354
355             LocalKind::ReturnPointer
356         } else if index < self.arg_count + 1 {
357             LocalKind::Arg
358         } else if self.local_decls[local].is_user_variable() {
359             LocalKind::Var
360         } else {
361             LocalKind::Temp
362         }
363     }
364
365     /// Returns an iterator over all temporaries.
366     #[inline]
367     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
368         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
369             let local = Local::new(index);
370             if self.local_decls[local].is_user_variable() { None } else { Some(local) }
371         })
372     }
373
374     /// Returns an iterator over all user-declared locals.
375     #[inline]
376     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
377         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
378             let local = Local::new(index);
379             self.local_decls[local].is_user_variable().then_some(local)
380         })
381     }
382
383     /// Returns an iterator over all user-declared mutable locals.
384     #[inline]
385     pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
386         (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
387             let local = Local::new(index);
388             let decl = &self.local_decls[local];
389             if decl.is_user_variable() && decl.mutability == Mutability::Mut {
390                 Some(local)
391             } else {
392                 None
393             }
394         })
395     }
396
397     /// Returns an iterator over all user-declared mutable arguments and locals.
398     #[inline]
399     pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
400         (1..self.local_decls.len()).filter_map(move |index| {
401             let local = Local::new(index);
402             let decl = &self.local_decls[local];
403             if (decl.is_user_variable() || index < self.arg_count + 1)
404                 && decl.mutability == Mutability::Mut
405             {
406                 Some(local)
407             } else {
408                 None
409             }
410         })
411     }
412
413     /// Returns an iterator over all function arguments.
414     #[inline]
415     pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
416         let arg_count = self.arg_count;
417         (1..arg_count + 1).map(Local::new)
418     }
419
420     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
421     /// locals that are neither arguments nor the return place).
422     #[inline]
423     pub fn vars_and_temps_iter(
424         &self,
425     ) -> impl DoubleEndedIterator<Item = Local> + ExactSizeIterator {
426         let arg_count = self.arg_count;
427         let local_count = self.local_decls.len();
428         (arg_count + 1..local_count).map(Local::new)
429     }
430
431     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
432     /// invalidating statement indices in `Location`s.
433     pub fn make_statement_nop(&mut self, location: Location) {
434         let block = &mut self.basic_blocks[location.block];
435         debug_assert!(location.statement_index < block.statements.len());
436         block.statements[location.statement_index].make_nop()
437     }
438
439     /// Returns the source info associated with `location`.
440     pub fn source_info(&self, location: Location) -> &SourceInfo {
441         let block = &self[location.block];
442         let stmts = &block.statements;
443         let idx = location.statement_index;
444         if idx < stmts.len() {
445             &stmts[idx].source_info
446         } else {
447             assert_eq!(idx, stmts.len());
448             &block.terminator().source_info
449         }
450     }
451
452     /// Returns the return type; it always return first element from `local_decls` array.
453     #[inline]
454     pub fn return_ty(&self) -> Ty<'tcx> {
455         self.local_decls[RETURN_PLACE].ty
456     }
457
458     /// Gets the location of the terminator for the given block.
459     #[inline]
460     pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
461         Location { block: bb, statement_index: self[bb].statements.len() }
462     }
463
464     #[inline]
465     pub fn predecessors(&self) -> impl std::ops::Deref<Target = Predecessors> + '_ {
466         self.predecessor_cache.compute(&self.basic_blocks)
467     }
468
469     #[inline]
470     pub fn dominators(&self) -> Dominators<BasicBlock> {
471         dominators(self)
472     }
473 }
474
475 #[derive(Copy, Clone, PartialEq, Eq, Debug, TyEncodable, TyDecodable, HashStable)]
476 pub enum Safety {
477     Safe,
478     /// Unsafe because of a PushUnsafeBlock
479     BuiltinUnsafe,
480     /// Unsafe because of an unsafe fn
481     FnUnsafe,
482     /// Unsafe because of an `unsafe` block
483     ExplicitUnsafe(hir::HirId),
484 }
485
486 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
487     type Output = BasicBlockData<'tcx>;
488
489     #[inline]
490     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
491         &self.basic_blocks()[index]
492     }
493 }
494
495 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
496     #[inline]
497     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
498         &mut self.basic_blocks_mut()[index]
499     }
500 }
501
502 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
503 pub enum ClearCrossCrate<T> {
504     Clear,
505     Set(T),
506 }
507
508 impl<T> ClearCrossCrate<T> {
509     pub fn as_ref(&self) -> ClearCrossCrate<&T> {
510         match self {
511             ClearCrossCrate::Clear => ClearCrossCrate::Clear,
512             ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
513         }
514     }
515
516     pub fn assert_crate_local(self) -> T {
517         match self {
518             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
519             ClearCrossCrate::Set(v) => v,
520         }
521     }
522 }
523
524 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
525 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
526
527 impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> {
528     #[inline]
529     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
530         if E::CLEAR_CROSS_CRATE {
531             return Ok(());
532         }
533
534         match *self {
535             ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e),
536             ClearCrossCrate::Set(ref val) => {
537                 TAG_CLEAR_CROSS_CRATE_SET.encode(e)?;
538                 val.encode(e)
539             }
540         }
541     }
542 }
543 impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> {
544     #[inline]
545     fn decode(d: &mut D) -> Result<ClearCrossCrate<T>, D::Error> {
546         if D::CLEAR_CROSS_CRATE {
547             return Ok(ClearCrossCrate::Clear);
548         }
549
550         let discr = u8::decode(d)?;
551
552         match discr {
553             TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear),
554             TAG_CLEAR_CROSS_CRATE_SET => {
555                 let val = T::decode(d)?;
556                 Ok(ClearCrossCrate::Set(val))
557             }
558             tag => Err(d.error(&format!("Invalid tag for ClearCrossCrate: {:?}", tag))),
559         }
560     }
561 }
562
563 /// Grouped information about the source code origin of a MIR entity.
564 /// Intended to be inspected by diagnostics and debuginfo.
565 /// Most passes can work with it as a whole, within a single function.
566 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
567 // `Hash`. Please ping @bjorn3 if removing them.
568 #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
569 pub struct SourceInfo {
570     /// The source span for the AST pertaining to this MIR entity.
571     pub span: Span,
572
573     /// The source scope, keeping track of which bindings can be
574     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
575     pub scope: SourceScope,
576 }
577
578 impl SourceInfo {
579     #[inline]
580     pub fn outermost(span: Span) -> Self {
581         SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE }
582     }
583 }
584
585 ///////////////////////////////////////////////////////////////////////////
586 // Borrow kinds
587
588 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
589 #[derive(HashStable)]
590 pub enum BorrowKind {
591     /// Data must be immutable and is aliasable.
592     Shared,
593
594     /// The immediately borrowed place must be immutable, but projections from
595     /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
596     /// conflict with a mutable borrow of `a.b.c`.
597     ///
598     /// This is used when lowering matches: when matching on a place we want to
599     /// ensure that place have the same value from the start of the match until
600     /// an arm is selected. This prevents this code from compiling:
601     ///
602     ///     let mut x = &Some(0);
603     ///     match *x {
604     ///         None => (),
605     ///         Some(_) if { x = &None; false } => (),
606     ///         Some(_) => (),
607     ///     }
608     ///
609     /// This can't be a shared borrow because mutably borrowing (*x as Some).0
610     /// should not prevent `if let None = x { ... }`, for example, because the
611     /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
612     /// We can also report errors with this kind of borrow differently.
613     Shallow,
614
615     /// Data must be immutable but not aliasable. This kind of borrow
616     /// cannot currently be expressed by the user and is used only in
617     /// implicit closure bindings. It is needed when the closure is
618     /// borrowing or mutating a mutable referent, e.g.:
619     ///
620     ///     let x: &mut isize = ...;
621     ///     let y = || *x += 5;
622     ///
623     /// If we were to try to translate this closure into a more explicit
624     /// form, we'd encounter an error with the code as written:
625     ///
626     ///     struct Env { x: & &mut isize }
627     ///     let x: &mut isize = ...;
628     ///     let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
629     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
630     ///
631     /// This is then illegal because you cannot mutate an `&mut` found
632     /// in an aliasable location. To solve, you'd have to translate with
633     /// an `&mut` borrow:
634     ///
635     ///     struct Env { x: & &mut isize }
636     ///     let x: &mut isize = ...;
637     ///     let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
638     ///     fn fn_ptr(env: &mut Env) { **env.x += 5; }
639     ///
640     /// Now the assignment to `**env.x` is legal, but creating a
641     /// mutable pointer to `x` is not because `x` is not mutable. We
642     /// could fix this by declaring `x` as `let mut x`. This is ok in
643     /// user code, if awkward, but extra weird for closures, since the
644     /// borrow is hidden.
645     ///
646     /// So we introduce a "unique imm" borrow -- the referent is
647     /// immutable, but not aliasable. This solves the problem. For
648     /// simplicity, we don't give users the way to express this
649     /// borrow, it's just used when translating closures.
650     Unique,
651
652     /// Data is mutable and not aliasable.
653     Mut {
654         /// `true` if this borrow arose from method-call auto-ref
655         /// (i.e., `adjustment::Adjust::Borrow`).
656         allow_two_phase_borrow: bool,
657     },
658 }
659
660 impl BorrowKind {
661     pub fn allows_two_phase_borrow(&self) -> bool {
662         match *self {
663             BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
664             BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
665         }
666     }
667 }
668
669 ///////////////////////////////////////////////////////////////////////////
670 // Variables and temps
671
672 rustc_index::newtype_index! {
673     pub struct Local {
674         derive [HashStable]
675         DEBUG_FORMAT = "_{}",
676         const RETURN_PLACE = 0,
677     }
678 }
679
680 impl Atom for Local {
681     fn index(self) -> usize {
682         Idx::index(self)
683     }
684 }
685
686 /// Classifies locals into categories. See `Body::local_kind`.
687 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)]
688 pub enum LocalKind {
689     /// User-declared variable binding.
690     Var,
691     /// Compiler-introduced temporary.
692     Temp,
693     /// Function argument.
694     Arg,
695     /// Location of function's return value.
696     ReturnPointer,
697 }
698
699 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
700 pub struct VarBindingForm<'tcx> {
701     /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
702     pub binding_mode: ty::BindingMode,
703     /// If an explicit type was provided for this variable binding,
704     /// this holds the source Span of that type.
705     ///
706     /// NOTE: if you want to change this to a `HirId`, be wary that
707     /// doing so breaks incremental compilation (as of this writing),
708     /// while a `Span` does not cause our tests to fail.
709     pub opt_ty_info: Option<Span>,
710     /// Place of the RHS of the =, or the subject of the `match` where this
711     /// variable is initialized. None in the case of `let PATTERN;`.
712     /// Some((None, ..)) in the case of and `let [mut] x = ...` because
713     /// (a) the right-hand side isn't evaluated as a place expression.
714     /// (b) it gives a way to separate this case from the remaining cases
715     ///     for diagnostics.
716     pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
717     /// The span of the pattern in which this variable was bound.
718     pub pat_span: Span,
719 }
720
721 #[derive(Clone, Debug, TyEncodable, TyDecodable)]
722 pub enum BindingForm<'tcx> {
723     /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
724     Var(VarBindingForm<'tcx>),
725     /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
726     ImplicitSelf(ImplicitSelfKind),
727     /// Reference used in a guard expression to ensure immutability.
728     RefForGuard,
729 }
730
731 /// Represents what type of implicit self a function has, if any.
732 #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
733 pub enum ImplicitSelfKind {
734     /// Represents a `fn x(self);`.
735     Imm,
736     /// Represents a `fn x(mut self);`.
737     Mut,
738     /// Represents a `fn x(&self);`.
739     ImmRef,
740     /// Represents a `fn x(&mut self);`.
741     MutRef,
742     /// Represents when a function does not have a self argument or
743     /// when a function has a `self: X` argument.
744     None,
745 }
746
747 TrivialTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
748
749 mod binding_form_impl {
750     use crate::ich::StableHashingContext;
751     use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
752
753     impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
754         fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
755             use super::BindingForm::*;
756             std::mem::discriminant(self).hash_stable(hcx, hasher);
757
758             match self {
759                 Var(binding) => binding.hash_stable(hcx, hasher),
760                 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
761                 RefForGuard => (),
762             }
763         }
764     }
765 }
766
767 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
768 /// created during evaluation of expressions in a block tail
769 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
770 ///
771 /// It is used to improve diagnostics when such temporaries are
772 /// involved in borrow_check errors, e.g., explanations of where the
773 /// temporaries come from, when their destructors are run, and/or how
774 /// one might revise the code to satisfy the borrow checker's rules.
775 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
776 pub struct BlockTailInfo {
777     /// If `true`, then the value resulting from evaluating this tail
778     /// expression is ignored by the block's expression context.
779     ///
780     /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
781     /// but not e.g., `let _x = { ...; tail };`
782     pub tail_result_is_ignored: bool,
783
784     /// `Span` of the tail expression.
785     pub span: Span,
786 }
787
788 /// A MIR local.
789 ///
790 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
791 /// argument, or the return place.
792 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
793 pub struct LocalDecl<'tcx> {
794     /// Whether this is a mutable binding (i.e., `let x` or `let mut x`).
795     ///
796     /// Temporaries and the return place are always mutable.
797     pub mutability: Mutability,
798
799     // FIXME(matthewjasper) Don't store in this in `Body`
800     pub local_info: Option<Box<LocalInfo<'tcx>>>,
801
802     /// `true` if this is an internal local.
803     ///
804     /// These locals are not based on types in the source code and are only used
805     /// for a few desugarings at the moment.
806     ///
807     /// The generator transformation will sanity check the locals which are live
808     /// across a suspension point against the type components of the generator
809     /// which type checking knows are live across a suspension point. We need to
810     /// flag drop flags to avoid triggering this check as they are introduced
811     /// after typeck.
812     ///
813     /// This should be sound because the drop flags are fully algebraic, and
814     /// therefore don't affect the auto-trait or outlives properties of the
815     /// generator.
816     pub internal: bool,
817
818     /// If this local is a temporary and `is_block_tail` is `Some`,
819     /// then it is a temporary created for evaluation of some
820     /// subexpression of some block's tail expression (with no
821     /// intervening statement context).
822     // FIXME(matthewjasper) Don't store in this in `Body`
823     pub is_block_tail: Option<BlockTailInfo>,
824
825     /// The type of this local.
826     pub ty: Ty<'tcx>,
827
828     /// If the user manually ascribed a type to this variable,
829     /// e.g., via `let x: T`, then we carry that type here. The MIR
830     /// borrow checker needs this information since it can affect
831     /// region inference.
832     // FIXME(matthewjasper) Don't store in this in `Body`
833     pub user_ty: Option<Box<UserTypeProjections>>,
834
835     /// The *syntactic* (i.e., not visibility) source scope the local is defined
836     /// in. If the local was defined in a let-statement, this
837     /// is *within* the let-statement, rather than outside
838     /// of it.
839     ///
840     /// This is needed because the visibility source scope of locals within
841     /// a let-statement is weird.
842     ///
843     /// The reason is that we want the local to be *within* the let-statement
844     /// for lint purposes, but we want the local to be *after* the let-statement
845     /// for names-in-scope purposes.
846     ///
847     /// That's it, if we have a let-statement like the one in this
848     /// function:
849     ///
850     /// ```
851     /// fn foo(x: &str) {
852     ///     #[allow(unused_mut)]
853     ///     let mut x: u32 = { // <- one unused mut
854     ///         let mut y: u32 = x.parse().unwrap();
855     ///         y + 2
856     ///     };
857     ///     drop(x);
858     /// }
859     /// ```
860     ///
861     /// Then, from a lint point of view, the declaration of `x: u32`
862     /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
863     /// lint scopes are the same as the AST/HIR nesting.
864     ///
865     /// However, from a name lookup point of view, the scopes look more like
866     /// as if the let-statements were `match` expressions:
867     ///
868     /// ```
869     /// fn foo(x: &str) {
870     ///     match {
871     ///         match x.parse().unwrap() {
872     ///             y => y + 2
873     ///         }
874     ///     } {
875     ///         x => drop(x)
876     ///     };
877     /// }
878     /// ```
879     ///
880     /// We care about the name-lookup scopes for debuginfo - if the
881     /// debuginfo instruction pointer is at the call to `x.parse()`, we
882     /// want `x` to refer to `x: &str`, but if it is at the call to
883     /// `drop(x)`, we want it to refer to `x: u32`.
884     ///
885     /// To allow both uses to work, we need to have more than a single scope
886     /// for a local. We have the `source_info.scope` represent the "syntactic"
887     /// lint scope (with a variable being under its let block) while the
888     /// `var_debug_info.source_info.scope` represents the "local variable"
889     /// scope (where the "rest" of a block is under all prior let-statements).
890     ///
891     /// The end result looks like this:
892     ///
893     /// ```text
894     /// ROOT SCOPE
895     ///  │{ argument x: &str }
896     ///  │
897     ///  │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
898     ///  │ │                         // in practice because I'm lazy.
899     ///  │ │
900     ///  │ │← x.source_info.scope
901     ///  │ │← `x.parse().unwrap()`
902     ///  │ │
903     ///  │ │ │← y.source_info.scope
904     ///  │ │
905     ///  │ │ │{ let y: u32 }
906     ///  │ │ │
907     ///  │ │ │← y.var_debug_info.source_info.scope
908     ///  │ │ │← `y + 2`
909     ///  │
910     ///  │ │{ let x: u32 }
911     ///  │ │← x.var_debug_info.source_info.scope
912     ///  │ │← `drop(x)` // This accesses `x: u32`.
913     /// ```
914     pub source_info: SourceInfo,
915 }
916
917 // `LocalDecl` is used a lot. Make sure it doesn't unintentionally get bigger.
918 #[cfg(target_arch = "x86_64")]
919 static_assert_size!(LocalDecl<'_>, 56);
920
921 /// Extra information about a some locals that's used for diagnostics and for
922 /// classifying variables into local variables, statics, etc, which is needed e.g.
923 /// for unsafety checking.
924 ///
925 /// Not used for non-StaticRef temporaries, the return place, or anonymous
926 /// function parameters.
927 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
928 pub enum LocalInfo<'tcx> {
929     /// A user-defined local variable or function parameter
930     ///
931     /// The `BindingForm` is solely used for local diagnostics when generating
932     /// warnings/errors when compiling the current crate, and therefore it need
933     /// not be visible across crates.
934     User(ClearCrossCrate<BindingForm<'tcx>>),
935     /// A temporary created that references the static with the given `DefId`.
936     StaticRef { def_id: DefId, is_thread_local: bool },
937     /// A temporary created that references the const with the given `DefId`
938     ConstRef { def_id: DefId },
939 }
940
941 impl<'tcx> LocalDecl<'tcx> {
942     /// Returns `true` only if local is a binding that can itself be
943     /// made mutable via the addition of the `mut` keyword, namely
944     /// something like the occurrences of `x` in:
945     /// - `fn foo(x: Type) { ... }`,
946     /// - `let x = ...`,
947     /// - or `match ... { C(x) => ... }`
948     pub fn can_be_made_mutable(&self) -> bool {
949         matches!(
950             self.local_info,
951             Some(box LocalInfo::User(ClearCrossCrate::Set(
952                 BindingForm::Var(VarBindingForm {
953                     binding_mode: ty::BindingMode::BindByValue(_),
954                     opt_ty_info: _,
955                     opt_match_place: _,
956                     pat_span: _,
957                 })
958                 | BindingForm::ImplicitSelf(ImplicitSelfKind::Imm),
959             )))
960         )
961     }
962
963     /// Returns `true` if local is definitely not a `ref ident` or
964     /// `ref mut ident` binding. (Such bindings cannot be made into
965     /// mutable bindings, but the inverse does not necessarily hold).
966     pub fn is_nonref_binding(&self) -> bool {
967         matches!(
968             self.local_info,
969             Some(box LocalInfo::User(ClearCrossCrate::Set(
970                 BindingForm::Var(VarBindingForm {
971                     binding_mode: ty::BindingMode::BindByValue(_),
972                     opt_ty_info: _,
973                     opt_match_place: _,
974                     pat_span: _,
975                 })
976                 | BindingForm::ImplicitSelf(_),
977             )))
978         )
979     }
980
981     /// Returns `true` if this variable is a named variable or function
982     /// parameter declared by the user.
983     #[inline]
984     pub fn is_user_variable(&self) -> bool {
985         matches!(self.local_info, Some(box LocalInfo::User(_)))
986     }
987
988     /// Returns `true` if this is a reference to a variable bound in a `match`
989     /// expression that is used to access said variable for the guard of the
990     /// match arm.
991     pub fn is_ref_for_guard(&self) -> bool {
992         matches!(
993             self.local_info,
994             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)))
995         )
996     }
997
998     /// Returns `Some` if this is a reference to a static item that is used to
999     /// access that static.
1000     pub fn is_ref_to_static(&self) -> bool {
1001         matches!(self.local_info, Some(box LocalInfo::StaticRef { .. }))
1002     }
1003
1004     /// Returns `Some` if this is a reference to a thread-local static item that is used to
1005     /// access that static.
1006     pub fn is_ref_to_thread_local(&self) -> bool {
1007         match self.local_info {
1008             Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local,
1009             _ => false,
1010         }
1011     }
1012
1013     /// Returns `true` is the local is from a compiler desugaring, e.g.,
1014     /// `__next` from a `for` loop.
1015     #[inline]
1016     pub fn from_compiler_desugaring(&self) -> bool {
1017         self.source_info.span.desugaring_kind().is_some()
1018     }
1019
1020     /// Creates a new `LocalDecl` for a temporary: mutable, non-internal.
1021     #[inline]
1022     pub fn new(ty: Ty<'tcx>, span: Span) -> Self {
1023         Self::with_source_info(ty, SourceInfo::outermost(span))
1024     }
1025
1026     /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`.
1027     #[inline]
1028     pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self {
1029         LocalDecl {
1030             mutability: Mutability::Mut,
1031             local_info: None,
1032             internal: false,
1033             is_block_tail: None,
1034             ty,
1035             user_ty: None,
1036             source_info,
1037         }
1038     }
1039
1040     /// Converts `self` into same `LocalDecl` except tagged as internal.
1041     #[inline]
1042     pub fn internal(mut self) -> Self {
1043         self.internal = true;
1044         self
1045     }
1046
1047     /// Converts `self` into same `LocalDecl` except tagged as immutable.
1048     #[inline]
1049     pub fn immutable(mut self) -> Self {
1050         self.mutability = Mutability::Not;
1051         self
1052     }
1053
1054     /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
1055     #[inline]
1056     pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
1057         assert!(self.is_block_tail.is_none());
1058         self.is_block_tail = Some(info);
1059         self
1060     }
1061 }
1062
1063 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1064 pub enum VarDebugInfoContents<'tcx> {
1065     /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1066     /// based on a `Local`, not a `Static`, and contains no indexing.
1067     Place(Place<'tcx>),
1068     Const(Constant<'tcx>),
1069 }
1070
1071 impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
1072     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1073         match self {
1074             VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
1075             VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
1076         }
1077     }
1078 }
1079
1080 /// Debug information pertaining to a user variable.
1081 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1082 pub struct VarDebugInfo<'tcx> {
1083     pub name: Symbol,
1084
1085     /// Source info of the user variable, including the scope
1086     /// within which the variable is visible (to debuginfo)
1087     /// (see `LocalDecl`'s `source_info` field for more details).
1088     pub source_info: SourceInfo,
1089
1090     /// Where the data for this user variable is to be found.
1091     pub value: VarDebugInfoContents<'tcx>,
1092 }
1093
1094 ///////////////////////////////////////////////////////////////////////////
1095 // BasicBlock
1096
1097 rustc_index::newtype_index! {
1098     /// A node in the MIR [control-flow graph][CFG].
1099     ///
1100     /// There are no branches (e.g., `if`s, function calls, etc.) within a basic block, which makes
1101     /// it easier to do [data-flow analyses] and optimizations. Instead, branches are represented
1102     /// as an edge in a graph between basic blocks.
1103     ///
1104     /// Basic blocks consist of a series of [statements][Statement], ending with a
1105     /// [terminator][Terminator]. Basic blocks can have multiple predecessors and successors,
1106     /// however there is a MIR pass ([`CriticalCallEdges`]) that removes *critical edges*, which
1107     /// are edges that go from a multi-successor node to a multi-predecessor node. This pass is
1108     /// needed because some analyses require that there are no critical edges in the CFG.
1109     ///
1110     /// Note that this type is just an index into [`Body.basic_blocks`](Body::basic_blocks);
1111     /// the actual data that a basic block holds is in [`BasicBlockData`].
1112     ///
1113     /// Read more about basic blocks in the [rustc-dev-guide][guide-mir].
1114     ///
1115     /// [CFG]: https://rustc-dev-guide.rust-lang.org/appendix/background.html#cfg
1116     /// [data-flow analyses]:
1117     ///     https://rustc-dev-guide.rust-lang.org/appendix/background.html#what-is-a-dataflow-analysis
1118     /// [`CriticalCallEdges`]: ../../rustc_mir/transform/add_call_guards/enum.AddCallGuards.html#variant.CriticalCallEdges
1119     /// [guide-mir]: https://rustc-dev-guide.rust-lang.org/mir/
1120     pub struct BasicBlock {
1121         derive [HashStable]
1122         DEBUG_FORMAT = "bb{}",
1123         const START_BLOCK = 0,
1124     }
1125 }
1126
1127 impl BasicBlock {
1128     pub fn start_location(self) -> Location {
1129         Location { block: self, statement_index: 0 }
1130     }
1131 }
1132
1133 ///////////////////////////////////////////////////////////////////////////
1134 // BasicBlockData and Terminator
1135
1136 /// See [`BasicBlock`] for documentation on what basic blocks are at a high level.
1137 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1138 pub struct BasicBlockData<'tcx> {
1139     /// List of statements in this block.
1140     pub statements: Vec<Statement<'tcx>>,
1141
1142     /// Terminator for this block.
1143     ///
1144     /// N.B., this should generally ONLY be `None` during construction.
1145     /// Therefore, you should generally access it via the
1146     /// `terminator()` or `terminator_mut()` methods. The only
1147     /// exception is that certain passes, such as `simplify_cfg`, swap
1148     /// out the terminator temporarily with `None` while they continue
1149     /// to recurse over the set of basic blocks.
1150     pub terminator: Option<Terminator<'tcx>>,
1151
1152     /// If true, this block lies on an unwind path. This is used
1153     /// during codegen where distinct kinds of basic blocks may be
1154     /// generated (particularly for MSVC cleanup). Unwind blocks must
1155     /// only branch to other unwind blocks.
1156     pub is_cleanup: bool,
1157 }
1158
1159 /// Information about an assertion failure.
1160 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
1161 pub enum AssertKind<O> {
1162     BoundsCheck { len: O, index: O },
1163     Overflow(BinOp, O, O),
1164     OverflowNeg(O),
1165     DivisionByZero(O),
1166     RemainderByZero(O),
1167     ResumedAfterReturn(GeneratorKind),
1168     ResumedAfterPanic(GeneratorKind),
1169 }
1170
1171 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1172 pub enum InlineAsmOperand<'tcx> {
1173     In {
1174         reg: InlineAsmRegOrRegClass,
1175         value: Operand<'tcx>,
1176     },
1177     Out {
1178         reg: InlineAsmRegOrRegClass,
1179         late: bool,
1180         place: Option<Place<'tcx>>,
1181     },
1182     InOut {
1183         reg: InlineAsmRegOrRegClass,
1184         late: bool,
1185         in_value: Operand<'tcx>,
1186         out_place: Option<Place<'tcx>>,
1187     },
1188     Const {
1189         value: Operand<'tcx>,
1190     },
1191     SymFn {
1192         value: Box<Constant<'tcx>>,
1193     },
1194     SymStatic {
1195         def_id: DefId,
1196     },
1197 }
1198
1199 /// Type for MIR `Assert` terminator error messages.
1200 pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
1201
1202 pub type Successors<'a> =
1203     iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1204 pub type SuccessorsMut<'a> =
1205     iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1206
1207 impl<'tcx> BasicBlockData<'tcx> {
1208     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1209         BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1210     }
1211
1212     /// Accessor for terminator.
1213     ///
1214     /// Terminator may not be None after construction of the basic block is complete. This accessor
1215     /// provides a convenience way to reach the terminator.
1216     pub fn terminator(&self) -> &Terminator<'tcx> {
1217         self.terminator.as_ref().expect("invalid terminator state")
1218     }
1219
1220     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1221         self.terminator.as_mut().expect("invalid terminator state")
1222     }
1223
1224     pub fn retain_statements<F>(&mut self, mut f: F)
1225     where
1226         F: FnMut(&mut Statement<'_>) -> bool,
1227     {
1228         for s in &mut self.statements {
1229             if !f(s) {
1230                 s.make_nop();
1231             }
1232         }
1233     }
1234
1235     pub fn expand_statements<F, I>(&mut self, mut f: F)
1236     where
1237         F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1238         I: iter::TrustedLen<Item = Statement<'tcx>>,
1239     {
1240         // Gather all the iterators we'll need to splice in, and their positions.
1241         let mut splices: Vec<(usize, I)> = vec![];
1242         let mut extra_stmts = 0;
1243         for (i, s) in self.statements.iter_mut().enumerate() {
1244             if let Some(mut new_stmts) = f(s) {
1245                 if let Some(first) = new_stmts.next() {
1246                     // We can already store the first new statement.
1247                     *s = first;
1248
1249                     // Save the other statements for optimized splicing.
1250                     let remaining = new_stmts.size_hint().0;
1251                     if remaining > 0 {
1252                         splices.push((i + 1 + extra_stmts, new_stmts));
1253                         extra_stmts += remaining;
1254                     }
1255                 } else {
1256                     s.make_nop();
1257                 }
1258             }
1259         }
1260
1261         // Splice in the new statements, from the end of the block.
1262         // FIXME(eddyb) This could be more efficient with a "gap buffer"
1263         // where a range of elements ("gap") is left uninitialized, with
1264         // splicing adding new elements to the end of that gap and moving
1265         // existing elements from before the gap to the end of the gap.
1266         // For now, this is safe code, emulating a gap but initializing it.
1267         let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1268         self.statements.resize(
1269             gap.end,
1270             Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop },
1271         );
1272         for (splice_start, new_stmts) in splices.into_iter().rev() {
1273             let splice_end = splice_start + new_stmts.size_hint().0;
1274             while gap.end > splice_end {
1275                 gap.start -= 1;
1276                 gap.end -= 1;
1277                 self.statements.swap(gap.start, gap.end);
1278             }
1279             self.statements.splice(splice_start..splice_end, new_stmts);
1280             gap.end = splice_start;
1281         }
1282     }
1283
1284     pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1285         if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1286     }
1287 }
1288
1289 impl<O> AssertKind<O> {
1290     /// Getting a description does not require `O` to be printable, and does not
1291     /// require allocation.
1292     /// The caller is expected to handle `BoundsCheck` separately.
1293     pub fn description(&self) -> &'static str {
1294         use AssertKind::*;
1295         match self {
1296             Overflow(BinOp::Add, _, _) => "attempt to add with overflow",
1297             Overflow(BinOp::Sub, _, _) => "attempt to subtract with overflow",
1298             Overflow(BinOp::Mul, _, _) => "attempt to multiply with overflow",
1299             Overflow(BinOp::Div, _, _) => "attempt to divide with overflow",
1300             Overflow(BinOp::Rem, _, _) => "attempt to calculate the remainder with overflow",
1301             OverflowNeg(_) => "attempt to negate with overflow",
1302             Overflow(BinOp::Shr, _, _) => "attempt to shift right with overflow",
1303             Overflow(BinOp::Shl, _, _) => "attempt to shift left with overflow",
1304             Overflow(op, _, _) => bug!("{:?} cannot overflow", op),
1305             DivisionByZero(_) => "attempt to divide by zero",
1306             RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero",
1307             ResumedAfterReturn(GeneratorKind::Gen) => "generator resumed after completion",
1308             ResumedAfterReturn(GeneratorKind::Async(_)) => "`async fn` resumed after completion",
1309             ResumedAfterPanic(GeneratorKind::Gen) => "generator resumed after panicking",
1310             ResumedAfterPanic(GeneratorKind::Async(_)) => "`async fn` resumed after panicking",
1311             BoundsCheck { .. } => bug!("Unexpected AssertKind"),
1312         }
1313     }
1314
1315     /// Format the message arguments for the `assert(cond, msg..)` terminator in MIR printing.
1316     fn fmt_assert_args<W: Write>(&self, f: &mut W) -> fmt::Result
1317     where
1318         O: Debug,
1319     {
1320         use AssertKind::*;
1321         match self {
1322             BoundsCheck { ref len, ref index } => write!(
1323                 f,
1324                 "\"index out of bounds: the length is {{}} but the index is {{}}\", {:?}, {:?}",
1325                 len, index
1326             ),
1327
1328             OverflowNeg(op) => {
1329                 write!(f, "\"attempt to negate `{{}}`, which would overflow\", {:?}", op)
1330             }
1331             DivisionByZero(op) => write!(f, "\"attempt to divide `{{}}` by zero\", {:?}", op),
1332             RemainderByZero(op) => write!(
1333                 f,
1334                 "\"attempt to calculate the remainder of `{{}}` with a divisor of zero\", {:?}",
1335                 op
1336             ),
1337             Overflow(BinOp::Add, l, r) => write!(
1338                 f,
1339                 "\"attempt to compute `{{}} + {{}}`, which would overflow\", {:?}, {:?}",
1340                 l, r
1341             ),
1342             Overflow(BinOp::Sub, l, r) => write!(
1343                 f,
1344                 "\"attempt to compute `{{}} - {{}}`, which would overflow\", {:?}, {:?}",
1345                 l, r
1346             ),
1347             Overflow(BinOp::Mul, l, r) => write!(
1348                 f,
1349                 "\"attempt to compute `{{}} * {{}}`, which would overflow\", {:?}, {:?}",
1350                 l, r
1351             ),
1352             Overflow(BinOp::Div, l, r) => write!(
1353                 f,
1354                 "\"attempt to compute `{{}} / {{}}`, which would overflow\", {:?}, {:?}",
1355                 l, r
1356             ),
1357             Overflow(BinOp::Rem, l, r) => write!(
1358                 f,
1359                 "\"attempt to compute the remainder of `{{}} % {{}}`, which would overflow\", {:?}, {:?}",
1360                 l, r
1361             ),
1362             Overflow(BinOp::Shr, _, r) => {
1363                 write!(f, "\"attempt to shift right by `{{}}`, which would overflow\", {:?}", r)
1364             }
1365             Overflow(BinOp::Shl, _, r) => {
1366                 write!(f, "\"attempt to shift left by `{{}}`, which would overflow\", {:?}", r)
1367             }
1368             _ => write!(f, "\"{}\"", self.description()),
1369         }
1370     }
1371 }
1372
1373 impl<O: fmt::Debug> fmt::Debug for AssertKind<O> {
1374     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1375         use AssertKind::*;
1376         match self {
1377             BoundsCheck { ref len, ref index } => write!(
1378                 f,
1379                 "index out of bounds: the length is {:?} but the index is {:?}",
1380                 len, index
1381             ),
1382             OverflowNeg(op) => write!(f, "attempt to negate `{:#?}`, which would overflow", op),
1383             DivisionByZero(op) => write!(f, "attempt to divide `{:#?}` by zero", op),
1384             RemainderByZero(op) => write!(
1385                 f,
1386                 "attempt to calculate the remainder of `{:#?}` with a divisor of zero",
1387                 op
1388             ),
1389             Overflow(BinOp::Add, l, r) => {
1390                 write!(f, "attempt to compute `{:#?} + {:#?}`, which would overflow", l, r)
1391             }
1392             Overflow(BinOp::Sub, l, r) => {
1393                 write!(f, "attempt to compute `{:#?} - {:#?}`, which would overflow", l, r)
1394             }
1395             Overflow(BinOp::Mul, l, r) => {
1396                 write!(f, "attempt to compute `{:#?} * {:#?}`, which would overflow", l, r)
1397             }
1398             Overflow(BinOp::Div, l, r) => {
1399                 write!(f, "attempt to compute `{:#?} / {:#?}`, which would overflow", l, r)
1400             }
1401             Overflow(BinOp::Rem, l, r) => write!(
1402                 f,
1403                 "attempt to compute the remainder of `{:#?} % {:#?}`, which would overflow",
1404                 l, r
1405             ),
1406             Overflow(BinOp::Shr, _, r) => {
1407                 write!(f, "attempt to shift right by `{:#?}`, which would overflow", r)
1408             }
1409             Overflow(BinOp::Shl, _, r) => {
1410                 write!(f, "attempt to shift left by `{:#?}`, which would overflow", r)
1411             }
1412             _ => write!(f, "{}", self.description()),
1413         }
1414     }
1415 }
1416
1417 ///////////////////////////////////////////////////////////////////////////
1418 // Statements
1419
1420 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1421 pub struct Statement<'tcx> {
1422     pub source_info: SourceInfo,
1423     pub kind: StatementKind<'tcx>,
1424 }
1425
1426 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1427 #[cfg(target_arch = "x86_64")]
1428 static_assert_size!(Statement<'_>, 32);
1429
1430 impl Statement<'_> {
1431     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1432     /// invalidating statement indices in `Location`s.
1433     pub fn make_nop(&mut self) {
1434         self.kind = StatementKind::Nop
1435     }
1436
1437     /// Changes a statement to a nop and returns the original statement.
1438     pub fn replace_nop(&mut self) -> Self {
1439         Statement {
1440             source_info: self.source_info,
1441             kind: mem::replace(&mut self.kind, StatementKind::Nop),
1442         }
1443     }
1444 }
1445
1446 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1447 pub enum StatementKind<'tcx> {
1448     /// Write the RHS Rvalue to the LHS Place.
1449     Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1450
1451     /// This represents all the reading that a pattern match may do
1452     /// (e.g., inspecting constants and discriminant values), and the
1453     /// kind of pattern it comes from. This is in order to adapt potential
1454     /// error messages to these specific patterns.
1455     ///
1456     /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1457     /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1458     FakeRead(FakeReadCause, Box<Place<'tcx>>),
1459
1460     /// Write the discriminant for a variant to the enum Place.
1461     SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1462
1463     /// Start a live range for the storage of the local.
1464     StorageLive(Local),
1465
1466     /// End the current live range for the storage of the local.
1467     StorageDead(Local),
1468
1469     /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1470     /// of `StatementKind` low.
1471     LlvmInlineAsm(Box<LlvmInlineAsm<'tcx>>),
1472
1473     /// Retag references in the given place, ensuring they got fresh tags. This is
1474     /// part of the Stacked Borrows model. These statements are currently only interpreted
1475     /// by miri and only generated when "-Z mir-emit-retag" is passed.
1476     /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1477     /// for more details.
1478     Retag(RetagKind, Box<Place<'tcx>>),
1479
1480     /// Encodes a user's type ascription. These need to be preserved
1481     /// intact so that NLL can respect them. For example:
1482     ///
1483     ///     let a: T = y;
1484     ///
1485     /// The effect of this annotation is to relate the type `T_y` of the place `y`
1486     /// to the user-given type `T`. The effect depends on the specified variance:
1487     ///
1488     /// - `Covariant` -- requires that `T_y <: T`
1489     /// - `Contravariant` -- requires that `T_y :> T`
1490     /// - `Invariant` -- requires that `T_y == T`
1491     /// - `Bivariant` -- no effect
1492     AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1493
1494     /// Marks the start of a "coverage region", injected with '-Zinstrument-coverage'. A
1495     /// `CoverageInfo` statement carries metadata about the coverage region, used to inject a coverage
1496     /// map into the binary. The `Counter` kind also generates executable code, to increment a
1497     /// counter varible at runtime, each time the code region is executed.
1498     Coverage(Box<Coverage>),
1499
1500     /// No-op. Useful for deleting instructions without affecting statement indices.
1501     Nop,
1502 }
1503
1504 impl<'tcx> StatementKind<'tcx> {
1505     pub fn as_assign_mut(&mut self) -> Option<&mut Box<(Place<'tcx>, Rvalue<'tcx>)>> {
1506         match self {
1507             StatementKind::Assign(x) => Some(x),
1508             _ => None,
1509         }
1510     }
1511 }
1512
1513 /// Describes what kind of retag is to be performed.
1514 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, HashStable)]
1515 pub enum RetagKind {
1516     /// The initial retag when entering a function.
1517     FnEntry,
1518     /// Retag preparing for a two-phase borrow.
1519     TwoPhase,
1520     /// Retagging raw pointers.
1521     Raw,
1522     /// A "normal" retag.
1523     Default,
1524 }
1525
1526 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1527 #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, HashStable, PartialEq)]
1528 pub enum FakeReadCause {
1529     /// Inject a fake read of the borrowed input at the end of each guards
1530     /// code.
1531     ///
1532     /// This should ensure that you cannot change the variant for an enum while
1533     /// you are in the midst of matching on it.
1534     ForMatchGuard,
1535
1536     /// `let x: !; match x {}` doesn't generate any read of x so we need to
1537     /// generate a read of x to check that it is initialized and safe.
1538     ForMatchedPlace,
1539
1540     /// A fake read of the RefWithinGuard version of a bind-by-value variable
1541     /// in a match guard to ensure that it's value hasn't change by the time
1542     /// we create the OutsideGuard version.
1543     ForGuardBinding,
1544
1545     /// Officially, the semantics of
1546     ///
1547     /// `let pattern = <expr>;`
1548     ///
1549     /// is that `<expr>` is evaluated into a temporary and then this temporary is
1550     /// into the pattern.
1551     ///
1552     /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1553     /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1554     /// but in some cases it can affect the borrow checker, as in #53695.
1555     /// Therefore, we insert a "fake read" here to ensure that we get
1556     /// appropriate errors.
1557     ForLet,
1558
1559     /// If we have an index expression like
1560     ///
1561     /// (*x)[1][{ x = y; 4}]
1562     ///
1563     /// then the first bounds check is invalidated when we evaluate the second
1564     /// index expression. Thus we create a fake borrow of `x` across the second
1565     /// indexer, which will cause a borrow check error.
1566     ForIndex,
1567 }
1568
1569 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1570 pub struct LlvmInlineAsm<'tcx> {
1571     pub asm: hir::LlvmInlineAsmInner,
1572     pub outputs: Box<[Place<'tcx>]>,
1573     pub inputs: Box<[(Span, Operand<'tcx>)]>,
1574 }
1575
1576 impl Debug for Statement<'_> {
1577     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1578         use self::StatementKind::*;
1579         match self.kind {
1580             Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1581             FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1582             Retag(ref kind, ref place) => write!(
1583                 fmt,
1584                 "Retag({}{:?})",
1585                 match kind {
1586                     RetagKind::FnEntry => "[fn entry] ",
1587                     RetagKind::TwoPhase => "[2phase] ",
1588                     RetagKind::Raw => "[raw] ",
1589                     RetagKind::Default => "",
1590                 },
1591                 place,
1592             ),
1593             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1594             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1595             SetDiscriminant { ref place, variant_index } => {
1596                 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1597             }
1598             LlvmInlineAsm(ref asm) => {
1599                 write!(fmt, "llvm_asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1600             }
1601             AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1602                 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1603             }
1604             Coverage(box ref coverage) => {
1605                 if let Some(rgn) = &coverage.code_region {
1606                     write!(fmt, "Coverage::{:?} for {:?}", coverage.kind, rgn)
1607                 } else {
1608                     write!(fmt, "Coverage::{:?}", coverage.kind)
1609                 }
1610             }
1611             Nop => write!(fmt, "nop"),
1612         }
1613     }
1614 }
1615
1616 #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1617 pub struct Coverage {
1618     pub kind: CoverageKind,
1619     pub code_region: Option<CodeRegion>,
1620 }
1621
1622 ///////////////////////////////////////////////////////////////////////////
1623 // Places
1624
1625 /// A path to a value; something that can be evaluated without
1626 /// changing or disturbing program state.
1627 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
1628 pub struct Place<'tcx> {
1629     pub local: Local,
1630
1631     /// projection out of a place (access a field, deref a pointer, etc)
1632     pub projection: &'tcx List<PlaceElem<'tcx>>,
1633 }
1634
1635 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1636 #[derive(TyEncodable, TyDecodable, HashStable)]
1637 pub enum ProjectionElem<V, T> {
1638     Deref,
1639     Field(Field, T),
1640     Index(V),
1641
1642     /// These indices are generated by slice patterns. Easiest to explain
1643     /// by example:
1644     ///
1645     /// ```
1646     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1647     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1648     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1649     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1650     /// ```
1651     ConstantIndex {
1652         /// index or -index (in Python terms), depending on from_end
1653         offset: u64,
1654         /// The thing being indexed must be at least this long. For arrays this
1655         /// is always the exact length.
1656         min_length: u64,
1657         /// Counting backwards from end? This is always false when indexing an
1658         /// array.
1659         from_end: bool,
1660     },
1661
1662     /// These indices are generated by slice patterns.
1663     ///
1664     /// If `from_end` is true `slice[from..slice.len() - to]`.
1665     /// Otherwise `array[from..to]`.
1666     Subslice {
1667         from: u64,
1668         to: u64,
1669         /// Whether `to` counts from the start or end of the array/slice.
1670         /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1671         /// For `ProjectionKind`, this can also be `true` for arrays.
1672         from_end: bool,
1673     },
1674
1675     /// "Downcast" to a variant of an ADT. Currently, we only introduce
1676     /// this for ADTs with more than one variant. It may be better to
1677     /// just introduce it always, or always for enums.
1678     ///
1679     /// The included Symbol is the name of the variant, used for printing MIR.
1680     Downcast(Option<Symbol>, VariantIdx),
1681 }
1682
1683 impl<V, T> ProjectionElem<V, T> {
1684     /// Returns `true` if the target of this projection may refer to a different region of memory
1685     /// than the base.
1686     fn is_indirect(&self) -> bool {
1687         match self {
1688             Self::Deref => true,
1689
1690             Self::Field(_, _)
1691             | Self::Index(_)
1692             | Self::ConstantIndex { .. }
1693             | Self::Subslice { .. }
1694             | Self::Downcast(_, _) => false,
1695         }
1696     }
1697 }
1698
1699 /// Alias for projections as they appear in places, where the base is a place
1700 /// and the index is a local.
1701 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1702
1703 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1704 #[cfg(target_arch = "x86_64")]
1705 static_assert_size!(PlaceElem<'_>, 24);
1706
1707 /// Alias for projections as they appear in `UserTypeProjection`, where we
1708 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1709 pub type ProjectionKind = ProjectionElem<(), ()>;
1710
1711 rustc_index::newtype_index! {
1712     pub struct Field {
1713         derive [HashStable]
1714         DEBUG_FORMAT = "field[{}]"
1715     }
1716 }
1717
1718 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1719 pub struct PlaceRef<'tcx> {
1720     pub local: Local,
1721     pub projection: &'tcx [PlaceElem<'tcx>],
1722 }
1723
1724 impl<'tcx> Place<'tcx> {
1725     // FIXME change this to a const fn by also making List::empty a const fn.
1726     pub fn return_place() -> Place<'tcx> {
1727         Place { local: RETURN_PLACE, projection: List::empty() }
1728     }
1729
1730     /// Returns `true` if this `Place` contains a `Deref` projection.
1731     ///
1732     /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1733     /// same region of memory as its base.
1734     pub fn is_indirect(&self) -> bool {
1735         self.projection.iter().any(|elem| elem.is_indirect())
1736     }
1737
1738     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1739     /// a single deref of a local.
1740     //
1741     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1742     pub fn local_or_deref_local(&self) -> Option<Local> {
1743         match self.as_ref() {
1744             PlaceRef { local, projection: [] }
1745             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1746             _ => None,
1747         }
1748     }
1749
1750     /// If this place represents a local variable like `_X` with no
1751     /// projections, return `Some(_X)`.
1752     pub fn as_local(&self) -> Option<Local> {
1753         self.as_ref().as_local()
1754     }
1755
1756     pub fn as_ref(&self) -> PlaceRef<'tcx> {
1757         PlaceRef { local: self.local, projection: &self.projection }
1758     }
1759
1760     /// Iterate over the projections in evaluation order, i.e., the first element is the base with
1761     /// its projection and then subsequently more projections are added.
1762     /// As a concrete example, given the place a.b.c, this would yield:
1763     /// - (a, .b)
1764     /// - (a.b, .c)
1765     /// Given a place without projections, the iterator is empty.
1766     pub fn iter_projections(
1767         self,
1768     ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
1769         self.projection.iter().enumerate().map(move |(i, proj)| {
1770             let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
1771             (base, proj)
1772         })
1773     }
1774 }
1775
1776 impl From<Local> for Place<'_> {
1777     fn from(local: Local) -> Self {
1778         Place { local, projection: List::empty() }
1779     }
1780 }
1781
1782 impl<'tcx> PlaceRef<'tcx> {
1783     /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1784     /// a single deref of a local.
1785     //
1786     // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1787     pub fn local_or_deref_local(&self) -> Option<Local> {
1788         match *self {
1789             PlaceRef { local, projection: [] }
1790             | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
1791             _ => None,
1792         }
1793     }
1794
1795     /// If this place represents a local variable like `_X` with no
1796     /// projections, return `Some(_X)`.
1797     pub fn as_local(&self) -> Option<Local> {
1798         match *self {
1799             PlaceRef { local, projection: [] } => Some(local),
1800             _ => None,
1801         }
1802     }
1803 }
1804
1805 impl Debug for Place<'_> {
1806     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1807         for elem in self.projection.iter().rev() {
1808             match elem {
1809                 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1810                     write!(fmt, "(").unwrap();
1811                 }
1812                 ProjectionElem::Deref => {
1813                     write!(fmt, "(*").unwrap();
1814                 }
1815                 ProjectionElem::Index(_)
1816                 | ProjectionElem::ConstantIndex { .. }
1817                 | ProjectionElem::Subslice { .. } => {}
1818             }
1819         }
1820
1821         write!(fmt, "{:?}", self.local)?;
1822
1823         for elem in self.projection.iter() {
1824             match elem {
1825                 ProjectionElem::Downcast(Some(name), _index) => {
1826                     write!(fmt, " as {})", name)?;
1827                 }
1828                 ProjectionElem::Downcast(None, index) => {
1829                     write!(fmt, " as variant#{:?})", index)?;
1830                 }
1831                 ProjectionElem::Deref => {
1832                     write!(fmt, ")")?;
1833                 }
1834                 ProjectionElem::Field(field, ty) => {
1835                     write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1836                 }
1837                 ProjectionElem::Index(ref index) => {
1838                     write!(fmt, "[{:?}]", index)?;
1839                 }
1840                 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1841                     write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1842                 }
1843                 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1844                     write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1845                 }
1846                 ProjectionElem::Subslice { from, to, from_end: true } if to == 0 => {
1847                     write!(fmt, "[{:?}:]", from)?;
1848                 }
1849                 ProjectionElem::Subslice { from, to, from_end: true } if from == 0 => {
1850                     write!(fmt, "[:-{:?}]", to)?;
1851                 }
1852                 ProjectionElem::Subslice { from, to, from_end: true } => {
1853                     write!(fmt, "[{:?}:-{:?}]", from, to)?;
1854                 }
1855                 ProjectionElem::Subslice { from, to, from_end: false } => {
1856                     write!(fmt, "[{:?}..{:?}]", from, to)?;
1857                 }
1858             }
1859         }
1860
1861         Ok(())
1862     }
1863 }
1864
1865 ///////////////////////////////////////////////////////////////////////////
1866 // Scopes
1867
1868 rustc_index::newtype_index! {
1869     pub struct SourceScope {
1870         derive [HashStable]
1871         DEBUG_FORMAT = "scope[{}]",
1872         const OUTERMOST_SOURCE_SCOPE = 0,
1873     }
1874 }
1875
1876 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
1877 pub struct SourceScopeData<'tcx> {
1878     pub span: Span,
1879     pub parent_scope: Option<SourceScope>,
1880
1881     /// Whether this scope is the root of a scope tree of another body,
1882     /// inlined into this body by the MIR inliner.
1883     /// `ty::Instance` is the callee, and the `Span` is the call site.
1884     pub inlined: Option<(ty::Instance<'tcx>, Span)>,
1885
1886     /// Nearest (transitive) parent scope (if any) which is inlined.
1887     /// This is an optimization over walking up `parent_scope`
1888     /// until a scope with `inlined: Some(...)` is found.
1889     pub inlined_parent_scope: Option<SourceScope>,
1890
1891     /// Crate-local information for this source scope, that can't (and
1892     /// needn't) be tracked across crates.
1893     pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1894 }
1895
1896 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
1897 pub struct SourceScopeLocalData {
1898     /// An `HirId` with lint levels equivalent to this scope's lint levels.
1899     pub lint_root: hir::HirId,
1900     /// The unsafe block that contains this node.
1901     pub safety: Safety,
1902 }
1903
1904 ///////////////////////////////////////////////////////////////////////////
1905 // Operands
1906
1907 /// These are values that can appear inside an rvalue. They are intentionally
1908 /// limited to prevent rvalues from being nested in one another.
1909 #[derive(Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
1910 pub enum Operand<'tcx> {
1911     /// Copy: The value must be available for use afterwards.
1912     ///
1913     /// This implies that the type of the place must be `Copy`; this is true
1914     /// by construction during build, but also checked by the MIR type checker.
1915     Copy(Place<'tcx>),
1916
1917     /// Move: The value (including old borrows of it) will not be used again.
1918     ///
1919     /// Safe for values of all types (modulo future developments towards `?Move`).
1920     /// Correct usage patterns are enforced by the borrow checker for safe code.
1921     /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1922     Move(Place<'tcx>),
1923
1924     /// Synthesizes a constant value.
1925     Constant(Box<Constant<'tcx>>),
1926 }
1927
1928 impl<'tcx> Debug for Operand<'tcx> {
1929     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1930         use self::Operand::*;
1931         match *self {
1932             Constant(ref a) => write!(fmt, "{:?}", a),
1933             Copy(ref place) => write!(fmt, "{:?}", place),
1934             Move(ref place) => write!(fmt, "move {:?}", place),
1935         }
1936     }
1937 }
1938
1939 impl<'tcx> Operand<'tcx> {
1940     /// Convenience helper to make a constant that refers to the fn
1941     /// with given `DefId` and substs. Since this is used to synthesize
1942     /// MIR, assumes `user_ty` is None.
1943     pub fn function_handle(
1944         tcx: TyCtxt<'tcx>,
1945         def_id: DefId,
1946         substs: SubstsRef<'tcx>,
1947         span: Span,
1948     ) -> Self {
1949         let ty = tcx.type_of(def_id).subst(tcx, substs);
1950         Operand::Constant(box Constant {
1951             span,
1952             user_ty: None,
1953             literal: ty::Const::zero_sized(tcx, ty),
1954         })
1955     }
1956
1957     pub fn is_move(&self) -> bool {
1958         matches!(self, Operand::Move(..))
1959     }
1960
1961     /// Convenience helper to make a literal-like constant from a given scalar value.
1962     /// Since this is used to synthesize MIR, assumes `user_ty` is None.
1963     pub fn const_from_scalar(
1964         tcx: TyCtxt<'tcx>,
1965         ty: Ty<'tcx>,
1966         val: Scalar,
1967         span: Span,
1968     ) -> Operand<'tcx> {
1969         debug_assert!({
1970             let param_env_and_ty = ty::ParamEnv::empty().and(ty);
1971             let type_size = tcx
1972                 .layout_of(param_env_and_ty)
1973                 .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e))
1974                 .size;
1975             let scalar_size = match val {
1976                 Scalar::Int(int) => int.size(),
1977                 _ => panic!("Invalid scalar type {:?}", val),
1978             };
1979             scalar_size == type_size
1980         });
1981         Operand::Constant(box Constant {
1982             span,
1983             user_ty: None,
1984             literal: ty::Const::from_scalar(tcx, val, ty),
1985         })
1986     }
1987
1988     pub fn to_copy(&self) -> Self {
1989         match *self {
1990             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1991             Operand::Move(place) => Operand::Copy(place),
1992         }
1993     }
1994
1995     /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
1996     /// constant.
1997     pub fn place(&self) -> Option<Place<'tcx>> {
1998         match self {
1999             Operand::Copy(place) | Operand::Move(place) => Some(*place),
2000             Operand::Constant(_) => None,
2001         }
2002     }
2003
2004     /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a
2005     /// place.
2006     pub fn constant(&self) -> Option<&Constant<'tcx>> {
2007         match self {
2008             Operand::Constant(x) => Some(&**x),
2009             Operand::Copy(_) | Operand::Move(_) => None,
2010         }
2011     }
2012 }
2013
2014 ///////////////////////////////////////////////////////////////////////////
2015 /// Rvalues
2016
2017 #[derive(Clone, TyEncodable, TyDecodable, HashStable, PartialEq)]
2018 pub enum Rvalue<'tcx> {
2019     /// x (either a move or copy, depending on type of x)
2020     Use(Operand<'tcx>),
2021
2022     /// [x; 32]
2023     Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>),
2024
2025     /// &x or &mut x
2026     Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2027
2028     /// Accessing a thread local static. This is inherently a runtime operation, even if llvm
2029     /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local
2030     /// static.
2031     ThreadLocalRef(DefId),
2032
2033     /// Create a raw pointer to the given place
2034     /// Can be generated by raw address of expressions (`&raw const x`),
2035     /// or when casting a reference to a raw pointer.
2036     AddressOf(Mutability, Place<'tcx>),
2037
2038     /// length of a `[X]` or `[X;n]` value
2039     Len(Place<'tcx>),
2040
2041     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2042
2043     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2044     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2045
2046     NullaryOp(NullOp, Ty<'tcx>),
2047     UnaryOp(UnOp, Operand<'tcx>),
2048
2049     /// Read the discriminant of an ADT.
2050     ///
2051     /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2052     /// be defined to return, say, a 0) if ADT is not an enum.
2053     Discriminant(Place<'tcx>),
2054
2055     /// Creates an aggregate value, like a tuple or struct. This is
2056     /// only needed because we want to distinguish `dest = Foo { x:
2057     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2058     /// that `Foo` has a destructor. These rvalues can be optimized
2059     /// away after type-checking and before lowering.
2060     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2061 }
2062
2063 #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2064 pub enum CastKind {
2065     Misc,
2066     Pointer(PointerCast),
2067 }
2068
2069 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2070 pub enum AggregateKind<'tcx> {
2071     /// The type is of the element
2072     Array(Ty<'tcx>),
2073     Tuple,
2074
2075     /// The second field is the variant index. It's equal to 0 for struct
2076     /// and union expressions. The fourth field is
2077     /// active field number and is present only for union expressions
2078     /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2079     /// active field index would identity the field `c`
2080     Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2081
2082     Closure(DefId, SubstsRef<'tcx>),
2083     Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2084 }
2085
2086 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2087 pub enum BinOp {
2088     /// The `+` operator (addition)
2089     Add,
2090     /// The `-` operator (subtraction)
2091     Sub,
2092     /// The `*` operator (multiplication)
2093     Mul,
2094     /// The `/` operator (division)
2095     Div,
2096     /// The `%` operator (modulus)
2097     Rem,
2098     /// The `^` operator (bitwise xor)
2099     BitXor,
2100     /// The `&` operator (bitwise and)
2101     BitAnd,
2102     /// The `|` operator (bitwise or)
2103     BitOr,
2104     /// The `<<` operator (shift left)
2105     Shl,
2106     /// The `>>` operator (shift right)
2107     Shr,
2108     /// The `==` operator (equality)
2109     Eq,
2110     /// The `<` operator (less than)
2111     Lt,
2112     /// The `<=` operator (less than or equal to)
2113     Le,
2114     /// The `!=` operator (not equal to)
2115     Ne,
2116     /// The `>=` operator (greater than or equal to)
2117     Ge,
2118     /// The `>` operator (greater than)
2119     Gt,
2120     /// The `ptr.offset` operator
2121     Offset,
2122 }
2123
2124 impl BinOp {
2125     pub fn is_checkable(self) -> bool {
2126         use self::BinOp::*;
2127         matches!(self, Add | Sub | Mul | Shl | Shr)
2128     }
2129 }
2130
2131 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2132 pub enum NullOp {
2133     /// Returns the size of a value of that type
2134     SizeOf,
2135     /// Creates a new uninitialized box for a value of that type
2136     Box,
2137 }
2138
2139 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
2140 pub enum UnOp {
2141     /// The `!` operator for logical inversion
2142     Not,
2143     /// The `-` operator for negation
2144     Neg,
2145 }
2146
2147 impl<'tcx> Debug for Rvalue<'tcx> {
2148     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2149         use self::Rvalue::*;
2150
2151         match *self {
2152             Use(ref place) => write!(fmt, "{:?}", place),
2153             Repeat(ref a, ref b) => {
2154                 write!(fmt, "[{:?}; ", a)?;
2155                 pretty_print_const(b, fmt, false)?;
2156                 write!(fmt, "]")
2157             }
2158             Len(ref a) => write!(fmt, "Len({:?})", a),
2159             Cast(ref kind, ref place, ref ty) => {
2160                 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2161             }
2162             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2163             CheckedBinaryOp(ref op, ref a, ref b) => {
2164                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2165             }
2166             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2167             Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2168             NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2169             ThreadLocalRef(did) => ty::tls::with(|tcx| {
2170                 let muta = tcx.static_mutability(did).unwrap().prefix_str();
2171                 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
2172             }),
2173             Ref(region, borrow_kind, ref place) => {
2174                 let kind_str = match borrow_kind {
2175                     BorrowKind::Shared => "",
2176                     BorrowKind::Shallow => "shallow ",
2177                     BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2178                 };
2179
2180                 // When printing regions, add trailing space if necessary.
2181                 let print_region = ty::tls::with(|tcx| {
2182                     tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2183                 });
2184                 let region = if print_region {
2185                     let mut region = region.to_string();
2186                     if !region.is_empty() {
2187                         region.push(' ');
2188                     }
2189                     region
2190                 } else {
2191                     // Do not even print 'static
2192                     String::new()
2193                 };
2194                 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2195             }
2196
2197             AddressOf(mutability, ref place) => {
2198                 let kind_str = match mutability {
2199                     Mutability::Mut => "mut",
2200                     Mutability::Not => "const",
2201                 };
2202
2203                 write!(fmt, "&raw {} {:?}", kind_str, place)
2204             }
2205
2206             Aggregate(ref kind, ref places) => {
2207                 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
2208                     let mut tuple_fmt = fmt.debug_tuple(name);
2209                     for place in places {
2210                         tuple_fmt.field(place);
2211                     }
2212                     tuple_fmt.finish()
2213                 };
2214
2215                 match **kind {
2216                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2217
2218                     AggregateKind::Tuple => {
2219                         if places.is_empty() {
2220                             write!(fmt, "()")
2221                         } else {
2222                             fmt_tuple(fmt, "")
2223                         }
2224                     }
2225
2226                     AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2227                         let variant_def = &adt_def.variants[variant];
2228
2229                         let name = ty::tls::with(|tcx| {
2230                             let mut name = String::new();
2231                             let substs = tcx.lift(substs).expect("could not lift for printing");
2232                             FmtPrinter::new(tcx, &mut name, Namespace::ValueNS)
2233                                 .print_def_path(variant_def.def_id, substs)?;
2234                             Ok(name)
2235                         })?;
2236
2237                         match variant_def.ctor_kind {
2238                             CtorKind::Const => fmt.write_str(&name),
2239                             CtorKind::Fn => fmt_tuple(fmt, &name),
2240                             CtorKind::Fictive => {
2241                                 let mut struct_fmt = fmt.debug_struct(&name);
2242                                 for (field, place) in variant_def.fields.iter().zip(places) {
2243                                     struct_fmt.field(&field.ident.as_str(), place);
2244                                 }
2245                                 struct_fmt.finish()
2246                             }
2247                         }
2248                     }
2249
2250                     AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2251                         if let Some(def_id) = def_id.as_local() {
2252                             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2253                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2254                                 let substs = tcx.lift(substs).unwrap();
2255                                 format!(
2256                                     "[closure@{}]",
2257                                     tcx.def_path_str_with_substs(def_id.to_def_id(), substs),
2258                                 )
2259                             } else {
2260                                 let span = tcx.hir().span(hir_id);
2261                                 format!("[closure@{}]", tcx.sess.source_map().span_to_string(span))
2262                             };
2263                             let mut struct_fmt = fmt.debug_struct(&name);
2264
2265                             if let Some(upvars) = tcx.upvars_mentioned(def_id) {
2266                                 for (&var_id, place) in upvars.keys().zip(places) {
2267                                     let var_name = tcx.hir().name(var_id);
2268                                     struct_fmt.field(&var_name.as_str(), place);
2269                                 }
2270                             }
2271
2272                             struct_fmt.finish()
2273                         } else {
2274                             write!(fmt, "[closure]")
2275                         }
2276                     }),
2277
2278                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2279                         if let Some(def_id) = def_id.as_local() {
2280                             let hir_id = tcx.hir().local_def_id_to_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_mentioned(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, Copy, PartialEq, TyEncodable, TyDecodable, 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.global_alloc(ptr.alloc_id) {
2327                 GlobalAlloc::Static(def_id) => {
2328                     assert!(!tcx.is_thread_local_static(def_id));
2329                     Some(def_id)
2330                 }
2331                 _ => None,
2332             },
2333             _ => None,
2334         }
2335     }
2336 }
2337
2338 /// A collection of projections into user types.
2339 ///
2340 /// They are projections because a binding can occur a part of a
2341 /// parent pattern that has been ascribed a type.
2342 ///
2343 /// Its a collection because there can be multiple type ascriptions on
2344 /// the path from the root of the pattern down to the binding itself.
2345 ///
2346 /// An example:
2347 ///
2348 /// ```rust
2349 /// struct S<'a>((i32, &'a str), String);
2350 /// let S((_, w): (i32, &'static str), _): S = ...;
2351 /// //    ------  ^^^^^^^^^^^^^^^^^^^ (1)
2352 /// //  ---------------------------------  ^ (2)
2353 /// ```
2354 ///
2355 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2356 /// ascribed the type `(i32, &'static str)`.
2357 ///
2358 /// The highlights labelled `(2)` show the whole pattern being
2359 /// ascribed the type `S`.
2360 ///
2361 /// In this example, when we descend to `w`, we will have built up the
2362 /// following two projected types:
2363 ///
2364 ///   * base: `S`,                   projection: `(base.0).1`
2365 ///   * base: `(i32, &'static str)`, projection: `base.1`
2366 ///
2367 /// The first will lead to the constraint `w: &'1 str` (for some
2368 /// inferred region `'1`). The second will lead to the constraint `w:
2369 /// &'static str`.
2370 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
2371 pub struct UserTypeProjections {
2372     pub contents: Vec<(UserTypeProjection, Span)>,
2373 }
2374
2375 impl<'tcx> UserTypeProjections {
2376     pub fn none() -> Self {
2377         UserTypeProjections { contents: vec![] }
2378     }
2379
2380     pub fn is_empty(&self) -> bool {
2381         self.contents.is_empty()
2382     }
2383
2384     pub fn projections_and_spans(
2385         &self,
2386     ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2387         self.contents.iter()
2388     }
2389
2390     pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2391         self.contents.iter().map(|&(ref user_type, _span)| user_type)
2392     }
2393
2394     pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2395         self.contents.push((user_ty.clone(), span));
2396         self
2397     }
2398
2399     fn map_projections(
2400         mut self,
2401         mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2402     ) -> Self {
2403         self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2404         self
2405     }
2406
2407     pub fn index(self) -> Self {
2408         self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2409     }
2410
2411     pub fn subslice(self, from: u64, to: u64) -> Self {
2412         self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2413     }
2414
2415     pub fn deref(self) -> Self {
2416         self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2417     }
2418
2419     pub fn leaf(self, field: Field) -> Self {
2420         self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2421     }
2422
2423     pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2424         self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2425     }
2426 }
2427
2428 /// Encodes the effect of a user-supplied type annotation on the
2429 /// subcomponents of a pattern. The effect is determined by applying the
2430 /// given list of proejctions to some underlying base type. Often,
2431 /// the projection element list `projs` is empty, in which case this
2432 /// directly encodes a type in `base`. But in the case of complex patterns with
2433 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2434 /// in which case the `projs` vector is used.
2435 ///
2436 /// Examples:
2437 ///
2438 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2439 ///
2440 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2441 ///   `field[0]` (aka `.0`), indicating that the type of `s` is
2442 ///   determined by finding the type of the `.0` field from `T`.
2443 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, PartialEq)]
2444 pub struct UserTypeProjection {
2445     pub base: UserTypeAnnotationIndex,
2446     pub projs: Vec<ProjectionKind>,
2447 }
2448
2449 impl Copy for ProjectionKind {}
2450
2451 impl UserTypeProjection {
2452     pub(crate) fn index(mut self) -> Self {
2453         self.projs.push(ProjectionElem::Index(()));
2454         self
2455     }
2456
2457     pub(crate) fn subslice(mut self, from: u64, to: u64) -> Self {
2458         self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2459         self
2460     }
2461
2462     pub(crate) fn deref(mut self) -> Self {
2463         self.projs.push(ProjectionElem::Deref);
2464         self
2465     }
2466
2467     pub(crate) fn leaf(mut self, field: Field) -> Self {
2468         self.projs.push(ProjectionElem::Field(field, ()));
2469         self
2470     }
2471
2472     pub(crate) fn variant(
2473         mut self,
2474         adt_def: &AdtDef,
2475         variant_index: VariantIdx,
2476         field: Field,
2477     ) -> Self {
2478         self.projs.push(ProjectionElem::Downcast(
2479             Some(adt_def.variants[variant_index].ident.name),
2480             variant_index,
2481         ));
2482         self.projs.push(ProjectionElem::Field(field, ()));
2483         self
2484     }
2485 }
2486
2487 TrivialTypeFoldableAndLiftImpls! { ProjectionKind, }
2488
2489 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2490     fn super_fold_with<F: TypeFolder<'tcx>>(self, folder: &mut F) -> Self {
2491         UserTypeProjection {
2492             base: self.base.fold_with(folder),
2493             projs: self.projs.fold_with(folder),
2494         }
2495     }
2496
2497     fn super_visit_with<Vs: TypeVisitor<'tcx>>(
2498         &self,
2499         visitor: &mut Vs,
2500     ) -> ControlFlow<Vs::BreakTy> {
2501         self.base.visit_with(visitor)
2502         // Note: there's nothing in `self.proj` to visit.
2503     }
2504 }
2505
2506 rustc_index::newtype_index! {
2507     pub struct Promoted {
2508         derive [HashStable]
2509         DEBUG_FORMAT = "promoted[{}]"
2510     }
2511 }
2512
2513 impl<'tcx> Debug for Constant<'tcx> {
2514     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2515         write!(fmt, "{}", self)
2516     }
2517 }
2518
2519 impl<'tcx> Display for Constant<'tcx> {
2520     fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2521         match self.literal.ty.kind() {
2522             ty::FnDef(..) => {}
2523             _ => write!(fmt, "const ")?,
2524         }
2525         pretty_print_const(self.literal, fmt, true)
2526     }
2527 }
2528
2529 fn pretty_print_const(
2530     c: &ty::Const<'tcx>,
2531     fmt: &mut Formatter<'_>,
2532     print_types: bool,
2533 ) -> fmt::Result {
2534     use crate::ty::print::PrettyPrinter;
2535     ty::tls::with(|tcx| {
2536         let literal = tcx.lift(c).unwrap();
2537         let mut cx = FmtPrinter::new(tcx, fmt, Namespace::ValueNS);
2538         cx.print_alloc_ids = true;
2539         cx.pretty_print_const(literal, print_types)?;
2540         Ok(())
2541     })
2542 }
2543
2544 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2545     type Node = BasicBlock;
2546 }
2547
2548 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2549     #[inline]
2550     fn num_nodes(&self) -> usize {
2551         self.basic_blocks.len()
2552     }
2553 }
2554
2555 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2556     #[inline]
2557     fn start_node(&self) -> Self::Node {
2558         START_BLOCK
2559     }
2560 }
2561
2562 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2563     #[inline]
2564     fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2565         self.basic_blocks[node].terminator().successors().cloned()
2566     }
2567 }
2568
2569 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2570     type Item = BasicBlock;
2571     type Iter = iter::Cloned<Successors<'b>>;
2572 }
2573
2574 impl graph::GraphPredecessors<'graph> for Body<'tcx> {
2575     type Item = BasicBlock;
2576     type Iter = smallvec::IntoIter<[BasicBlock; 4]>;
2577 }
2578
2579 impl graph::WithPredecessors for Body<'tcx> {
2580     #[inline]
2581     fn predecessors(&self, node: Self::Node) -> <Self as graph::GraphPredecessors<'_>>::Iter {
2582         self.predecessors()[node].clone().into_iter()
2583     }
2584 }
2585
2586 /// `Location` represents the position of the start of the statement; or, if
2587 /// `statement_index` equals the number of statements, then the start of the
2588 /// terminator.
2589 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2590 pub struct Location {
2591     /// The block that the location is within.
2592     pub block: BasicBlock,
2593
2594     pub statement_index: usize,
2595 }
2596
2597 impl fmt::Debug for Location {
2598     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2599         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2600     }
2601 }
2602
2603 impl Location {
2604     pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2605
2606     /// Returns the location immediately after this one within the enclosing block.
2607     ///
2608     /// Note that if this location represents a terminator, then the
2609     /// resulting location would be out of bounds and invalid.
2610     pub fn successor_within_block(&self) -> Location {
2611         Location { block: self.block, statement_index: self.statement_index + 1 }
2612     }
2613
2614     /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2615     pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2616         // If we are in the same block as the other location and are an earlier statement
2617         // then we are a predecessor of `other`.
2618         if self.block == other.block && self.statement_index < other.statement_index {
2619             return true;
2620         }
2621
2622         let predecessors = body.predecessors();
2623
2624         // If we're in another block, then we want to check that block is a predecessor of `other`.
2625         let mut queue: Vec<BasicBlock> = predecessors[other.block].to_vec();
2626         let mut visited = FxHashSet::default();
2627
2628         while let Some(block) = queue.pop() {
2629             // If we haven't visited this block before, then make sure we visit it's predecessors.
2630             if visited.insert(block) {
2631                 queue.extend(predecessors[block].iter().cloned());
2632             } else {
2633                 continue;
2634             }
2635
2636             // If we found the block that `self` is in, then we are a predecessor of `other` (since
2637             // we found that block by looking at the predecessors of `other`).
2638             if self.block == block {
2639                 return true;
2640             }
2641         }
2642
2643         false
2644     }
2645
2646     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2647         if self.block == other.block {
2648             self.statement_index <= other.statement_index
2649         } else {
2650             dominators.is_dominated_by(other.block, self.block)
2651         }
2652     }
2653 }