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