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