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