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