1 // ignore-tidy-filelength
3 //! MIR datatypes and passes. See the [rustc guide] for more info.
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
7 use crate::hir::def::{CtorKind, Namespace};
8 use crate::hir::def_id::DefId;
9 use crate::hir::{self, GeneratorKind};
10 use crate::mir::interpret::{GlobalAlloc, PanicInfo, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use crate::ty::adjustment::PointerCast;
13 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
14 use crate::ty::layout::VariantIdx;
15 use crate::ty::print::{FmtPrinter, Printer};
16 use crate::ty::subst::{Subst, SubstsRef};
18 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
21 use polonius_engine::Atom;
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::graph::dominators::Dominators;
24 use rustc_data_structures::graph::{self, GraphSuccessors};
25 use rustc_data_structures::sync::Lrc;
26 use rustc_index::bit_set::BitMatrix;
27 use rustc_index::vec::{Idx, IndexVec};
28 use rustc_macros::HashStable;
29 use rustc_serialize::{Decodable, Encodable};
30 use smallvec::SmallVec;
32 use std::fmt::{self, Debug, Display, Formatter, Write};
35 use std::{iter, mem, option, u32};
36 pub use syntax::ast::Mutability;
37 use syntax::ast::Name;
38 use syntax::symbol::Symbol;
39 use syntax_pos::{Span, DUMMY_SP};
41 pub use crate::mir::cache::{BodyAndCache, ReadOnlyBodyAndCache};
42 pub use crate::mir::interpret::AssertMessage;
43 pub use crate::read_only;
53 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55 pub trait HasLocalDecls<'tcx> {
56 fn local_decls(&self) -> &LocalDecls<'tcx>;
59 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx> {
65 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
66 fn local_decls(&self) -> &LocalDecls<'tcx> {
71 /// The various "big phases" that MIR goes through.
73 /// Warning: ordering of variants is significant.
94 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
95 pub fn phase_index(&self) -> usize {
100 /// The lowered representation of a single function.
101 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
102 pub struct Body<'tcx> {
103 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
104 /// that indexes into this vector.
105 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
107 /// Records how far through the "desugaring and optimization" process this particular
108 /// MIR has traversed. This is particularly useful when inlining, since in that context
109 /// we instantiate the promoted constants and add them to our promoted vector -- but those
110 /// promoted items have already been optimized, whereas ours have not. This field allows
111 /// us to see the difference and forego optimization on the inlined promoted items.
114 /// A list of source scopes; these are referenced by statements
115 /// and used for debuginfo. Indexed by a `SourceScope`.
116 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
118 /// The yield type of the function, if it is a generator.
119 pub yield_ty: Option<Ty<'tcx>>,
121 /// Generator drop glue.
122 pub generator_drop: Option<Box<BodyAndCache<'tcx>>>,
124 /// The layout of a generator. Produced by the state transformation.
125 pub generator_layout: Option<GeneratorLayout<'tcx>>,
127 /// If this is a generator then record the type of source expression that caused this generator
129 pub generator_kind: Option<GeneratorKind>,
131 /// Declarations of locals.
133 /// The first local is the return value pointer, followed by `arg_count`
134 /// locals for the function arguments, followed by any user-declared
135 /// variables and temporaries.
136 pub local_decls: LocalDecls<'tcx>,
138 /// User type annotations.
139 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
141 /// The number of arguments this function takes.
143 /// Starting at local 1, `arg_count` locals will be provided by the caller
144 /// and can be assumed to be initialized.
146 /// If this MIR was built for a constant, this will be 0.
147 pub arg_count: usize,
149 /// Mark an argument local (which must be a tuple) as getting passed as
150 /// its individual components at the LLVM level.
152 /// This is used for the "rust-call" ABI.
153 pub spread_arg: Option<Local>,
155 /// Debug information pertaining to user variables, including captures.
156 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
158 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
159 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
160 /// this conversion from happening and use short circuiting, we will cause the following code
161 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
163 /// List of places where control flow was destroyed. Used for error reporting.
164 pub control_flow_destroyed: Vec<(Span, String)>,
166 /// A span representing this MIR, for error reporting.
170 impl<'tcx> Body<'tcx> {
172 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
173 source_scopes: IndexVec<SourceScope, SourceScopeData>,
174 local_decls: LocalDecls<'tcx>,
175 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
177 var_debug_info: Vec<VarDebugInfo<'tcx>>,
179 control_flow_destroyed: Vec<(Span, String)>,
180 generator_kind: Option<GeneratorKind>,
182 // We need `arg_count` locals, and one for the return place.
184 local_decls.len() >= arg_count + 1,
185 "expected at least {} locals, got {}",
191 phase: MirPhase::Build,
195 generator_drop: None,
196 generator_layout: None,
199 user_type_annotations,
204 control_flow_destroyed,
209 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
213 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
215 pub fn is_cfg_cyclic(&self) -> bool {
216 graph::is_cyclic(self)
220 pub fn local_kind(&self, local: Local) -> LocalKind {
221 let index = local.as_usize();
224 self.local_decls[local].mutability == Mutability::Mut,
225 "return place should be mutable"
228 LocalKind::ReturnPointer
229 } else if index < self.arg_count + 1 {
231 } else if self.local_decls[local].is_user_variable() {
238 /// Returns an iterator over all temporaries.
240 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
241 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
242 let local = Local::new(index);
243 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
247 /// Returns an iterator over all user-declared locals.
249 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
250 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
251 let local = Local::new(index);
252 self.local_decls[local].is_user_variable().then_some(local)
256 /// Returns an iterator over all user-declared mutable locals.
258 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
259 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
260 let local = Local::new(index);
261 let decl = &self.local_decls[local];
262 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
270 /// Returns an iterator over all user-declared mutable arguments and locals.
272 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
273 (1..self.local_decls.len()).filter_map(move |index| {
274 let local = Local::new(index);
275 let decl = &self.local_decls[local];
276 if (decl.is_user_variable() || index < self.arg_count + 1)
277 && decl.mutability == Mutability::Mut
286 /// Returns an iterator over all function arguments.
288 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
289 let arg_count = self.arg_count;
290 (1..arg_count + 1).map(Local::new)
293 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
294 /// locals that are neither arguments nor the return place).
296 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
297 let arg_count = self.arg_count;
298 let local_count = self.local_decls.len();
299 (arg_count + 1..local_count).map(Local::new)
302 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
303 /// invalidating statement indices in `Location`s.
304 pub fn make_statement_nop(&mut self, location: Location) {
305 let block = &mut self.basic_blocks[location.block];
306 debug_assert!(location.statement_index < block.statements.len());
307 block.statements[location.statement_index].make_nop()
310 /// Returns the source info associated with `location`.
311 pub fn source_info(&self, location: Location) -> &SourceInfo {
312 let block = &self[location.block];
313 let stmts = &block.statements;
314 let idx = location.statement_index;
315 if idx < stmts.len() {
316 &stmts[idx].source_info
318 assert_eq!(idx, stmts.len());
319 &block.terminator().source_info
323 /// Checks if `sub` is a sub scope of `sup`
324 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
326 match self.source_scopes[sub].parent_scope {
327 None => return false,
334 /// Returns the return type; it always return first element from `local_decls` array.
335 pub fn return_ty(&self) -> Ty<'tcx> {
336 self.local_decls[RETURN_PLACE].ty
339 /// Gets the location of the terminator for the given block.
340 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
341 Location { block: bb, statement_index: self[bb].statements.len() }
345 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
348 /// Unsafe because of a PushUnsafeBlock
350 /// Unsafe because of an unsafe fn
352 /// Unsafe because of an `unsafe` block
353 ExplicitUnsafe(hir::HirId),
356 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
357 type Output = BasicBlockData<'tcx>;
360 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
361 &self.basic_blocks()[index]
365 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
366 pub enum ClearCrossCrate<T> {
371 impl<T> ClearCrossCrate<T> {
372 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
374 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
375 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
379 pub fn assert_crate_local(self) -> T {
381 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
382 ClearCrossCrate::Set(v) => v,
387 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
388 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
390 /// Grouped information about the source code origin of a MIR entity.
391 /// Intended to be inspected by diagnostics and debuginfo.
392 /// Most passes can work with it as a whole, within a single function.
393 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
394 // `Hash`. Please ping @bjorn3 if removing them.
395 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
396 pub struct SourceInfo {
397 /// The source span for the AST pertaining to this MIR entity.
400 /// The source scope, keeping track of which bindings can be
401 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
402 pub scope: SourceScope,
405 ///////////////////////////////////////////////////////////////////////////
420 pub enum BorrowKind {
421 /// Data must be immutable and is aliasable.
424 /// The immediately borrowed place must be immutable, but projections from
425 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
426 /// conflict with a mutable borrow of `a.b.c`.
428 /// This is used when lowering matches: when matching on a place we want to
429 /// ensure that place have the same value from the start of the match until
430 /// an arm is selected. This prevents this code from compiling:
432 /// let mut x = &Some(0);
435 /// Some(_) if { x = &None; false } => (),
439 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
440 /// should not prevent `if let None = x { ... }`, for example, because the
441 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
442 /// We can also report errors with this kind of borrow differently.
445 /// Data must be immutable but not aliasable. This kind of borrow
446 /// cannot currently be expressed by the user and is used only in
447 /// implicit closure bindings. It is needed when the closure is
448 /// borrowing or mutating a mutable referent, e.g.:
450 /// let x: &mut isize = ...;
451 /// let y = || *x += 5;
453 /// If we were to try to translate this closure into a more explicit
454 /// form, we'd encounter an error with the code as written:
456 /// struct Env { x: & &mut isize }
457 /// let x: &mut isize = ...;
458 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
459 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
461 /// This is then illegal because you cannot mutate an `&mut` found
462 /// in an aliasable location. To solve, you'd have to translate with
463 /// an `&mut` borrow:
465 /// struct Env { x: & &mut isize }
466 /// let x: &mut isize = ...;
467 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
468 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
470 /// Now the assignment to `**env.x` is legal, but creating a
471 /// mutable pointer to `x` is not because `x` is not mutable. We
472 /// could fix this by declaring `x` as `let mut x`. This is ok in
473 /// user code, if awkward, but extra weird for closures, since the
474 /// borrow is hidden.
476 /// So we introduce a "unique imm" borrow -- the referent is
477 /// immutable, but not aliasable. This solves the problem. For
478 /// simplicity, we don't give users the way to express this
479 /// borrow, it's just used when translating closures.
482 /// Data is mutable and not aliasable.
484 /// `true` if this borrow arose from method-call auto-ref
485 /// (i.e., `adjustment::Adjust::Borrow`).
486 allow_two_phase_borrow: bool,
491 pub fn allows_two_phase_borrow(&self) -> bool {
493 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
494 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
499 ///////////////////////////////////////////////////////////////////////////
500 // Variables and temps
502 rustc_index::newtype_index! {
505 DEBUG_FORMAT = "_{}",
506 const RETURN_PLACE = 0,
510 impl Atom for Local {
511 fn index(self) -> usize {
516 /// Classifies locals into categories. See `Body::local_kind`.
517 #[derive(PartialEq, Eq, Debug, HashStable)]
519 /// User-declared variable binding.
521 /// Compiler-introduced temporary.
523 /// Function argument.
525 /// Location of function's return value.
529 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
530 pub struct VarBindingForm<'tcx> {
531 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
532 pub binding_mode: ty::BindingMode,
533 /// If an explicit type was provided for this variable binding,
534 /// this holds the source Span of that type.
536 /// NOTE: if you want to change this to a `HirId`, be wary that
537 /// doing so breaks incremental compilation (as of this writing),
538 /// while a `Span` does not cause our tests to fail.
539 pub opt_ty_info: Option<Span>,
540 /// Place of the RHS of the =, or the subject of the `match` where this
541 /// variable is initialized. None in the case of `let PATTERN;`.
542 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
543 /// (a) the right-hand side isn't evaluated as a place expression.
544 /// (b) it gives a way to separate this case from the remaining cases
546 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
547 /// The span of the pattern in which this variable was bound.
551 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
552 pub enum BindingForm<'tcx> {
553 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
554 Var(VarBindingForm<'tcx>),
555 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
556 ImplicitSelf(ImplicitSelfKind),
557 /// Reference used in a guard expression to ensure immutability.
561 /// Represents what type of implicit self a function has, if any.
562 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
563 pub enum ImplicitSelfKind {
564 /// Represents a `fn x(self);`.
566 /// Represents a `fn x(mut self);`.
568 /// Represents a `fn x(&self);`.
570 /// Represents a `fn x(&mut self);`.
572 /// Represents when a function does not have a self argument or
573 /// when a function has a `self: X` argument.
577 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
579 mod binding_form_impl {
580 use crate::ich::StableHashingContext;
581 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
583 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
584 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
585 use super::BindingForm::*;
586 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
589 Var(binding) => binding.hash_stable(hcx, hasher),
590 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
597 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
598 /// created during evaluation of expressions in a block tail
599 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
601 /// It is used to improve diagnostics when such temporaries are
602 /// involved in borrow_check errors, e.g., explanations of where the
603 /// temporaries come from, when their destructors are run, and/or how
604 /// one might revise the code to satisfy the borrow checker's rules.
605 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
606 pub struct BlockTailInfo {
607 /// If `true`, then the value resulting from evaluating this tail
608 /// expression is ignored by the block's expression context.
610 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
611 /// but not e.g., `let _x = { ...; tail };`
612 pub tail_result_is_ignored: bool,
617 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
618 /// argument, or the return place.
619 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
620 pub struct LocalDecl<'tcx> {
621 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
623 /// Temporaries and the return place are always mutable.
624 pub mutability: Mutability,
626 // FIXME(matthewjasper) Don't store in this in `Body`
627 pub local_info: LocalInfo<'tcx>,
629 /// `true` if this is an internal local.
631 /// These locals are not based on types in the source code and are only used
632 /// for a few desugarings at the moment.
634 /// The generator transformation will sanity check the locals which are live
635 /// across a suspension point against the type components of the generator
636 /// which type checking knows are live across a suspension point. We need to
637 /// flag drop flags to avoid triggering this check as they are introduced
640 /// Unsafety checking will also ignore dereferences of these locals,
641 /// so they can be used for raw pointers only used in a desugaring.
643 /// This should be sound because the drop flags are fully algebraic, and
644 /// therefore don't affect the OIBIT or outlives properties of the
648 /// If this local is a temporary and `is_block_tail` is `Some`,
649 /// then it is a temporary created for evaluation of some
650 /// subexpression of some block's tail expression (with no
651 /// intervening statement context).
652 // FIXME(matthewjasper) Don't store in this in `Body`
653 pub is_block_tail: Option<BlockTailInfo>,
655 /// The type of this local.
658 /// If the user manually ascribed a type to this variable,
659 /// e.g., via `let x: T`, then we carry that type here. The MIR
660 /// borrow checker needs this information since it can affect
661 /// region inference.
662 // FIXME(matthewjasper) Don't store in this in `Body`
663 pub user_ty: UserTypeProjections,
665 /// The *syntactic* (i.e., not visibility) source scope the local is defined
666 /// in. If the local was defined in a let-statement, this
667 /// is *within* the let-statement, rather than outside
670 /// This is needed because the visibility source scope of locals within
671 /// a let-statement is weird.
673 /// The reason is that we want the local to be *within* the let-statement
674 /// for lint purposes, but we want the local to be *after* the let-statement
675 /// for names-in-scope purposes.
677 /// That's it, if we have a let-statement like the one in this
681 /// fn foo(x: &str) {
682 /// #[allow(unused_mut)]
683 /// let mut x: u32 = { // <- one unused mut
684 /// let mut y: u32 = x.parse().unwrap();
691 /// Then, from a lint point of view, the declaration of `x: u32`
692 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
693 /// lint scopes are the same as the AST/HIR nesting.
695 /// However, from a name lookup point of view, the scopes look more like
696 /// as if the let-statements were `match` expressions:
699 /// fn foo(x: &str) {
701 /// match x.parse().unwrap() {
710 /// We care about the name-lookup scopes for debuginfo - if the
711 /// debuginfo instruction pointer is at the call to `x.parse()`, we
712 /// want `x` to refer to `x: &str`, but if it is at the call to
713 /// `drop(x)`, we want it to refer to `x: u32`.
715 /// To allow both uses to work, we need to have more than a single scope
716 /// for a local. We have the `source_info.scope` represent the "syntactic"
717 /// lint scope (with a variable being under its let block) while the
718 /// `var_debug_info.source_info.scope` represents the "local variable"
719 /// scope (where the "rest" of a block is under all prior let-statements).
721 /// The end result looks like this:
725 /// │{ argument x: &str }
727 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
728 /// │ │ // in practice because I'm lazy.
730 /// │ │← x.source_info.scope
731 /// │ │← `x.parse().unwrap()`
733 /// │ │ │← y.source_info.scope
735 /// │ │ │{ let y: u32 }
737 /// │ │ │← y.var_debug_info.source_info.scope
740 /// │ │{ let x: u32 }
741 /// │ │← x.var_debug_info.source_info.scope
742 /// │ │← `drop(x)` // This accesses `x: u32`.
744 pub source_info: SourceInfo,
747 /// Extra information about a local that's used for diagnostics.
748 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
749 pub enum LocalInfo<'tcx> {
750 /// A user-defined local variable or function parameter
752 /// The `BindingForm` is solely used for local diagnostics when generating
753 /// warnings/errors when compiling the current crate, and therefore it need
754 /// not be visible across crates.
755 User(ClearCrossCrate<BindingForm<'tcx>>),
756 /// A temporary created that references the static with the given `DefId`.
757 StaticRef { def_id: DefId, is_thread_local: bool },
758 /// Any other temporary, the return place, or an anonymous function parameter.
762 impl<'tcx> LocalDecl<'tcx> {
763 /// Returns `true` only if local is a binding that can itself be
764 /// made mutable via the addition of the `mut` keyword, namely
765 /// something like the occurrences of `x` in:
766 /// - `fn foo(x: Type) { ... }`,
768 /// - or `match ... { C(x) => ... }`
769 pub fn can_be_made_mutable(&self) -> bool {
770 match self.local_info {
771 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
772 binding_mode: ty::BindingMode::BindByValue(_),
778 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
779 ImplicitSelfKind::Imm,
786 /// Returns `true` if local is definitely not a `ref ident` or
787 /// `ref mut ident` binding. (Such bindings cannot be made into
788 /// mutable bindings, but the inverse does not necessarily hold).
789 pub fn is_nonref_binding(&self) -> bool {
790 match self.local_info {
791 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
792 binding_mode: ty::BindingMode::BindByValue(_),
798 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
804 /// Returns `true` if this variable is a named variable or function
805 /// parameter declared by the user.
807 pub fn is_user_variable(&self) -> bool {
808 match self.local_info {
809 LocalInfo::User(_) => true,
814 /// Returns `true` if this is a reference to a variable bound in a `match`
815 /// expression that is used to access said variable for the guard of the
817 pub fn is_ref_for_guard(&self) -> bool {
818 match self.local_info {
819 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
824 /// Returns `Some` if this is a reference to a static item that is used to
825 /// access that static
826 pub fn is_ref_to_static(&self) -> bool {
827 match self.local_info {
828 LocalInfo::StaticRef { .. } => true,
833 /// Returns `Some` if this is a reference to a static item that is used to
834 /// access that static
835 pub fn is_ref_to_thread_local(&self) -> bool {
836 match self.local_info {
837 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
842 /// Returns `true` is the local is from a compiler desugaring, e.g.,
843 /// `__next` from a `for` loop.
845 pub fn from_compiler_desugaring(&self) -> bool {
846 self.source_info.span.desugaring_kind().is_some()
849 /// Creates a new `LocalDecl` for a temporary.
851 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
852 Self::new_local(ty, Mutability::Mut, false, span)
855 /// Converts `self` into same `LocalDecl` except tagged as immutable.
857 pub fn immutable(mut self) -> Self {
858 self.mutability = Mutability::Not;
862 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
864 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
865 assert!(self.is_block_tail.is_none());
866 self.is_block_tail = Some(info);
870 /// Creates a new `LocalDecl` for a internal temporary.
872 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
873 Self::new_local(ty, Mutability::Mut, true, span)
877 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
881 user_ty: UserTypeProjections::none(),
882 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
884 local_info: LocalInfo::Other,
889 /// Builds a `LocalDecl` for the return place.
891 /// This must be inserted into the `local_decls` list as the first local.
893 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
895 mutability: Mutability::Mut,
897 user_ty: UserTypeProjections::none(),
898 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
901 local_info: LocalInfo::Other,
906 /// Debug information pertaining to a user variable.
907 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
908 pub struct VarDebugInfo<'tcx> {
911 /// Source info of the user variable, including the scope
912 /// within which the variable is visible (to debuginfo)
913 /// (see `LocalDecl`'s `source_info` field for more details).
914 pub source_info: SourceInfo,
916 /// Where the data for this user variable is to be found.
917 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
918 /// based on a `Local`, not a `Static`, and contains no indexing.
919 pub place: Place<'tcx>,
922 ///////////////////////////////////////////////////////////////////////////
925 rustc_index::newtype_index! {
926 pub struct BasicBlock {
928 DEBUG_FORMAT = "bb{}",
929 const START_BLOCK = 0,
934 pub fn start_location(self) -> Location {
935 Location { block: self, statement_index: 0 }
939 ///////////////////////////////////////////////////////////////////////////
940 // BasicBlockData and Terminator
942 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
943 pub struct BasicBlockData<'tcx> {
944 /// List of statements in this block.
945 pub statements: Vec<Statement<'tcx>>,
947 /// Terminator for this block.
949 /// N.B., this should generally ONLY be `None` during construction.
950 /// Therefore, you should generally access it via the
951 /// `terminator()` or `terminator_mut()` methods. The only
952 /// exception is that certain passes, such as `simplify_cfg`, swap
953 /// out the terminator temporarily with `None` while they continue
954 /// to recurse over the set of basic blocks.
955 pub terminator: Option<Terminator<'tcx>>,
957 /// If true, this block lies on an unwind path. This is used
958 /// during codegen where distinct kinds of basic blocks may be
959 /// generated (particularly for MSVC cleanup). Unwind blocks must
960 /// only branch to other unwind blocks.
961 pub is_cleanup: bool,
964 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
965 pub struct Terminator<'tcx> {
966 pub source_info: SourceInfo,
967 pub kind: TerminatorKind<'tcx>,
970 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
971 pub enum TerminatorKind<'tcx> {
972 /// Block should have one successor in the graph; we jump there.
973 Goto { target: BasicBlock },
975 /// Operand evaluates to an integer; jump depending on its value
976 /// to one of the targets, and otherwise fallback to `otherwise`.
978 /// The discriminant value being tested.
979 discr: Operand<'tcx>,
981 /// The type of value being tested.
984 /// Possible values. The locations to branch to in each case
985 /// are found in the corresponding indices from the `targets` vector.
986 values: Cow<'tcx, [u128]>,
988 /// Possible branch sites. The last element of this vector is used
989 /// for the otherwise branch, so targets.len() == values.len() + 1
992 // This invariant is quite non-obvious and also could be improved.
993 // One way to make this invariant is to have something like this instead:
995 // branches: Vec<(ConstInt, BasicBlock)>,
996 // otherwise: Option<BasicBlock> // exhaustive if None
998 // However we’ve decided to keep this as-is until we figure a case
999 // where some other approach seems to be strictly better than other.
1000 targets: Vec<BasicBlock>,
1003 /// Indicates that the landing pad is finished and unwinding should
1004 /// continue. Emitted by `build::scope::diverge_cleanup`.
1007 /// Indicates that the landing pad is finished and that the process
1008 /// should abort. Used to prevent unwinding for foreign items.
1011 /// Indicates a normal return. The return place should have
1012 /// been filled in by now. This should occur at most once.
1015 /// Indicates a terminator that can never be reached.
1018 /// Drop the `Place`.
1019 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1021 /// Drop the `Place` and assign the new value over it. This ensures
1022 /// that the assignment to `P` occurs *even if* the destructor for
1023 /// place unwinds. Its semantics are best explained by the
1028 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1036 /// Drop(P, goto BB1, unwind BB2)
1039 /// // P is now uninitialized
1043 /// // P is now uninitialized -- its dtor panicked
1048 location: Place<'tcx>,
1049 value: Operand<'tcx>,
1051 unwind: Option<BasicBlock>,
1054 /// Block ends with a call of a converging function.
1056 /// The function that’s being called.
1057 func: Operand<'tcx>,
1058 /// Arguments the function is called with.
1059 /// These are owned by the callee, which is free to modify them.
1060 /// This allows the memory occupied by "by-value" arguments to be
1061 /// reused across function calls without duplicating the contents.
1062 args: Vec<Operand<'tcx>>,
1063 /// Destination for the return value. If some, the call is converging.
1064 destination: Option<(Place<'tcx>, BasicBlock)>,
1065 /// Cleanups to be done if the call unwinds.
1066 cleanup: Option<BasicBlock>,
1067 /// `true` if this is from a call in HIR rather than from an overloaded
1068 /// operator. True for overloaded function call.
1069 from_hir_call: bool,
1072 /// Jump to the target if the condition has the expected value,
1073 /// otherwise panic with a message and a cleanup target.
1075 cond: Operand<'tcx>,
1077 msg: AssertMessage<'tcx>,
1079 cleanup: Option<BasicBlock>,
1082 /// A suspend point.
1084 /// The value to return.
1085 value: Operand<'tcx>,
1086 /// Where to resume to.
1088 /// Cleanup to be done if the generator is dropped at this suspend point.
1089 drop: Option<BasicBlock>,
1092 /// Indicates the end of the dropping of a generator.
1095 /// A block where control flow only ever takes one real path, but borrowck
1096 /// needs to be more conservative.
1098 /// The target normal control flow will take.
1099 real_target: BasicBlock,
1100 /// A block control flow could conceptually jump to, but won't in
1102 imaginary_target: BasicBlock,
1104 /// A terminator for blocks that only take one path in reality, but where we
1105 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1106 /// This can arise in infinite loops with no function calls for example.
1108 /// The target normal control flow will take.
1109 real_target: BasicBlock,
1110 /// The imaginary cleanup block link. This particular path will never be taken
1111 /// in practice, but in order to avoid fragility we want to always
1112 /// consider it in borrowck. We don't want to accept programs which
1113 /// pass borrowck only when `panic=abort` or some assertions are disabled
1114 /// due to release vs. debug mode builds. This needs to be an `Option` because
1115 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1116 unwind: Option<BasicBlock>,
1120 pub type Successors<'a> =
1121 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1122 pub type SuccessorsMut<'a> =
1123 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1125 impl<'tcx> Terminator<'tcx> {
1126 pub fn successors(&self) -> Successors<'_> {
1127 self.kind.successors()
1130 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1131 self.kind.successors_mut()
1134 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1138 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1139 self.kind.unwind_mut()
1143 impl<'tcx> TerminatorKind<'tcx> {
1146 cond: Operand<'tcx>,
1149 ) -> TerminatorKind<'tcx> {
1150 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1151 TerminatorKind::SwitchInt {
1153 switch_ty: tcx.types.bool,
1154 values: From::from(BOOL_SWITCH_FALSE),
1155 targets: vec![f, t],
1159 pub fn successors(&self) -> Successors<'_> {
1160 use self::TerminatorKind::*;
1167 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1168 Goto { target: ref t }
1169 | Call { destination: None, cleanup: Some(ref t), .. }
1170 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1171 | Yield { resume: ref t, drop: None, .. }
1172 | DropAndReplace { target: ref t, unwind: None, .. }
1173 | Drop { target: ref t, unwind: None, .. }
1174 | Assert { target: ref t, cleanup: None, .. }
1175 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1176 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1177 | Yield { resume: ref t, drop: Some(ref u), .. }
1178 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1179 | Drop { target: ref t, unwind: Some(ref u), .. }
1180 | Assert { target: ref t, cleanup: Some(ref u), .. }
1181 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1182 Some(t).into_iter().chain(slice::from_ref(u))
1184 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1185 FalseEdges { ref real_target, ref imaginary_target } => {
1186 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1191 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1192 use self::TerminatorKind::*;
1199 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1200 Goto { target: ref mut t }
1201 | Call { destination: None, cleanup: Some(ref mut t), .. }
1202 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1203 | Yield { resume: ref mut t, drop: None, .. }
1204 | DropAndReplace { target: ref mut t, unwind: None, .. }
1205 | Drop { target: ref mut t, unwind: None, .. }
1206 | Assert { target: ref mut t, cleanup: None, .. }
1207 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1208 Some(t).into_iter().chain(&mut [])
1210 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1211 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1212 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1213 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1214 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1215 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1216 Some(t).into_iter().chain(slice::from_mut(u))
1218 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1219 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1220 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1225 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1227 TerminatorKind::Goto { .. }
1228 | TerminatorKind::Resume
1229 | TerminatorKind::Abort
1230 | TerminatorKind::Return
1231 | TerminatorKind::Unreachable
1232 | TerminatorKind::GeneratorDrop
1233 | TerminatorKind::Yield { .. }
1234 | TerminatorKind::SwitchInt { .. }
1235 | TerminatorKind::FalseEdges { .. } => None,
1236 TerminatorKind::Call { cleanup: ref unwind, .. }
1237 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1238 | TerminatorKind::DropAndReplace { ref unwind, .. }
1239 | TerminatorKind::Drop { ref unwind, .. }
1240 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1244 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1246 TerminatorKind::Goto { .. }
1247 | TerminatorKind::Resume
1248 | TerminatorKind::Abort
1249 | TerminatorKind::Return
1250 | TerminatorKind::Unreachable
1251 | TerminatorKind::GeneratorDrop
1252 | TerminatorKind::Yield { .. }
1253 | TerminatorKind::SwitchInt { .. }
1254 | TerminatorKind::FalseEdges { .. } => None,
1255 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1256 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1257 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1258 | TerminatorKind::Drop { ref mut unwind, .. }
1259 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1264 impl<'tcx> BasicBlockData<'tcx> {
1265 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1266 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1269 /// Accessor for terminator.
1271 /// Terminator may not be None after construction of the basic block is complete. This accessor
1272 /// provides a convenience way to reach the terminator.
1273 pub fn terminator(&self) -> &Terminator<'tcx> {
1274 self.terminator.as_ref().expect("invalid terminator state")
1277 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1278 self.terminator.as_mut().expect("invalid terminator state")
1281 pub fn retain_statements<F>(&mut self, mut f: F)
1283 F: FnMut(&mut Statement<'_>) -> bool,
1285 for s in &mut self.statements {
1292 pub fn expand_statements<F, I>(&mut self, mut f: F)
1294 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1295 I: iter::TrustedLen<Item = Statement<'tcx>>,
1297 // Gather all the iterators we'll need to splice in, and their positions.
1298 let mut splices: Vec<(usize, I)> = vec![];
1299 let mut extra_stmts = 0;
1300 for (i, s) in self.statements.iter_mut().enumerate() {
1301 if let Some(mut new_stmts) = f(s) {
1302 if let Some(first) = new_stmts.next() {
1303 // We can already store the first new statement.
1306 // Save the other statements for optimized splicing.
1307 let remaining = new_stmts.size_hint().0;
1309 splices.push((i + 1 + extra_stmts, new_stmts));
1310 extra_stmts += remaining;
1318 // Splice in the new statements, from the end of the block.
1319 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1320 // where a range of elements ("gap") is left uninitialized, with
1321 // splicing adding new elements to the end of that gap and moving
1322 // existing elements from before the gap to the end of the gap.
1323 // For now, this is safe code, emulating a gap but initializing it.
1324 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1325 self.statements.resize(
1328 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1329 kind: StatementKind::Nop,
1332 for (splice_start, new_stmts) in splices.into_iter().rev() {
1333 let splice_end = splice_start + new_stmts.size_hint().0;
1334 while gap.end > splice_end {
1337 self.statements.swap(gap.start, gap.end);
1339 self.statements.splice(splice_start..splice_end, new_stmts);
1340 gap.end = splice_start;
1344 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1345 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1349 impl<'tcx> Debug for TerminatorKind<'tcx> {
1350 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1351 self.fmt_head(fmt)?;
1352 let successor_count = self.successors().count();
1353 let labels = self.fmt_successor_labels();
1354 assert_eq!(successor_count, labels.len());
1356 match successor_count {
1359 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1362 write!(fmt, " -> [")?;
1363 for (i, target) in self.successors().enumerate() {
1367 write!(fmt, "{}: {:?}", labels[i], target)?;
1375 impl<'tcx> TerminatorKind<'tcx> {
1376 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1377 /// successor basic block, if any. The only information not included is the list of possible
1378 /// successors, which may be rendered differently between the text and the graphviz format.
1379 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1380 use self::TerminatorKind::*;
1382 Goto { .. } => write!(fmt, "goto"),
1383 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1384 Return => write!(fmt, "return"),
1385 GeneratorDrop => write!(fmt, "generator_drop"),
1386 Resume => write!(fmt, "resume"),
1387 Abort => write!(fmt, "abort"),
1388 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1389 Unreachable => write!(fmt, "unreachable"),
1390 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1391 DropAndReplace { ref location, ref value, .. } => {
1392 write!(fmt, "replace({:?} <- {:?})", location, value)
1394 Call { ref func, ref args, ref destination, .. } => {
1395 if let Some((ref destination, _)) = *destination {
1396 write!(fmt, "{:?} = ", destination)?;
1398 write!(fmt, "{:?}(", func)?;
1399 for (index, arg) in args.iter().enumerate() {
1403 write!(fmt, "{:?}", arg)?;
1407 Assert { ref cond, expected, ref msg, .. } => {
1408 write!(fmt, "assert(")?;
1412 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1414 FalseEdges { .. } => write!(fmt, "falseEdges"),
1415 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1419 /// Returns the list of labels for the edges to the successor basic blocks.
1420 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1421 use self::TerminatorKind::*;
1423 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1424 Goto { .. } => vec!["".into()],
1425 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1426 let param_env = ty::ParamEnv::empty();
1427 let switch_ty = tcx.lift(&switch_ty).unwrap();
1428 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1432 ty::Const::from_scalar(tcx, Scalar::from_uint(u, size).into(), switch_ty)
1436 .chain(iter::once("otherwise".into()))
1439 Call { destination: Some(_), cleanup: Some(_), .. } => {
1440 vec!["return".into(), "unwind".into()]
1442 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1443 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1444 Call { destination: None, cleanup: None, .. } => vec![],
1445 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1446 Yield { drop: None, .. } => vec!["resume".into()],
1447 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1448 vec!["return".into()]
1450 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1451 vec!["return".into(), "unwind".into()]
1453 Assert { cleanup: None, .. } => vec!["".into()],
1454 Assert { .. } => vec!["success".into(), "unwind".into()],
1455 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1456 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1457 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1462 ///////////////////////////////////////////////////////////////////////////
1465 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1466 pub struct Statement<'tcx> {
1467 pub source_info: SourceInfo,
1468 pub kind: StatementKind<'tcx>,
1471 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1472 #[cfg(target_arch = "x86_64")]
1473 static_assert_size!(Statement<'_>, 32);
1475 impl Statement<'_> {
1476 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1477 /// invalidating statement indices in `Location`s.
1478 pub fn make_nop(&mut self) {
1479 self.kind = StatementKind::Nop
1482 /// Changes a statement to a nop and returns the original statement.
1483 pub fn replace_nop(&mut self) -> Self {
1485 source_info: self.source_info,
1486 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1491 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1492 pub enum StatementKind<'tcx> {
1493 /// Write the RHS Rvalue to the LHS Place.
1494 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1496 /// This represents all the reading that a pattern match may do
1497 /// (e.g., inspecting constants and discriminant values), and the
1498 /// kind of pattern it comes from. This is in order to adapt potential
1499 /// error messages to these specific patterns.
1501 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1502 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1503 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1505 /// Write the discriminant for a variant to the enum Place.
1506 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1508 /// Start a live range for the storage of the local.
1511 /// End the current live range for the storage of the local.
1514 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1515 /// of `StatementKind` low.
1516 InlineAsm(Box<InlineAsm<'tcx>>),
1518 /// Retag references in the given place, ensuring they got fresh tags. This is
1519 /// part of the Stacked Borrows model. These statements are currently only interpreted
1520 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1521 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1522 /// for more details.
1523 Retag(RetagKind, Box<Place<'tcx>>),
1525 /// Encodes a user's type ascription. These need to be preserved
1526 /// intact so that NLL can respect them. For example:
1530 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1531 /// to the user-given type `T`. The effect depends on the specified variance:
1533 /// - `Covariant` -- requires that `T_y <: T`
1534 /// - `Contravariant` -- requires that `T_y :> T`
1535 /// - `Invariant` -- requires that `T_y == T`
1536 /// - `Bivariant` -- no effect
1537 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1539 /// No-op. Useful for deleting instructions without affecting statement indices.
1543 /// Describes what kind of retag is to be performed.
1544 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1545 pub enum RetagKind {
1546 /// The initial retag when entering a function.
1548 /// Retag preparing for a two-phase borrow.
1550 /// Retagging raw pointers.
1552 /// A "normal" retag.
1556 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1557 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1558 pub enum FakeReadCause {
1559 /// Inject a fake read of the borrowed input at the end of each guards
1562 /// This should ensure that you cannot change the variant for an enum while
1563 /// you are in the midst of matching on it.
1566 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1567 /// generate a read of x to check that it is initialized and safe.
1570 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1571 /// in a match guard to ensure that it's value hasn't change by the time
1572 /// we create the OutsideGuard version.
1575 /// Officially, the semantics of
1577 /// `let pattern = <expr>;`
1579 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1580 /// into the pattern.
1582 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1583 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1584 /// but in some cases it can affect the borrow checker, as in #53695.
1585 /// Therefore, we insert a "fake read" here to ensure that we get
1586 /// appropriate errors.
1589 /// If we have an index expression like
1591 /// (*x)[1][{ x = y; 4}]
1593 /// then the first bounds check is invalidated when we evaluate the second
1594 /// index expression. Thus we create a fake borrow of `x` across the second
1595 /// indexer, which will cause a borrow check error.
1599 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1600 pub struct InlineAsm<'tcx> {
1601 pub asm: hir::InlineAsmInner,
1602 pub outputs: Box<[Place<'tcx>]>,
1603 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1606 impl Debug for Statement<'_> {
1607 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1608 use self::StatementKind::*;
1610 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1611 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1612 Retag(ref kind, ref place) => write!(
1616 RetagKind::FnEntry => "[fn entry] ",
1617 RetagKind::TwoPhase => "[2phase] ",
1618 RetagKind::Raw => "[raw] ",
1619 RetagKind::Default => "",
1623 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1624 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1625 SetDiscriminant { ref place, variant_index } => {
1626 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1628 InlineAsm(ref asm) => {
1629 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1631 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1632 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1634 Nop => write!(fmt, "nop"),
1639 ///////////////////////////////////////////////////////////////////////////
1642 /// A path to a value; something that can be evaluated without
1643 /// changing or disturbing program state.
1644 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable)]
1645 pub struct Place<'tcx> {
1646 pub base: PlaceBase<'tcx>,
1648 /// projection out of a place (access a field, deref a pointer, etc)
1649 pub projection: &'tcx List<PlaceElem<'tcx>>,
1652 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1654 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1655 pub enum PlaceBase<'tcx> {
1659 /// static or static mut variable
1660 Static(Box<Static<'tcx>>),
1663 /// We store the normalized type to avoid requiring normalization when reading MIR
1676 pub struct Static<'tcx> {
1678 pub kind: StaticKind<'tcx>,
1679 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1680 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1681 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1682 /// into the calling frame.
1698 pub enum StaticKind<'tcx> {
1699 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1700 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1701 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1702 Promoted(Promoted, SubstsRef<'tcx>),
1706 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1707 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1708 pub enum ProjectionElem<V, T> {
1713 /// These indices are generated by slice patterns. Easiest to explain
1717 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1718 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1719 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1720 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1723 /// index or -index (in Python terms), depending on from_end
1725 /// The thing being indexed must be at least this long. For arrays this
1726 /// is always the exact length.
1728 /// Counting backwards from end? This is always false when indexing an
1733 /// These indices are generated by slice patterns.
1735 /// If `from_end` is true `slice[from..slice.len() - to]`.
1736 /// Otherwise `array[from..to]`.
1740 /// Whether `to` counts from the start or end of the array/slice.
1741 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1742 /// For `ProjectionKind`, this can also be `true` for arrays.
1746 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1747 /// this for ADTs with more than one variant. It may be better to
1748 /// just introduce it always, or always for enums.
1750 /// The included Symbol is the name of the variant, used for printing MIR.
1751 Downcast(Option<Symbol>, VariantIdx),
1754 impl<V, T> ProjectionElem<V, T> {
1755 /// Returns `true` if the target of this projection may refer to a different region of memory
1757 fn is_indirect(&self) -> bool {
1759 Self::Deref => true,
1763 | Self::ConstantIndex { .. }
1764 | Self::Subslice { .. }
1765 | Self::Downcast(_, _) => false,
1770 /// Alias for projections as they appear in places, where the base is a place
1771 /// and the index is a local.
1772 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1774 impl<'tcx> Copy for PlaceElem<'tcx> {}
1776 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1777 #[cfg(target_arch = "x86_64")]
1778 static_assert_size!(PlaceElem<'_>, 16);
1780 /// Alias for projections as they appear in `UserTypeProjection`, where we
1781 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1782 pub type ProjectionKind = ProjectionElem<(), ()>;
1784 rustc_index::newtype_index! {
1787 DEBUG_FORMAT = "field[{}]"
1791 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1792 pub struct PlaceRef<'a, 'tcx> {
1793 pub base: &'a PlaceBase<'tcx>,
1794 pub projection: &'a [PlaceElem<'tcx>],
1797 impl<'tcx> Place<'tcx> {
1798 // FIXME change this to a const fn by also making List::empty a const fn.
1799 pub fn return_place() -> Place<'tcx> {
1800 Place { base: PlaceBase::Local(RETURN_PLACE), projection: List::empty() }
1803 /// Returns `true` if this `Place` contains a `Deref` projection.
1805 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1806 /// same region of memory as its base.
1807 pub fn is_indirect(&self) -> bool {
1808 self.projection.iter().any(|elem| elem.is_indirect())
1811 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1812 /// a single deref of a local.
1814 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1815 pub fn local_or_deref_local(&self) -> Option<Local> {
1816 match self.as_ref() {
1817 PlaceRef { base: &PlaceBase::Local(local), projection: &[] }
1818 | PlaceRef { base: &PlaceBase::Local(local), projection: &[ProjectionElem::Deref] } => {
1825 /// If this place represents a local variable like `_X` with no
1826 /// projections, return `Some(_X)`.
1827 pub fn as_local(&self) -> Option<Local> {
1828 self.as_ref().as_local()
1831 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1832 PlaceRef { base: &self.base, projection: &self.projection }
1836 impl From<Local> for Place<'_> {
1837 fn from(local: Local) -> Self {
1838 Place { base: local.into(), projection: List::empty() }
1842 impl From<Local> for PlaceBase<'_> {
1843 fn from(local: Local) -> Self {
1844 PlaceBase::Local(local)
1848 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1849 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1850 /// a single deref of a local.
1852 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1853 pub fn local_or_deref_local(&self) -> Option<Local> {
1855 PlaceRef { base: PlaceBase::Local(local), projection: [] }
1856 | PlaceRef { base: PlaceBase::Local(local), projection: [ProjectionElem::Deref] } => {
1863 /// If this place represents a local variable like `_X` with no
1864 /// projections, return `Some(_X)`.
1865 pub fn as_local(&self) -> Option<Local> {
1867 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1873 impl Debug for Place<'_> {
1874 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1875 for elem in self.projection.iter().rev() {
1877 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1878 write!(fmt, "(").unwrap();
1880 ProjectionElem::Deref => {
1881 write!(fmt, "(*").unwrap();
1883 ProjectionElem::Index(_)
1884 | ProjectionElem::ConstantIndex { .. }
1885 | ProjectionElem::Subslice { .. } => {}
1889 write!(fmt, "{:?}", self.base)?;
1891 for elem in self.projection.iter() {
1893 ProjectionElem::Downcast(Some(name), _index) => {
1894 write!(fmt, " as {})", name)?;
1896 ProjectionElem::Downcast(None, index) => {
1897 write!(fmt, " as variant#{:?})", index)?;
1899 ProjectionElem::Deref => {
1902 ProjectionElem::Field(field, ty) => {
1903 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1905 ProjectionElem::Index(ref index) => {
1906 write!(fmt, "[{:?}]", index)?;
1908 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1909 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1911 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1912 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1914 ProjectionElem::Subslice { from, to, from_end: true } if *to == 0 => {
1915 write!(fmt, "[{:?}:]", from)?;
1917 ProjectionElem::Subslice { from, to, from_end: true } if *from == 0 => {
1918 write!(fmt, "[:-{:?}]", to)?;
1920 ProjectionElem::Subslice { from, to, from_end: true } => {
1921 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1923 ProjectionElem::Subslice { from, to, from_end: false } => {
1924 write!(fmt, "[{:?}..{:?}]", from, to)?;
1933 impl Debug for PlaceBase<'_> {
1934 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1936 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
1937 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
1938 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
1940 PlaceBase::Static(box self::Static {
1942 kind: StaticKind::Promoted(promoted, _),
1944 }) => write!(fmt, "({:?}: {:?})", promoted, ty),
1949 ///////////////////////////////////////////////////////////////////////////
1952 rustc_index::newtype_index! {
1953 pub struct SourceScope {
1955 DEBUG_FORMAT = "scope[{}]",
1956 const OUTERMOST_SOURCE_SCOPE = 0,
1960 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1961 pub struct SourceScopeData {
1963 pub parent_scope: Option<SourceScope>,
1965 /// Crate-local information for this source scope, that can't (and
1966 /// needn't) be tracked across crates.
1967 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1970 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1971 pub struct SourceScopeLocalData {
1972 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1973 pub lint_root: hir::HirId,
1974 /// The unsafe block that contains this node.
1978 ///////////////////////////////////////////////////////////////////////////
1981 /// These are values that can appear inside an rvalue. They are intentionally
1982 /// limited to prevent rvalues from being nested in one another.
1983 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
1984 pub enum Operand<'tcx> {
1985 /// Copy: The value must be available for use afterwards.
1987 /// This implies that the type of the place must be `Copy`; this is true
1988 /// by construction during build, but also checked by the MIR type checker.
1991 /// Move: The value (including old borrows of it) will not be used again.
1993 /// Safe for values of all types (modulo future developments towards `?Move`).
1994 /// Correct usage patterns are enforced by the borrow checker for safe code.
1995 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1998 /// Synthesizes a constant value.
1999 Constant(Box<Constant<'tcx>>),
2002 impl<'tcx> Debug for Operand<'tcx> {
2003 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2004 use self::Operand::*;
2006 Constant(ref a) => write!(fmt, "{:?}", a),
2007 Copy(ref place) => write!(fmt, "{:?}", place),
2008 Move(ref place) => write!(fmt, "move {:?}", place),
2013 impl<'tcx> Operand<'tcx> {
2014 /// Convenience helper to make a constant that refers to the fn
2015 /// with given `DefId` and substs. Since this is used to synthesize
2016 /// MIR, assumes `user_ty` is None.
2017 pub fn function_handle(
2020 substs: SubstsRef<'tcx>,
2023 let ty = tcx.type_of(def_id).subst(tcx, substs);
2024 Operand::Constant(box Constant {
2027 literal: ty::Const::zero_sized(tcx, ty),
2031 pub fn to_copy(&self) -> Self {
2033 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2034 Operand::Move(ref place) => Operand::Copy(place.clone()),
2039 ///////////////////////////////////////////////////////////////////////////
2042 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2043 pub enum Rvalue<'tcx> {
2044 /// x (either a move or copy, depending on type of x)
2048 Repeat(Operand<'tcx>, u64),
2051 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2053 /// Create a raw pointer to the given place
2054 /// Can be generated by raw address of expressions (`&raw const x`),
2055 /// or when casting a reference to a raw pointer.
2056 AddressOf(Mutability, Place<'tcx>),
2058 /// length of a [X] or [X;n] value
2061 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2063 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2064 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2066 NullaryOp(NullOp, Ty<'tcx>),
2067 UnaryOp(UnOp, Operand<'tcx>),
2069 /// Read the discriminant of an ADT.
2071 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2072 /// be defined to return, say, a 0) if ADT is not an enum.
2073 Discriminant(Place<'tcx>),
2075 /// Creates an aggregate value, like a tuple or struct. This is
2076 /// only needed because we want to distinguish `dest = Foo { x:
2077 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2078 /// that `Foo` has a destructor. These rvalues can be optimized
2079 /// away after type-checking and before lowering.
2080 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2083 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2086 Pointer(PointerCast),
2089 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2090 pub enum AggregateKind<'tcx> {
2091 /// The type is of the element
2095 /// The second field is the variant index. It's equal to 0 for struct
2096 /// and union expressions. The fourth field is
2097 /// active field number and is present only for union expressions
2098 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2099 /// active field index would identity the field `c`
2100 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2102 Closure(DefId, SubstsRef<'tcx>),
2103 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2106 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2108 /// The `+` operator (addition)
2110 /// The `-` operator (subtraction)
2112 /// The `*` operator (multiplication)
2114 /// The `/` operator (division)
2116 /// The `%` operator (modulus)
2118 /// The `^` operator (bitwise xor)
2120 /// The `&` operator (bitwise and)
2122 /// The `|` operator (bitwise or)
2124 /// The `<<` operator (shift left)
2126 /// The `>>` operator (shift right)
2128 /// The `==` operator (equality)
2130 /// The `<` operator (less than)
2132 /// The `<=` operator (less than or equal to)
2134 /// The `!=` operator (not equal to)
2136 /// The `>=` operator (greater than or equal to)
2138 /// The `>` operator (greater than)
2140 /// The `ptr.offset` operator
2145 pub fn is_checkable(self) -> bool {
2148 Add | Sub | Mul | Shl | Shr => true,
2154 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2156 /// Returns the size of a value of that type
2158 /// Creates a new uninitialized box for a value of that type
2162 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2164 /// The `!` operator for logical inversion
2166 /// The `-` operator for negation
2170 impl<'tcx> Debug for Rvalue<'tcx> {
2171 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2172 use self::Rvalue::*;
2175 Use(ref place) => write!(fmt, "{:?}", place),
2176 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2177 Len(ref a) => write!(fmt, "Len({:?})", a),
2178 Cast(ref kind, ref place, ref ty) => {
2179 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2181 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2182 CheckedBinaryOp(ref op, ref a, ref b) => {
2183 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2185 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2186 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2187 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2188 Ref(region, borrow_kind, ref place) => {
2189 let kind_str = match borrow_kind {
2190 BorrowKind::Shared => "",
2191 BorrowKind::Shallow => "shallow ",
2192 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2195 // When printing regions, add trailing space if necessary.
2196 let print_region = ty::tls::with(|tcx| {
2197 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2199 let region = if print_region {
2200 let mut region = region.to_string();
2201 if region.len() > 0 {
2206 // Do not even print 'static
2209 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2212 AddressOf(mutability, ref place) => {
2213 let kind_str = match mutability {
2214 Mutability::Mut => "mut",
2215 Mutability::Not => "const",
2218 write!(fmt, "&raw {} {:?}", kind_str, place)
2221 Aggregate(ref kind, ref places) => {
2222 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2223 let mut tuple_fmt = fmt.debug_tuple("");
2224 for place in places {
2225 tuple_fmt.field(place);
2231 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2233 AggregateKind::Tuple => match places.len() {
2234 0 => write!(fmt, "()"),
2235 1 => write!(fmt, "({:?},)", places[0]),
2236 _ => fmt_tuple(fmt, places),
2239 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2240 let variant_def = &adt_def.variants[variant];
2243 ty::tls::with(|tcx| {
2244 let substs = tcx.lift(&substs).expect("could not lift for printing");
2245 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2246 .print_def_path(variant_def.def_id, substs)?;
2250 match variant_def.ctor_kind {
2251 CtorKind::Const => Ok(()),
2252 CtorKind::Fn => fmt_tuple(fmt, places),
2253 CtorKind::Fictive => {
2254 let mut struct_fmt = fmt.debug_struct("");
2255 for (field, place) in variant_def.fields.iter().zip(places) {
2256 struct_fmt.field(&field.ident.as_str(), place);
2263 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2264 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2265 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2266 let substs = tcx.lift(&substs).unwrap();
2269 tcx.def_path_str_with_substs(def_id, substs),
2272 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2274 let mut struct_fmt = fmt.debug_struct(&name);
2276 if let Some(upvars) = tcx.upvars(def_id) {
2277 for (&var_id, place) in upvars.keys().zip(places) {
2278 let var_name = tcx.hir().name(var_id);
2279 struct_fmt.field(&var_name.as_str(), place);
2285 write!(fmt, "[closure]")
2289 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2290 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2291 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2292 let mut struct_fmt = fmt.debug_struct(&name);
2294 if let Some(upvars) = tcx.upvars(def_id) {
2295 for (&var_id, place) in upvars.keys().zip(places) {
2296 let var_name = tcx.hir().name(var_id);
2297 struct_fmt.field(&var_name.as_str(), place);
2303 write!(fmt, "[generator]")
2312 ///////////////////////////////////////////////////////////////////////////
2315 /// Two constants are equal if they are the same constant. Note that
2316 /// this does not necessarily mean that they are "==" in Rust -- in
2317 /// particular one must be wary of `NaN`!
2319 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2320 pub struct Constant<'tcx> {
2323 /// Optional user-given type: for something like
2324 /// `collect::<Vec<_>>`, this would be present and would
2325 /// indicate that `Vec<_>` was explicitly specified.
2327 /// Needed for NLL to impose user-given type constraints.
2328 pub user_ty: Option<UserTypeAnnotationIndex>,
2330 pub literal: &'tcx ty::Const<'tcx>,
2333 impl Constant<'tcx> {
2334 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2335 match self.literal.val.try_to_scalar() {
2336 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2337 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2340 tcx.sess.delay_span_bug(DUMMY_SP, "MIR cannot contain dangling const pointers");
2349 /// A collection of projections into user types.
2351 /// They are projections because a binding can occur a part of a
2352 /// parent pattern that has been ascribed a type.
2354 /// Its a collection because there can be multiple type ascriptions on
2355 /// the path from the root of the pattern down to the binding itself.
2360 /// struct S<'a>((i32, &'a str), String);
2361 /// let S((_, w): (i32, &'static str), _): S = ...;
2362 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2363 /// // --------------------------------- ^ (2)
2366 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2367 /// ascribed the type `(i32, &'static str)`.
2369 /// The highlights labelled `(2)` show the whole pattern being
2370 /// ascribed the type `S`.
2372 /// In this example, when we descend to `w`, we will have built up the
2373 /// following two projected types:
2375 /// * base: `S`, projection: `(base.0).1`
2376 /// * base: `(i32, &'static str)`, projection: `base.1`
2378 /// The first will lead to the constraint `w: &'1 str` (for some
2379 /// inferred region `'1`). The second will lead to the constraint `w:
2381 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2382 pub struct UserTypeProjections {
2383 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2386 impl<'tcx> UserTypeProjections {
2387 pub fn none() -> Self {
2388 UserTypeProjections { contents: vec![] }
2391 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2392 UserTypeProjections { contents: projs.collect() }
2395 pub fn projections_and_spans(
2397 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2398 self.contents.iter()
2401 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2402 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2405 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2406 self.contents.push((user_ty.clone(), span));
2412 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2414 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2418 pub fn index(self) -> Self {
2419 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2422 pub fn subslice(self, from: u32, to: u32) -> Self {
2423 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2426 pub fn deref(self) -> Self {
2427 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2430 pub fn leaf(self, field: Field) -> Self {
2431 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2434 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2435 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2439 /// Encodes the effect of a user-supplied type annotation on the
2440 /// subcomponents of a pattern. The effect is determined by applying the
2441 /// given list of proejctions to some underlying base type. Often,
2442 /// the projection element list `projs` is empty, in which case this
2443 /// directly encodes a type in `base`. But in the case of complex patterns with
2444 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2445 /// in which case the `projs` vector is used.
2449 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2451 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2452 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2453 /// determined by finding the type of the `.0` field from `T`.
2454 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2455 pub struct UserTypeProjection {
2456 pub base: UserTypeAnnotationIndex,
2457 pub projs: Vec<ProjectionKind>,
2460 impl Copy for ProjectionKind {}
2462 impl UserTypeProjection {
2463 pub(crate) fn index(mut self) -> Self {
2464 self.projs.push(ProjectionElem::Index(()));
2468 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2469 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2473 pub(crate) fn deref(mut self) -> Self {
2474 self.projs.push(ProjectionElem::Deref);
2478 pub(crate) fn leaf(mut self, field: Field) -> Self {
2479 self.projs.push(ProjectionElem::Field(field, ()));
2483 pub(crate) fn variant(
2485 adt_def: &'tcx AdtDef,
2486 variant_index: VariantIdx,
2489 self.projs.push(ProjectionElem::Downcast(
2490 Some(adt_def.variants[variant_index].ident.name),
2493 self.projs.push(ProjectionElem::Field(field, ()));
2498 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2500 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2501 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2502 use crate::mir::ProjectionElem::*;
2504 let base = self.base.fold_with(folder);
2505 let projs: Vec<_> = self
2508 .map(|elem| match elem {
2510 Field(f, ()) => Field(f.clone(), ()),
2511 Index(()) => Index(()),
2512 elem => elem.clone(),
2516 UserTypeProjection { base, projs }
2519 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2520 self.base.visit_with(visitor)
2521 // Note: there's nothing in `self.proj` to visit.
2525 rustc_index::newtype_index! {
2526 pub struct Promoted {
2528 DEBUG_FORMAT = "promoted[{}]"
2532 impl<'tcx> Debug for Constant<'tcx> {
2533 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2534 write!(fmt, "{}", self)
2538 impl<'tcx> Display for Constant<'tcx> {
2539 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2540 write!(fmt, "const ")?;
2541 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2542 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2543 // detailed and just not '{pointer}'.
2544 if let ty::RawPtr(_) = self.literal.ty.kind {
2545 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2547 write!(fmt, "{}", self.literal)
2552 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2553 type Node = BasicBlock;
2556 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2557 fn num_nodes(&self) -> usize {
2558 self.basic_blocks.len()
2562 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2563 fn start_node(&self) -> Self::Node {
2568 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2569 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2570 self.basic_blocks[node].terminator().successors().cloned()
2574 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2575 type Item = BasicBlock;
2576 type Iter = iter::Cloned<Successors<'b>>;
2579 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2580 pub struct Location {
2581 /// The block that the location is within.
2582 pub block: BasicBlock,
2584 /// The location is the position of the start of the statement; or, if
2585 /// `statement_index` equals the number of statements, then the start of the
2587 pub statement_index: usize,
2590 impl fmt::Debug for Location {
2591 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2592 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2597 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2599 /// Returns the location immediately after this one within the enclosing block.
2601 /// Note that if this location represents a terminator, then the
2602 /// resulting location would be out of bounds and invalid.
2603 pub fn successor_within_block(&self) -> Location {
2604 Location { block: self.block, statement_index: self.statement_index + 1 }
2607 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2608 pub fn is_predecessor_of<'tcx>(
2611 body: ReadOnlyBodyAndCache<'_, 'tcx>,
2613 // If we are in the same block as the other location and are an earlier statement
2614 // then we are a predecessor of `other`.
2615 if self.block == other.block && self.statement_index < other.statement_index {
2619 // If we're in another block, then we want to check that block is a predecessor of `other`.
2620 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).to_vec();
2621 let mut visited = FxHashSet::default();
2623 while let Some(block) = queue.pop() {
2624 // If we haven't visited this block before, then make sure we visit it's predecessors.
2625 if visited.insert(block) {
2626 queue.extend(body.predecessors_for(block).iter().cloned());
2631 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2632 // we found that block by looking at the predecessors of `other`).
2633 if self.block == block {
2641 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2642 if self.block == other.block {
2643 self.statement_index <= other.statement_index
2645 dominators.is_dominated_by(other.block, self.block)
2650 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2651 pub enum UnsafetyViolationKind {
2653 /// Permitted both in `const fn`s and regular `fn`s.
2655 BorrowPacked(hir::HirId),
2658 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2659 pub struct UnsafetyViolation {
2660 pub source_info: SourceInfo,
2661 pub description: Symbol,
2662 pub details: Symbol,
2663 pub kind: UnsafetyViolationKind,
2666 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2667 pub struct UnsafetyCheckResult {
2668 /// Violations that are propagated *upwards* from this function.
2669 pub violations: Lrc<[UnsafetyViolation]>,
2670 /// `unsafe` blocks in this function, along with whether they are used. This is
2671 /// used for the "unused_unsafe" lint.
2672 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2675 rustc_index::newtype_index! {
2676 pub struct GeneratorSavedLocal {
2678 DEBUG_FORMAT = "_{}",
2682 /// The layout of generator state.
2683 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2684 pub struct GeneratorLayout<'tcx> {
2685 /// The type of every local stored inside the generator.
2686 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2688 /// Which of the above fields are in each variant. Note that one field may
2689 /// be stored in multiple variants.
2690 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2692 /// Which saved locals are storage-live at the same time. Locals that do not
2693 /// have conflicts with each other are allowed to overlap in the computed
2695 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2698 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2699 pub struct BorrowCheckResult<'tcx> {
2700 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2701 pub used_mut_upvars: SmallVec<[Field; 8]>,
2704 /// The result of the `mir_const_qualif` query.
2706 /// Each field corresponds to an implementer of the `Qualif` trait in
2707 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2709 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2710 pub struct ConstQualifs {
2711 pub has_mut_interior: bool,
2712 pub needs_drop: bool,
2715 /// After we borrow check a closure, we are left with various
2716 /// requirements that we have inferred between the free regions that
2717 /// appear in the closure's signature or on its field types. These
2718 /// requirements are then verified and proved by the closure's
2719 /// creating function. This struct encodes those requirements.
2721 /// The requirements are listed as being between various
2722 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2723 /// vids refer to the free regions that appear in the closure (or
2724 /// generator's) type, in order of appearance. (This numbering is
2725 /// actually defined by the `UniversalRegions` struct in the NLL
2726 /// region checker. See for example
2727 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2728 /// regions in the closure's type "as if" they were erased, so their
2729 /// precise identity is not important, only their position.
2731 /// Example: If type check produces a closure with the closure substs:
2734 /// ClosureSubsts = [
2735 /// i8, // the "closure kind"
2736 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2737 /// &'a String, // some upvar
2741 /// here, there is one unique free region (`'a`) but it appears
2742 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2745 /// ClosureSubsts = [
2746 /// i8, // the "closure kind"
2747 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2748 /// &'2 String, // some upvar
2752 /// Now the code might impose a requirement like `'1: '2`. When an
2753 /// instance of the closure is created, the corresponding free regions
2754 /// can be extracted from its type and constrained to have the given
2755 /// outlives relationship.
2757 /// In some cases, we have to record outlives requirements between
2758 /// types and regions as well. In that case, if those types include
2759 /// any regions, those regions are recorded as `ReClosureBound`
2760 /// instances assigned one of these same indices. Those regions will
2761 /// be substituted away by the creator. We use `ReClosureBound` in
2762 /// that case because the regions must be allocated in the global
2763 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2764 /// internally within the rest of the NLL code).
2765 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2766 pub struct ClosureRegionRequirements<'tcx> {
2767 /// The number of external regions defined on the closure. In our
2768 /// example above, it would be 3 -- one for `'static`, then `'1`
2769 /// and `'2`. This is just used for a sanity check later on, to
2770 /// make sure that the number of regions we see at the callsite
2772 pub num_external_vids: usize,
2774 /// Requirements between the various free regions defined in
2776 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2779 /// Indicates an outlives-constraint between a type or between two
2780 /// free regions declared on the closure.
2781 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2782 pub struct ClosureOutlivesRequirement<'tcx> {
2783 // This region or type ...
2784 pub subject: ClosureOutlivesSubject<'tcx>,
2786 // ... must outlive this one.
2787 pub outlived_free_region: ty::RegionVid,
2789 // If not, report an error here ...
2790 pub blame_span: Span,
2792 // ... due to this reason.
2793 pub category: ConstraintCategory,
2796 /// Outlives-constraints can be categorized to determine whether and why they
2797 /// are interesting (for error reporting). Order of variants indicates sort
2798 /// order of the category, thereby influencing diagnostic output.
2800 /// See also [rustc_mir::borrow_check::nll::constraints].
2814 pub enum ConstraintCategory {
2822 /// A constraint that came from checking the body of a closure.
2824 /// We try to get the category that the closure used when reporting this.
2832 /// A "boring" constraint (caused by the given location) is one that
2833 /// the user probably doesn't want to see described in diagnostics,
2834 /// because it is kind of an artifact of the type system setup.
2835 /// Example: `x = Foo { field: y }` technically creates
2836 /// intermediate regions representing the "type of `Foo { field: y
2837 /// }`", and data flows from `y` into those variables, but they
2838 /// are not very interesting. The assignment into `x` on the other
2841 // Boring and applicable everywhere.
2844 /// A constraint that doesn't correspond to anything the user sees.
2848 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2849 /// that must outlive some region.
2850 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2851 pub enum ClosureOutlivesSubject<'tcx> {
2852 /// Subject is a type, typically a type parameter, but could also
2853 /// be a projection. Indicates a requirement like `T: 'a` being
2854 /// passed to the caller, where the type here is `T`.
2856 /// The type here is guaranteed not to contain any free regions at
2860 /// Subject is a free region from the closure. Indicates a requirement
2861 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2862 Region(ty::RegionVid),
2866 * `TypeFoldable` implementations for MIR types
2869 CloneTypeFoldableAndLiftImpls! {
2877 SourceScopeLocalData,
2878 UserTypeAnnotationIndex,
2881 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2882 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2883 use crate::mir::TerminatorKind::*;
2885 let kind = match self.kind {
2886 Goto { target } => Goto { target },
2887 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2888 discr: discr.fold_with(folder),
2889 switch_ty: switch_ty.fold_with(folder),
2890 values: values.clone(),
2891 targets: targets.clone(),
2893 Drop { ref location, target, unwind } => {
2894 Drop { location: location.fold_with(folder), target, unwind }
2896 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2897 location: location.fold_with(folder),
2898 value: value.fold_with(folder),
2902 Yield { ref value, resume, drop } => {
2903 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
2905 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
2907 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2910 func: func.fold_with(folder),
2911 args: args.fold_with(folder),
2917 Assert { ref cond, expected, ref msg, target, cleanup } => {
2919 let msg = match msg {
2920 BoundsCheck { ref len, ref index } => {
2921 BoundsCheck { len: len.fold_with(folder), index: index.fold_with(folder) }
2928 | ResumedAfterReturn(_)
2929 | ResumedAfterPanic(_) => msg.clone(),
2931 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
2933 GeneratorDrop => GeneratorDrop,
2937 Unreachable => Unreachable,
2938 FalseEdges { real_target, imaginary_target } => {
2939 FalseEdges { real_target, imaginary_target }
2941 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
2943 Terminator { source_info: self.source_info, kind }
2946 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2947 use crate::mir::TerminatorKind::*;
2950 SwitchInt { ref discr, switch_ty, .. } => {
2951 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
2953 Drop { ref location, .. } => location.visit_with(visitor),
2954 DropAndReplace { ref location, ref value, .. } => {
2955 location.visit_with(visitor) || value.visit_with(visitor)
2957 Yield { ref value, .. } => value.visit_with(visitor),
2958 Call { ref func, ref args, ref destination, .. } => {
2959 let dest = if let Some((ref loc, _)) = *destination {
2960 loc.visit_with(visitor)
2964 dest || func.visit_with(visitor) || args.visit_with(visitor)
2966 Assert { ref cond, ref msg, .. } => {
2967 if cond.visit_with(visitor) {
2970 BoundsCheck { ref len, ref index } => {
2971 len.visit_with(visitor) || index.visit_with(visitor)
2978 | ResumedAfterReturn(_)
2979 | ResumedAfterPanic(_) => false,
2992 | FalseUnwind { .. } => false,
2997 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
2998 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3002 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3007 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3008 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3009 Place { base: self.base.fold_with(folder), projection: self.projection.fold_with(folder) }
3012 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3013 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3017 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3018 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3020 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3021 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3025 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3027 PlaceBase::Local(local) => local.visit_with(visitor),
3028 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3033 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3034 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3035 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3036 folder.tcx().intern_place_elems(&v)
3039 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3040 self.iter().any(|t| t.visit_with(visitor))
3044 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3045 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3047 ty: self.ty.fold_with(folder),
3048 kind: self.kind.fold_with(folder),
3049 def_id: self.def_id,
3053 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3054 let Static { ty, kind, def_id: _ } = self;
3056 ty.visit_with(visitor) || kind.visit_with(visitor)
3060 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3061 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3063 StaticKind::Promoted(promoted, substs) => {
3064 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder))
3066 StaticKind::Static => StaticKind::Static,
3070 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3072 StaticKind::Promoted(promoted, substs) => {
3073 promoted.visit_with(visitor) || substs.visit_with(visitor)
3075 StaticKind::Static => false,
3080 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3081 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3082 use crate::mir::Rvalue::*;
3084 Use(ref op) => Use(op.fold_with(folder)),
3085 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3086 Ref(region, bk, ref place) => {
3087 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3089 AddressOf(mutability, ref place) => AddressOf(mutability, place.fold_with(folder)),
3090 Len(ref place) => Len(place.fold_with(folder)),
3091 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3092 BinaryOp(op, ref rhs, ref lhs) => {
3093 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3095 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3096 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3098 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3099 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3100 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3101 Aggregate(ref kind, ref fields) => {
3102 let kind = box match **kind {
3103 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3104 AggregateKind::Tuple => AggregateKind::Tuple,
3105 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3108 substs.fold_with(folder),
3109 user_ty.fold_with(folder),
3112 AggregateKind::Closure(id, substs) => {
3113 AggregateKind::Closure(id, substs.fold_with(folder))
3115 AggregateKind::Generator(id, substs, movablity) => {
3116 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3119 Aggregate(kind, fields.fold_with(folder))
3124 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3125 use crate::mir::Rvalue::*;
3127 Use(ref op) => op.visit_with(visitor),
3128 Repeat(ref op, _) => op.visit_with(visitor),
3129 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3130 AddressOf(_, ref place) => place.visit_with(visitor),
3131 Len(ref place) => place.visit_with(visitor),
3132 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3133 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3134 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3136 UnaryOp(_, ref val) => val.visit_with(visitor),
3137 Discriminant(ref place) => place.visit_with(visitor),
3138 NullaryOp(_, ty) => ty.visit_with(visitor),
3139 Aggregate(ref kind, ref fields) => {
3141 AggregateKind::Array(ty) => ty.visit_with(visitor),
3142 AggregateKind::Tuple => false,
3143 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3144 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3146 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3147 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3148 }) || fields.visit_with(visitor)
3154 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3155 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3157 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3158 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3159 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3163 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3165 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3166 Operand::Constant(ref c) => c.visit_with(visitor),
3171 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3172 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3173 use crate::mir::ProjectionElem::*;
3177 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3178 Index(v) => Index(v.fold_with(folder)),
3179 elem => elem.clone(),
3183 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3184 use crate::mir::ProjectionElem::*;
3187 Field(_, ty) => ty.visit_with(visitor),
3188 Index(v) => v.visit_with(visitor),
3194 impl<'tcx> TypeFoldable<'tcx> for Field {
3195 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3198 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3203 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3204 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3207 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3212 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3213 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3216 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3221 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3222 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3224 span: self.span.clone(),
3225 user_ty: self.user_ty.fold_with(folder),
3226 literal: self.literal.fold_with(folder),
3229 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3230 self.literal.visit_with(visitor)