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