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::mir::interpret::{GlobalAlloc, PanicInfo, Scalar};
8 use crate::mir::visit::MirVisitable;
9 use crate::ty::adjustment::PointerCast;
10 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
11 use crate::ty::layout::VariantIdx;
12 use crate::ty::print::{FmtPrinter, Printer};
13 use crate::ty::subst::{Subst, SubstsRef};
15 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
18 use rustc_hir::def::{CtorKind, Namespace};
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::{self, GeneratorKind};
22 use polonius_engine::Atom;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::Dominators;
25 use rustc_data_structures::graph::{self, GraphSuccessors};
26 use rustc_data_structures::sync::Lrc;
27 use rustc_index::bit_set::BitMatrix;
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_macros::HashStable;
30 use rustc_serialize::{Decodable, Encodable};
31 use rustc_span::symbol::Symbol;
32 use rustc_span::{Span, DUMMY_SP};
33 use smallvec::SmallVec;
35 use std::fmt::{self, Debug, Display, Formatter, Write};
38 use std::{iter, mem, option, u32};
39 pub use syntax::ast::Mutability;
40 use syntax::ast::Name;
42 pub use crate::mir::cache::{BodyAndCache, ReadOnlyBodyAndCache};
43 pub use crate::mir::interpret::AssertMessage;
44 pub use crate::read_only;
54 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
56 pub trait HasLocalDecls<'tcx> {
57 fn local_decls(&self) -> &LocalDecls<'tcx>;
60 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
61 fn local_decls(&self) -> &LocalDecls<'tcx> {
66 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
67 fn local_decls(&self) -> &LocalDecls<'tcx> {
72 /// The various "big phases" that MIR goes through.
74 /// Warning: ordering of variants is significant.
95 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
96 pub fn phase_index(&self) -> usize {
101 /// The lowered representation of a single function.
102 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
103 pub struct Body<'tcx> {
104 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
105 /// that indexes into this vector.
106 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
108 /// Records how far through the "desugaring and optimization" process this particular
109 /// MIR has traversed. This is particularly useful when inlining, since in that context
110 /// we instantiate the promoted constants and add them to our promoted vector -- but those
111 /// promoted items have already been optimized, whereas ours have not. This field allows
112 /// us to see the difference and forego optimization on the inlined promoted items.
115 /// A list of source scopes; these are referenced by statements
116 /// and used for debuginfo. Indexed by a `SourceScope`.
117 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
119 /// The yield type of the function, if it is a generator.
120 pub yield_ty: Option<Ty<'tcx>>,
122 /// Generator drop glue.
123 pub generator_drop: Option<Box<BodyAndCache<'tcx>>>,
125 /// The layout of a generator. Produced by the state transformation.
126 pub generator_layout: Option<GeneratorLayout<'tcx>>,
128 /// If this is a generator then record the type of source expression that caused this generator
130 pub generator_kind: Option<GeneratorKind>,
132 /// Declarations of locals.
134 /// The first local is the return value pointer, followed by `arg_count`
135 /// locals for the function arguments, followed by any user-declared
136 /// variables and temporaries.
137 pub local_decls: LocalDecls<'tcx>,
139 /// User type annotations.
140 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
142 /// The number of arguments this function takes.
144 /// Starting at local 1, `arg_count` locals will be provided by the caller
145 /// and can be assumed to be initialized.
147 /// If this MIR was built for a constant, this will be 0.
148 pub arg_count: usize,
150 /// Mark an argument local (which must be a tuple) as getting passed as
151 /// its individual components at the LLVM level.
153 /// This is used for the "rust-call" ABI.
154 pub spread_arg: Option<Local>,
156 /// Debug information pertaining to user variables, including captures.
157 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
159 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
160 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
161 /// this conversion from happening and use short circuiting, we will cause the following code
162 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
164 /// List of places where control flow was destroyed. Used for error reporting.
165 pub control_flow_destroyed: Vec<(Span, String)>,
167 /// A span representing this MIR, for error reporting.
171 impl<'tcx> Body<'tcx> {
173 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
174 source_scopes: IndexVec<SourceScope, SourceScopeData>,
175 local_decls: LocalDecls<'tcx>,
176 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
178 var_debug_info: Vec<VarDebugInfo<'tcx>>,
180 control_flow_destroyed: Vec<(Span, String)>,
181 generator_kind: Option<GeneratorKind>,
183 // We need `arg_count` locals, and one for the return place.
185 local_decls.len() >= arg_count + 1,
186 "expected at least {} locals, got {}",
192 phase: MirPhase::Build,
196 generator_drop: None,
197 generator_layout: None,
200 user_type_annotations,
205 control_flow_destroyed,
210 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
214 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
216 pub fn is_cfg_cyclic(&self) -> bool {
217 graph::is_cyclic(self)
221 pub fn local_kind(&self, local: Local) -> LocalKind {
222 let index = local.as_usize();
225 self.local_decls[local].mutability == Mutability::Mut,
226 "return place should be mutable"
229 LocalKind::ReturnPointer
230 } else if index < self.arg_count + 1 {
232 } else if self.local_decls[local].is_user_variable() {
239 /// Returns an iterator over all temporaries.
241 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
242 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
243 let local = Local::new(index);
244 if self.local_decls[local].is_user_variable() { None } else { Some(local) }
248 /// Returns an iterator over all user-declared locals.
250 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
251 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
252 let local = Local::new(index);
253 self.local_decls[local].is_user_variable().then_some(local)
257 /// Returns an iterator over all user-declared mutable locals.
259 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
260 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
261 let local = Local::new(index);
262 let decl = &self.local_decls[local];
263 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
271 /// Returns an iterator over all user-declared mutable arguments and locals.
273 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
274 (1..self.local_decls.len()).filter_map(move |index| {
275 let local = Local::new(index);
276 let decl = &self.local_decls[local];
277 if (decl.is_user_variable() || index < self.arg_count + 1)
278 && decl.mutability == Mutability::Mut
287 /// Returns an iterator over all function arguments.
289 pub fn args_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
290 let arg_count = self.arg_count;
291 (1..arg_count + 1).map(Local::new)
294 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
295 /// locals that are neither arguments nor the return place).
297 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> + ExactSizeIterator {
298 let arg_count = self.arg_count;
299 let local_count = self.local_decls.len();
300 (arg_count + 1..local_count).map(Local::new)
303 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
304 /// invalidating statement indices in `Location`s.
305 pub fn make_statement_nop(&mut self, location: Location) {
306 let block = &mut self.basic_blocks[location.block];
307 debug_assert!(location.statement_index < block.statements.len());
308 block.statements[location.statement_index].make_nop()
311 /// Returns the source info associated with `location`.
312 pub fn source_info(&self, location: Location) -> &SourceInfo {
313 let block = &self[location.block];
314 let stmts = &block.statements;
315 let idx = location.statement_index;
316 if idx < stmts.len() {
317 &stmts[idx].source_info
319 assert_eq!(idx, stmts.len());
320 &block.terminator().source_info
324 /// Checks if `sub` is a sub scope of `sup`
325 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
327 match self.source_scopes[sub].parent_scope {
328 None => return false,
335 /// Returns the return type; it always return first element from `local_decls` array.
336 pub fn return_ty(&self) -> Ty<'tcx> {
337 self.local_decls[RETURN_PLACE].ty
340 /// Gets the location of the terminator for the given block.
341 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
342 Location { block: bb, statement_index: self[bb].statements.len() }
346 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
349 /// Unsafe because of a PushUnsafeBlock
351 /// Unsafe because of an unsafe fn
353 /// Unsafe because of an `unsafe` block
354 ExplicitUnsafe(hir::HirId),
357 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
358 type Output = BasicBlockData<'tcx>;
361 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
362 &self.basic_blocks()[index]
366 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
367 pub enum ClearCrossCrate<T> {
372 impl<T> ClearCrossCrate<T> {
373 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
375 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
376 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
380 pub fn assert_crate_local(self) -> T {
382 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
383 ClearCrossCrate::Set(v) => v,
388 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
389 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
391 /// Grouped information about the source code origin of a MIR entity.
392 /// Intended to be inspected by diagnostics and debuginfo.
393 /// Most passes can work with it as a whole, within a single function.
394 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
395 // `Hash`. Please ping @bjorn3 if removing them.
396 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
397 pub struct SourceInfo {
398 /// The source span for the AST pertaining to this MIR entity.
401 /// The source scope, keeping track of which bindings can be
402 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
403 pub scope: SourceScope,
406 ///////////////////////////////////////////////////////////////////////////
421 pub enum BorrowKind {
422 /// Data must be immutable and is aliasable.
425 /// The immediately borrowed place must be immutable, but projections from
426 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
427 /// conflict with a mutable borrow of `a.b.c`.
429 /// This is used when lowering matches: when matching on a place we want to
430 /// ensure that place have the same value from the start of the match until
431 /// an arm is selected. This prevents this code from compiling:
433 /// let mut x = &Some(0);
436 /// Some(_) if { x = &None; false } => (),
440 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
441 /// should not prevent `if let None = x { ... }`, for example, because the
442 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
443 /// We can also report errors with this kind of borrow differently.
446 /// Data must be immutable but not aliasable. This kind of borrow
447 /// cannot currently be expressed by the user and is used only in
448 /// implicit closure bindings. It is needed when the closure is
449 /// borrowing or mutating a mutable referent, e.g.:
451 /// let x: &mut isize = ...;
452 /// let y = || *x += 5;
454 /// If we were to try to translate this closure into a more explicit
455 /// form, we'd encounter an error with the code as written:
457 /// struct Env { x: & &mut isize }
458 /// let x: &mut isize = ...;
459 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
460 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
462 /// This is then illegal because you cannot mutate an `&mut` found
463 /// in an aliasable location. To solve, you'd have to translate with
464 /// an `&mut` borrow:
466 /// struct Env { x: & &mut isize }
467 /// let x: &mut isize = ...;
468 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
469 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
471 /// Now the assignment to `**env.x` is legal, but creating a
472 /// mutable pointer to `x` is not because `x` is not mutable. We
473 /// could fix this by declaring `x` as `let mut x`. This is ok in
474 /// user code, if awkward, but extra weird for closures, since the
475 /// borrow is hidden.
477 /// So we introduce a "unique imm" borrow -- the referent is
478 /// immutable, but not aliasable. This solves the problem. For
479 /// simplicity, we don't give users the way to express this
480 /// borrow, it's just used when translating closures.
483 /// Data is mutable and not aliasable.
485 /// `true` if this borrow arose from method-call auto-ref
486 /// (i.e., `adjustment::Adjust::Borrow`).
487 allow_two_phase_borrow: bool,
492 pub fn allows_two_phase_borrow(&self) -> bool {
494 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
495 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
500 ///////////////////////////////////////////////////////////////////////////
501 // Variables and temps
503 rustc_index::newtype_index! {
506 DEBUG_FORMAT = "_{}",
507 const RETURN_PLACE = 0,
511 impl Atom for Local {
512 fn index(self) -> usize {
517 /// Classifies locals into categories. See `Body::local_kind`.
518 #[derive(PartialEq, Eq, Debug, HashStable)]
520 /// User-declared variable binding.
522 /// Compiler-introduced temporary.
524 /// Function argument.
526 /// Location of function's return value.
530 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
531 pub struct VarBindingForm<'tcx> {
532 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
533 pub binding_mode: ty::BindingMode,
534 /// If an explicit type was provided for this variable binding,
535 /// this holds the source Span of that type.
537 /// NOTE: if you want to change this to a `HirId`, be wary that
538 /// doing so breaks incremental compilation (as of this writing),
539 /// while a `Span` does not cause our tests to fail.
540 pub opt_ty_info: Option<Span>,
541 /// Place of the RHS of the =, or the subject of the `match` where this
542 /// variable is initialized. None in the case of `let PATTERN;`.
543 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
544 /// (a) the right-hand side isn't evaluated as a place expression.
545 /// (b) it gives a way to separate this case from the remaining cases
547 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
548 /// The span of the pattern in which this variable was bound.
552 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
553 pub enum BindingForm<'tcx> {
554 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
555 Var(VarBindingForm<'tcx>),
556 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
557 ImplicitSelf(ImplicitSelfKind),
558 /// Reference used in a guard expression to ensure immutability.
562 /// Represents what type of implicit self a function has, if any.
563 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
564 pub enum ImplicitSelfKind {
565 /// Represents a `fn x(self);`.
567 /// Represents a `fn x(mut self);`.
569 /// Represents a `fn x(&self);`.
571 /// Represents a `fn x(&mut self);`.
573 /// Represents when a function does not have a self argument or
574 /// when a function has a `self: X` argument.
578 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
580 mod binding_form_impl {
581 use crate::ich::StableHashingContext;
582 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
584 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
585 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
586 use super::BindingForm::*;
587 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
590 Var(binding) => binding.hash_stable(hcx, hasher),
591 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
598 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
599 /// created during evaluation of expressions in a block tail
600 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
602 /// It is used to improve diagnostics when such temporaries are
603 /// involved in borrow_check errors, e.g., explanations of where the
604 /// temporaries come from, when their destructors are run, and/or how
605 /// one might revise the code to satisfy the borrow checker's rules.
606 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
607 pub struct BlockTailInfo {
608 /// If `true`, then the value resulting from evaluating this tail
609 /// expression is ignored by the block's expression context.
611 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
612 /// but not e.g., `let _x = { ...; tail };`
613 pub tail_result_is_ignored: bool,
618 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
619 /// argument, or the return place.
620 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
621 pub struct LocalDecl<'tcx> {
622 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
624 /// Temporaries and the return place are always mutable.
625 pub mutability: Mutability,
627 // FIXME(matthewjasper) Don't store in this in `Body`
628 pub local_info: LocalInfo<'tcx>,
630 /// `true` if this is an internal local.
632 /// These locals are not based on types in the source code and are only used
633 /// for a few desugarings at the moment.
635 /// The generator transformation will sanity check the locals which are live
636 /// across a suspension point against the type components of the generator
637 /// which type checking knows are live across a suspension point. We need to
638 /// flag drop flags to avoid triggering this check as they are introduced
641 /// Unsafety checking will also ignore dereferences of these locals,
642 /// so they can be used for raw pointers only used in a desugaring.
644 /// This should be sound because the drop flags are fully algebraic, and
645 /// therefore don't affect the OIBIT or outlives properties of the
649 /// If this local is a temporary and `is_block_tail` is `Some`,
650 /// then it is a temporary created for evaluation of some
651 /// subexpression of some block's tail expression (with no
652 /// intervening statement context).
653 // FIXME(matthewjasper) Don't store in this in `Body`
654 pub is_block_tail: Option<BlockTailInfo>,
656 /// The type of this local.
659 /// If the user manually ascribed a type to this variable,
660 /// e.g., via `let x: T`, then we carry that type here. The MIR
661 /// borrow checker needs this information since it can affect
662 /// region inference.
663 // FIXME(matthewjasper) Don't store in this in `Body`
664 pub user_ty: UserTypeProjections,
666 /// The *syntactic* (i.e., not visibility) source scope the local is defined
667 /// in. If the local was defined in a let-statement, this
668 /// is *within* the let-statement, rather than outside
671 /// This is needed because the visibility source scope of locals within
672 /// a let-statement is weird.
674 /// The reason is that we want the local to be *within* the let-statement
675 /// for lint purposes, but we want the local to be *after* the let-statement
676 /// for names-in-scope purposes.
678 /// That's it, if we have a let-statement like the one in this
682 /// fn foo(x: &str) {
683 /// #[allow(unused_mut)]
684 /// let mut x: u32 = { // <- one unused mut
685 /// let mut y: u32 = x.parse().unwrap();
692 /// Then, from a lint point of view, the declaration of `x: u32`
693 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
694 /// lint scopes are the same as the AST/HIR nesting.
696 /// However, from a name lookup point of view, the scopes look more like
697 /// as if the let-statements were `match` expressions:
700 /// fn foo(x: &str) {
702 /// match x.parse().unwrap() {
711 /// We care about the name-lookup scopes for debuginfo - if the
712 /// debuginfo instruction pointer is at the call to `x.parse()`, we
713 /// want `x` to refer to `x: &str`, but if it is at the call to
714 /// `drop(x)`, we want it to refer to `x: u32`.
716 /// To allow both uses to work, we need to have more than a single scope
717 /// for a local. We have the `source_info.scope` represent the "syntactic"
718 /// lint scope (with a variable being under its let block) while the
719 /// `var_debug_info.source_info.scope` represents the "local variable"
720 /// scope (where the "rest" of a block is under all prior let-statements).
722 /// The end result looks like this:
726 /// │{ argument x: &str }
728 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
729 /// │ │ // in practice because I'm lazy.
731 /// │ │← x.source_info.scope
732 /// │ │← `x.parse().unwrap()`
734 /// │ │ │← y.source_info.scope
736 /// │ │ │{ let y: u32 }
738 /// │ │ │← y.var_debug_info.source_info.scope
741 /// │ │{ let x: u32 }
742 /// │ │← x.var_debug_info.source_info.scope
743 /// │ │← `drop(x)` // This accesses `x: u32`.
745 pub source_info: SourceInfo,
748 /// Extra information about a local that's used for diagnostics.
749 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
750 pub enum LocalInfo<'tcx> {
751 /// A user-defined local variable or function parameter
753 /// The `BindingForm` is solely used for local diagnostics when generating
754 /// warnings/errors when compiling the current crate, and therefore it need
755 /// not be visible across crates.
756 User(ClearCrossCrate<BindingForm<'tcx>>),
757 /// A temporary created that references the static with the given `DefId`.
758 StaticRef { def_id: DefId, is_thread_local: bool },
759 /// Any other temporary, the return place, or an anonymous function parameter.
763 impl<'tcx> LocalDecl<'tcx> {
764 /// Returns `true` only if local is a binding that can itself be
765 /// made mutable via the addition of the `mut` keyword, namely
766 /// something like the occurrences of `x` in:
767 /// - `fn foo(x: Type) { ... }`,
769 /// - or `match ... { C(x) => ... }`
770 pub fn can_be_made_mutable(&self) -> bool {
771 match self.local_info {
772 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
773 binding_mode: ty::BindingMode::BindByValue(_),
779 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
780 ImplicitSelfKind::Imm,
787 /// Returns `true` if local is definitely not a `ref ident` or
788 /// `ref mut ident` binding. (Such bindings cannot be made into
789 /// mutable bindings, but the inverse does not necessarily hold).
790 pub fn is_nonref_binding(&self) -> bool {
791 match self.local_info {
792 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
793 binding_mode: ty::BindingMode::BindByValue(_),
799 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
805 /// Returns `true` if this variable is a named variable or function
806 /// parameter declared by the user.
808 pub fn is_user_variable(&self) -> bool {
809 match self.local_info {
810 LocalInfo::User(_) => true,
815 /// Returns `true` if this is a reference to a variable bound in a `match`
816 /// expression that is used to access said variable for the guard of the
818 pub fn is_ref_for_guard(&self) -> bool {
819 match self.local_info {
820 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
825 /// Returns `Some` if this is a reference to a static item that is used to
826 /// access that static
827 pub fn is_ref_to_static(&self) -> bool {
828 match self.local_info {
829 LocalInfo::StaticRef { .. } => true,
834 /// Returns `Some` if this is a reference to a static item that is used to
835 /// access that static
836 pub fn is_ref_to_thread_local(&self) -> bool {
837 match self.local_info {
838 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
843 /// Returns `true` is the local is from a compiler desugaring, e.g.,
844 /// `__next` from a `for` loop.
846 pub fn from_compiler_desugaring(&self) -> bool {
847 self.source_info.span.desugaring_kind().is_some()
850 /// Creates a new `LocalDecl` for a temporary.
852 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
853 Self::new_local(ty, Mutability::Mut, false, span)
856 /// Converts `self` into same `LocalDecl` except tagged as immutable.
858 pub fn immutable(mut self) -> Self {
859 self.mutability = Mutability::Not;
863 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
865 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
866 assert!(self.is_block_tail.is_none());
867 self.is_block_tail = Some(info);
871 /// Creates a new `LocalDecl` for a internal temporary.
873 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
874 Self::new_local(ty, Mutability::Mut, true, span)
878 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
882 user_ty: UserTypeProjections::none(),
883 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
885 local_info: LocalInfo::Other,
890 /// Builds a `LocalDecl` for the return place.
892 /// This must be inserted into the `local_decls` list as the first local.
894 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
896 mutability: Mutability::Mut,
898 user_ty: UserTypeProjections::none(),
899 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
902 local_info: LocalInfo::Other,
907 /// Debug information pertaining to a user variable.
908 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
909 pub struct VarDebugInfo<'tcx> {
912 /// Source info of the user variable, including the scope
913 /// within which the variable is visible (to debuginfo)
914 /// (see `LocalDecl`'s `source_info` field for more details).
915 pub source_info: SourceInfo,
917 /// Where the data for this user variable is to be found.
918 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
919 /// based on a `Local`, not a `Static`, and contains no indexing.
920 pub place: Place<'tcx>,
923 ///////////////////////////////////////////////////////////////////////////
926 rustc_index::newtype_index! {
927 pub struct BasicBlock {
929 DEBUG_FORMAT = "bb{}",
930 const START_BLOCK = 0,
935 pub fn start_location(self) -> Location {
936 Location { block: self, statement_index: 0 }
940 ///////////////////////////////////////////////////////////////////////////
941 // BasicBlockData and Terminator
943 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
944 pub struct BasicBlockData<'tcx> {
945 /// List of statements in this block.
946 pub statements: Vec<Statement<'tcx>>,
948 /// Terminator for this block.
950 /// N.B., this should generally ONLY be `None` during construction.
951 /// Therefore, you should generally access it via the
952 /// `terminator()` or `terminator_mut()` methods. The only
953 /// exception is that certain passes, such as `simplify_cfg`, swap
954 /// out the terminator temporarily with `None` while they continue
955 /// to recurse over the set of basic blocks.
956 pub terminator: Option<Terminator<'tcx>>,
958 /// If true, this block lies on an unwind path. This is used
959 /// during codegen where distinct kinds of basic blocks may be
960 /// generated (particularly for MSVC cleanup). Unwind blocks must
961 /// only branch to other unwind blocks.
962 pub is_cleanup: bool,
965 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
966 pub struct Terminator<'tcx> {
967 pub source_info: SourceInfo,
968 pub kind: TerminatorKind<'tcx>,
971 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
972 pub enum TerminatorKind<'tcx> {
973 /// Block should have one successor in the graph; we jump there.
974 Goto { target: BasicBlock },
976 /// Operand evaluates to an integer; jump depending on its value
977 /// to one of the targets, and otherwise fallback to `otherwise`.
979 /// The discriminant value being tested.
980 discr: Operand<'tcx>,
982 /// The type of value being tested.
985 /// Possible values. The locations to branch to in each case
986 /// are found in the corresponding indices from the `targets` vector.
987 values: Cow<'tcx, [u128]>,
989 /// Possible branch sites. The last element of this vector is used
990 /// for the otherwise branch, so targets.len() == values.len() + 1
993 // This invariant is quite non-obvious and also could be improved.
994 // One way to make this invariant is to have something like this instead:
996 // branches: Vec<(ConstInt, BasicBlock)>,
997 // otherwise: Option<BasicBlock> // exhaustive if None
999 // However we’ve decided to keep this as-is until we figure a case
1000 // where some other approach seems to be strictly better than other.
1001 targets: Vec<BasicBlock>,
1004 /// Indicates that the landing pad is finished and unwinding should
1005 /// continue. Emitted by `build::scope::diverge_cleanup`.
1008 /// Indicates that the landing pad is finished and that the process
1009 /// should abort. Used to prevent unwinding for foreign items.
1012 /// Indicates a normal return. The return place should have
1013 /// been filled in by now. This should occur at most once.
1016 /// Indicates a terminator that can never be reached.
1019 /// Drop the `Place`.
1020 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1022 /// Drop the `Place` and assign the new value over it. This ensures
1023 /// that the assignment to `P` occurs *even if* the destructor for
1024 /// place unwinds. Its semantics are best explained by the
1029 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1037 /// Drop(P, goto BB1, unwind BB2)
1040 /// // P is now uninitialized
1044 /// // P is now uninitialized -- its dtor panicked
1049 location: Place<'tcx>,
1050 value: Operand<'tcx>,
1052 unwind: Option<BasicBlock>,
1055 /// Block ends with a call of a converging function.
1057 /// The function that’s being called.
1058 func: Operand<'tcx>,
1059 /// Arguments the function is called with.
1060 /// These are owned by the callee, which is free to modify them.
1061 /// This allows the memory occupied by "by-value" arguments to be
1062 /// reused across function calls without duplicating the contents.
1063 args: Vec<Operand<'tcx>>,
1064 /// Destination for the return value. If some, the call is converging.
1065 destination: Option<(Place<'tcx>, BasicBlock)>,
1066 /// Cleanups to be done if the call unwinds.
1067 cleanup: Option<BasicBlock>,
1068 /// `true` if this is from a call in HIR rather than from an overloaded
1069 /// operator. True for overloaded function call.
1070 from_hir_call: bool,
1073 /// Jump to the target if the condition has the expected value,
1074 /// otherwise panic with a message and a cleanup target.
1076 cond: Operand<'tcx>,
1078 msg: AssertMessage<'tcx>,
1080 cleanup: Option<BasicBlock>,
1083 /// A suspend point.
1085 /// The value to return.
1086 value: Operand<'tcx>,
1087 /// Where to resume to.
1089 /// Cleanup to be done if the generator is dropped at this suspend point.
1090 drop: Option<BasicBlock>,
1093 /// Indicates the end of the dropping of a generator.
1096 /// A block where control flow only ever takes one real path, but borrowck
1097 /// needs to be more conservative.
1099 /// The target normal control flow will take.
1100 real_target: BasicBlock,
1101 /// A block control flow could conceptually jump to, but won't in
1103 imaginary_target: BasicBlock,
1105 /// A terminator for blocks that only take one path in reality, but where we
1106 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1107 /// This can arise in infinite loops with no function calls for example.
1109 /// The target normal control flow will take.
1110 real_target: BasicBlock,
1111 /// The imaginary cleanup block link. This particular path will never be taken
1112 /// in practice, but in order to avoid fragility we want to always
1113 /// consider it in borrowck. We don't want to accept programs which
1114 /// pass borrowck only when `panic=abort` or some assertions are disabled
1115 /// due to release vs. debug mode builds. This needs to be an `Option` because
1116 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1117 unwind: Option<BasicBlock>,
1121 pub type Successors<'a> =
1122 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1123 pub type SuccessorsMut<'a> =
1124 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1126 impl<'tcx> Terminator<'tcx> {
1127 pub fn successors(&self) -> Successors<'_> {
1128 self.kind.successors()
1131 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1132 self.kind.successors_mut()
1135 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1139 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1140 self.kind.unwind_mut()
1144 impl<'tcx> TerminatorKind<'tcx> {
1147 cond: Operand<'tcx>,
1150 ) -> TerminatorKind<'tcx> {
1151 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1152 TerminatorKind::SwitchInt {
1154 switch_ty: tcx.types.bool,
1155 values: From::from(BOOL_SWITCH_FALSE),
1156 targets: vec![f, t],
1160 pub fn successors(&self) -> Successors<'_> {
1161 use self::TerminatorKind::*;
1168 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1169 Goto { target: ref t }
1170 | Call { destination: None, cleanup: Some(ref t), .. }
1171 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1172 | Yield { resume: ref t, drop: None, .. }
1173 | DropAndReplace { target: ref t, unwind: None, .. }
1174 | Drop { target: ref t, unwind: None, .. }
1175 | Assert { target: ref t, cleanup: None, .. }
1176 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1177 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1178 | Yield { resume: ref t, drop: Some(ref u), .. }
1179 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1180 | Drop { target: ref t, unwind: Some(ref u), .. }
1181 | Assert { target: ref t, cleanup: Some(ref u), .. }
1182 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1183 Some(t).into_iter().chain(slice::from_ref(u))
1185 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1186 FalseEdges { ref real_target, ref imaginary_target } => {
1187 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1192 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1193 use self::TerminatorKind::*;
1200 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1201 Goto { target: ref mut t }
1202 | Call { destination: None, cleanup: Some(ref mut t), .. }
1203 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1204 | Yield { resume: ref mut t, drop: None, .. }
1205 | DropAndReplace { target: ref mut t, unwind: None, .. }
1206 | Drop { target: ref mut t, unwind: None, .. }
1207 | Assert { target: ref mut t, cleanup: None, .. }
1208 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1209 Some(t).into_iter().chain(&mut [])
1211 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1212 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1213 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1214 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1215 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1216 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1217 Some(t).into_iter().chain(slice::from_mut(u))
1219 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1220 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1221 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1226 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1228 TerminatorKind::Goto { .. }
1229 | TerminatorKind::Resume
1230 | TerminatorKind::Abort
1231 | TerminatorKind::Return
1232 | TerminatorKind::Unreachable
1233 | TerminatorKind::GeneratorDrop
1234 | TerminatorKind::Yield { .. }
1235 | TerminatorKind::SwitchInt { .. }
1236 | TerminatorKind::FalseEdges { .. } => None,
1237 TerminatorKind::Call { cleanup: ref unwind, .. }
1238 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1239 | TerminatorKind::DropAndReplace { ref unwind, .. }
1240 | TerminatorKind::Drop { ref unwind, .. }
1241 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1245 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1247 TerminatorKind::Goto { .. }
1248 | TerminatorKind::Resume
1249 | TerminatorKind::Abort
1250 | TerminatorKind::Return
1251 | TerminatorKind::Unreachable
1252 | TerminatorKind::GeneratorDrop
1253 | TerminatorKind::Yield { .. }
1254 | TerminatorKind::SwitchInt { .. }
1255 | TerminatorKind::FalseEdges { .. } => None,
1256 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1257 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1258 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1259 | TerminatorKind::Drop { ref mut unwind, .. }
1260 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1265 impl<'tcx> BasicBlockData<'tcx> {
1266 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1267 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1270 /// Accessor for terminator.
1272 /// Terminator may not be None after construction of the basic block is complete. This accessor
1273 /// provides a convenience way to reach the terminator.
1274 pub fn terminator(&self) -> &Terminator<'tcx> {
1275 self.terminator.as_ref().expect("invalid terminator state")
1278 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1279 self.terminator.as_mut().expect("invalid terminator state")
1282 pub fn retain_statements<F>(&mut self, mut f: F)
1284 F: FnMut(&mut Statement<'_>) -> bool,
1286 for s in &mut self.statements {
1293 pub fn expand_statements<F, I>(&mut self, mut f: F)
1295 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1296 I: iter::TrustedLen<Item = Statement<'tcx>>,
1298 // Gather all the iterators we'll need to splice in, and their positions.
1299 let mut splices: Vec<(usize, I)> = vec![];
1300 let mut extra_stmts = 0;
1301 for (i, s) in self.statements.iter_mut().enumerate() {
1302 if let Some(mut new_stmts) = f(s) {
1303 if let Some(first) = new_stmts.next() {
1304 // We can already store the first new statement.
1307 // Save the other statements for optimized splicing.
1308 let remaining = new_stmts.size_hint().0;
1310 splices.push((i + 1 + extra_stmts, new_stmts));
1311 extra_stmts += remaining;
1319 // Splice in the new statements, from the end of the block.
1320 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1321 // where a range of elements ("gap") is left uninitialized, with
1322 // splicing adding new elements to the end of that gap and moving
1323 // existing elements from before the gap to the end of the gap.
1324 // For now, this is safe code, emulating a gap but initializing it.
1325 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1326 self.statements.resize(
1329 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1330 kind: StatementKind::Nop,
1333 for (splice_start, new_stmts) in splices.into_iter().rev() {
1334 let splice_end = splice_start + new_stmts.size_hint().0;
1335 while gap.end > splice_end {
1338 self.statements.swap(gap.start, gap.end);
1340 self.statements.splice(splice_start..splice_end, new_stmts);
1341 gap.end = splice_start;
1345 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1346 if index < self.statements.len() { &self.statements[index] } else { &self.terminator }
1350 impl<'tcx> Debug for TerminatorKind<'tcx> {
1351 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1352 self.fmt_head(fmt)?;
1353 let successor_count = self.successors().count();
1354 let labels = self.fmt_successor_labels();
1355 assert_eq!(successor_count, labels.len());
1357 match successor_count {
1360 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1363 write!(fmt, " -> [")?;
1364 for (i, target) in self.successors().enumerate() {
1368 write!(fmt, "{}: {:?}", labels[i], target)?;
1376 impl<'tcx> TerminatorKind<'tcx> {
1377 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1378 /// successor basic block, if any. The only information not included is the list of possible
1379 /// successors, which may be rendered differently between the text and the graphviz format.
1380 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1381 use self::TerminatorKind::*;
1383 Goto { .. } => write!(fmt, "goto"),
1384 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1385 Return => write!(fmt, "return"),
1386 GeneratorDrop => write!(fmt, "generator_drop"),
1387 Resume => write!(fmt, "resume"),
1388 Abort => write!(fmt, "abort"),
1389 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1390 Unreachable => write!(fmt, "unreachable"),
1391 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1392 DropAndReplace { ref location, ref value, .. } => {
1393 write!(fmt, "replace({:?} <- {:?})", location, value)
1395 Call { ref func, ref args, ref destination, .. } => {
1396 if let Some((ref destination, _)) = *destination {
1397 write!(fmt, "{:?} = ", destination)?;
1399 write!(fmt, "{:?}(", func)?;
1400 for (index, arg) in args.iter().enumerate() {
1404 write!(fmt, "{:?}", arg)?;
1408 Assert { ref cond, expected, ref msg, .. } => {
1409 write!(fmt, "assert(")?;
1413 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1415 FalseEdges { .. } => write!(fmt, "falseEdges"),
1416 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1420 /// Returns the list of labels for the edges to the successor basic blocks.
1421 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1422 use self::TerminatorKind::*;
1424 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1425 Goto { .. } => vec!["".into()],
1426 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1427 let param_env = ty::ParamEnv::empty();
1428 let switch_ty = tcx.lift(&switch_ty).unwrap();
1429 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1433 ty::Const::from_scalar(tcx, Scalar::from_uint(u, size).into(), switch_ty)
1437 .chain(iter::once("otherwise".into()))
1440 Call { destination: Some(_), cleanup: Some(_), .. } => {
1441 vec!["return".into(), "unwind".into()]
1443 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1444 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1445 Call { destination: None, cleanup: None, .. } => vec![],
1446 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1447 Yield { drop: None, .. } => vec!["resume".into()],
1448 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1449 vec!["return".into()]
1451 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1452 vec!["return".into(), "unwind".into()]
1454 Assert { cleanup: None, .. } => vec!["".into()],
1455 Assert { .. } => vec!["success".into(), "unwind".into()],
1456 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1457 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1458 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1463 ///////////////////////////////////////////////////////////////////////////
1466 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1467 pub struct Statement<'tcx> {
1468 pub source_info: SourceInfo,
1469 pub kind: StatementKind<'tcx>,
1472 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1473 #[cfg(target_arch = "x86_64")]
1474 static_assert_size!(Statement<'_>, 32);
1476 impl Statement<'_> {
1477 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1478 /// invalidating statement indices in `Location`s.
1479 pub fn make_nop(&mut self) {
1480 self.kind = StatementKind::Nop
1483 /// Changes a statement to a nop and returns the original statement.
1484 pub fn replace_nop(&mut self) -> Self {
1486 source_info: self.source_info,
1487 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1492 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1493 pub enum StatementKind<'tcx> {
1494 /// Write the RHS Rvalue to the LHS Place.
1495 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1497 /// This represents all the reading that a pattern match may do
1498 /// (e.g., inspecting constants and discriminant values), and the
1499 /// kind of pattern it comes from. This is in order to adapt potential
1500 /// error messages to these specific patterns.
1502 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1503 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1504 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1506 /// Write the discriminant for a variant to the enum Place.
1507 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1509 /// Start a live range for the storage of the local.
1512 /// End the current live range for the storage of the local.
1515 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1516 /// of `StatementKind` low.
1517 InlineAsm(Box<InlineAsm<'tcx>>),
1519 /// Retag references in the given place, ensuring they got fresh tags. This is
1520 /// part of the Stacked Borrows model. These statements are currently only interpreted
1521 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1522 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1523 /// for more details.
1524 Retag(RetagKind, Box<Place<'tcx>>),
1526 /// Encodes a user's type ascription. These need to be preserved
1527 /// intact so that NLL can respect them. For example:
1531 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1532 /// to the user-given type `T`. The effect depends on the specified variance:
1534 /// - `Covariant` -- requires that `T_y <: T`
1535 /// - `Contravariant` -- requires that `T_y :> T`
1536 /// - `Invariant` -- requires that `T_y == T`
1537 /// - `Bivariant` -- no effect
1538 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1540 /// No-op. Useful for deleting instructions without affecting statement indices.
1544 /// Describes what kind of retag is to be performed.
1545 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1546 pub enum RetagKind {
1547 /// The initial retag when entering a function.
1549 /// Retag preparing for a two-phase borrow.
1551 /// Retagging raw pointers.
1553 /// A "normal" retag.
1557 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1558 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1559 pub enum FakeReadCause {
1560 /// Inject a fake read of the borrowed input at the end of each guards
1563 /// This should ensure that you cannot change the variant for an enum while
1564 /// you are in the midst of matching on it.
1567 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1568 /// generate a read of x to check that it is initialized and safe.
1571 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1572 /// in a match guard to ensure that it's value hasn't change by the time
1573 /// we create the OutsideGuard version.
1576 /// Officially, the semantics of
1578 /// `let pattern = <expr>;`
1580 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1581 /// into the pattern.
1583 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1584 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1585 /// but in some cases it can affect the borrow checker, as in #53695.
1586 /// Therefore, we insert a "fake read" here to ensure that we get
1587 /// appropriate errors.
1590 /// If we have an index expression like
1592 /// (*x)[1][{ x = y; 4}]
1594 /// then the first bounds check is invalidated when we evaluate the second
1595 /// index expression. Thus we create a fake borrow of `x` across the second
1596 /// indexer, which will cause a borrow check error.
1600 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1601 pub struct InlineAsm<'tcx> {
1602 pub asm: hir::InlineAsmInner,
1603 pub outputs: Box<[Place<'tcx>]>,
1604 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1607 impl Debug for Statement<'_> {
1608 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1609 use self::StatementKind::*;
1611 Assign(box (ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1612 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1613 Retag(ref kind, ref place) => write!(
1617 RetagKind::FnEntry => "[fn entry] ",
1618 RetagKind::TwoPhase => "[2phase] ",
1619 RetagKind::Raw => "[raw] ",
1620 RetagKind::Default => "",
1624 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1625 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1626 SetDiscriminant { ref place, variant_index } => {
1627 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1629 InlineAsm(ref asm) => {
1630 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1632 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
1633 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1635 Nop => write!(fmt, "nop"),
1640 ///////////////////////////////////////////////////////////////////////////
1643 /// A path to a value; something that can be evaluated without
1644 /// changing or disturbing program state.
1645 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable)]
1646 pub struct Place<'tcx> {
1647 pub base: PlaceBase<'tcx>,
1649 /// projection out of a place (access a field, deref a pointer, etc)
1650 pub projection: &'tcx List<PlaceElem<'tcx>>,
1653 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1655 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable)]
1656 pub enum PlaceBase<'tcx> {
1660 /// static or static mut variable
1661 Static(Box<Static<'tcx>>),
1664 /// We store the normalized type to avoid requiring normalization when reading MIR
1677 pub struct Static<'tcx> {
1679 pub kind: StaticKind<'tcx>,
1680 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1681 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1682 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1683 /// into the calling frame.
1699 pub enum StaticKind<'tcx> {
1700 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1701 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1702 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1703 Promoted(Promoted, SubstsRef<'tcx>),
1707 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1708 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1709 pub enum ProjectionElem<V, T> {
1714 /// These indices are generated by slice patterns. Easiest to explain
1718 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1719 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1720 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1721 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1724 /// index or -index (in Python terms), depending on from_end
1726 /// The thing being indexed must be at least this long. For arrays this
1727 /// is always the exact length.
1729 /// Counting backwards from end? This is always false when indexing an
1734 /// These indices are generated by slice patterns.
1736 /// If `from_end` is true `slice[from..slice.len() - to]`.
1737 /// Otherwise `array[from..to]`.
1741 /// Whether `to` counts from the start or end of the array/slice.
1742 /// For `PlaceElem`s this is `true` if and only if the base is a slice.
1743 /// For `ProjectionKind`, this can also be `true` for arrays.
1747 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1748 /// this for ADTs with more than one variant. It may be better to
1749 /// just introduce it always, or always for enums.
1751 /// The included Symbol is the name of the variant, used for printing MIR.
1752 Downcast(Option<Symbol>, VariantIdx),
1755 impl<V, T> ProjectionElem<V, T> {
1756 /// Returns `true` if the target of this projection may refer to a different region of memory
1758 fn is_indirect(&self) -> bool {
1760 Self::Deref => true,
1764 | Self::ConstantIndex { .. }
1765 | Self::Subslice { .. }
1766 | Self::Downcast(_, _) => false,
1771 /// Alias for projections as they appear in places, where the base is a place
1772 /// and the index is a local.
1773 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1775 impl<'tcx> Copy for PlaceElem<'tcx> {}
1777 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1778 #[cfg(target_arch = "x86_64")]
1779 static_assert_size!(PlaceElem<'_>, 16);
1781 /// Alias for projections as they appear in `UserTypeProjection`, where we
1782 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1783 pub type ProjectionKind = ProjectionElem<(), ()>;
1785 rustc_index::newtype_index! {
1788 DEBUG_FORMAT = "field[{}]"
1792 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1793 pub struct PlaceRef<'a, 'tcx> {
1794 pub base: &'a PlaceBase<'tcx>,
1795 pub projection: &'a [PlaceElem<'tcx>],
1798 impl<'tcx> Place<'tcx> {
1799 // FIXME change this to a const fn by also making List::empty a const fn.
1800 pub fn return_place() -> Place<'tcx> {
1801 Place { base: PlaceBase::Local(RETURN_PLACE), projection: List::empty() }
1804 /// Returns `true` if this `Place` contains a `Deref` projection.
1806 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1807 /// same region of memory as its base.
1808 pub fn is_indirect(&self) -> bool {
1809 self.projection.iter().any(|elem| elem.is_indirect())
1812 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1813 /// a single deref of a local.
1815 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1816 pub fn local_or_deref_local(&self) -> Option<Local> {
1817 match self.as_ref() {
1818 PlaceRef { base: &PlaceBase::Local(local), projection: &[] }
1819 | PlaceRef { base: &PlaceBase::Local(local), projection: &[ProjectionElem::Deref] } => {
1826 /// If this place represents a local variable like `_X` with no
1827 /// projections, return `Some(_X)`.
1828 pub fn as_local(&self) -> Option<Local> {
1829 self.as_ref().as_local()
1832 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1833 PlaceRef { base: &self.base, projection: &self.projection }
1837 impl From<Local> for Place<'_> {
1838 fn from(local: Local) -> Self {
1839 Place { base: local.into(), projection: List::empty() }
1843 impl From<Local> for PlaceBase<'_> {
1844 fn from(local: Local) -> Self {
1845 PlaceBase::Local(local)
1849 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1850 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1851 /// a single deref of a local.
1853 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1854 pub fn local_or_deref_local(&self) -> Option<Local> {
1856 PlaceRef { base: PlaceBase::Local(local), projection: [] }
1857 | PlaceRef { base: PlaceBase::Local(local), projection: [ProjectionElem::Deref] } => {
1864 /// If this place represents a local variable like `_X` with no
1865 /// projections, return `Some(_X)`.
1866 pub fn as_local(&self) -> Option<Local> {
1868 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1874 impl Debug for Place<'_> {
1875 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1876 for elem in self.projection.iter().rev() {
1878 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1879 write!(fmt, "(").unwrap();
1881 ProjectionElem::Deref => {
1882 write!(fmt, "(*").unwrap();
1884 ProjectionElem::Index(_)
1885 | ProjectionElem::ConstantIndex { .. }
1886 | ProjectionElem::Subslice { .. } => {}
1890 write!(fmt, "{:?}", self.base)?;
1892 for elem in self.projection.iter() {
1894 ProjectionElem::Downcast(Some(name), _index) => {
1895 write!(fmt, " as {})", name)?;
1897 ProjectionElem::Downcast(None, index) => {
1898 write!(fmt, " as variant#{:?})", index)?;
1900 ProjectionElem::Deref => {
1903 ProjectionElem::Field(field, ty) => {
1904 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1906 ProjectionElem::Index(ref index) => {
1907 write!(fmt, "[{:?}]", index)?;
1909 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1910 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1912 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1913 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1915 ProjectionElem::Subslice { from, to, from_end: true } if *to == 0 => {
1916 write!(fmt, "[{:?}:]", from)?;
1918 ProjectionElem::Subslice { from, to, from_end: true } if *from == 0 => {
1919 write!(fmt, "[:-{:?}]", to)?;
1921 ProjectionElem::Subslice { from, to, from_end: true } => {
1922 write!(fmt, "[{:?}:-{:?}]", from, to)?;
1924 ProjectionElem::Subslice { from, to, from_end: false } => {
1925 write!(fmt, "[{:?}..{:?}]", from, to)?;
1934 impl Debug for PlaceBase<'_> {
1935 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1937 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
1938 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
1939 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
1941 PlaceBase::Static(box self::Static {
1943 kind: StaticKind::Promoted(promoted, _),
1945 }) => write!(fmt, "({:?}: {:?})", promoted, ty),
1950 ///////////////////////////////////////////////////////////////////////////
1953 rustc_index::newtype_index! {
1954 pub struct SourceScope {
1956 DEBUG_FORMAT = "scope[{}]",
1957 const OUTERMOST_SOURCE_SCOPE = 0,
1961 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1962 pub struct SourceScopeData {
1964 pub parent_scope: Option<SourceScope>,
1966 /// Crate-local information for this source scope, that can't (and
1967 /// needn't) be tracked across crates.
1968 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
1971 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1972 pub struct SourceScopeLocalData {
1973 /// An `HirId` with lint levels equivalent to this scope's lint levels.
1974 pub lint_root: hir::HirId,
1975 /// The unsafe block that contains this node.
1979 ///////////////////////////////////////////////////////////////////////////
1982 /// These are values that can appear inside an rvalue. They are intentionally
1983 /// limited to prevent rvalues from being nested in one another.
1984 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
1985 pub enum Operand<'tcx> {
1986 /// Copy: The value must be available for use afterwards.
1988 /// This implies that the type of the place must be `Copy`; this is true
1989 /// by construction during build, but also checked by the MIR type checker.
1992 /// Move: The value (including old borrows of it) will not be used again.
1994 /// Safe for values of all types (modulo future developments towards `?Move`).
1995 /// Correct usage patterns are enforced by the borrow checker for safe code.
1996 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1999 /// Synthesizes a constant value.
2000 Constant(Box<Constant<'tcx>>),
2003 impl<'tcx> Debug for Operand<'tcx> {
2004 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2005 use self::Operand::*;
2007 Constant(ref a) => write!(fmt, "{:?}", a),
2008 Copy(ref place) => write!(fmt, "{:?}", place),
2009 Move(ref place) => write!(fmt, "move {:?}", place),
2014 impl<'tcx> Operand<'tcx> {
2015 /// Convenience helper to make a constant that refers to the fn
2016 /// with given `DefId` and substs. Since this is used to synthesize
2017 /// MIR, assumes `user_ty` is None.
2018 pub fn function_handle(
2021 substs: SubstsRef<'tcx>,
2024 let ty = tcx.type_of(def_id).subst(tcx, substs);
2025 Operand::Constant(box Constant {
2028 literal: ty::Const::zero_sized(tcx, ty),
2032 pub fn to_copy(&self) -> Self {
2034 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2035 Operand::Move(ref place) => Operand::Copy(place.clone()),
2040 ///////////////////////////////////////////////////////////////////////////
2043 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2044 pub enum Rvalue<'tcx> {
2045 /// x (either a move or copy, depending on type of x)
2049 Repeat(Operand<'tcx>, u64),
2052 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2054 /// Create a raw pointer to the given place
2055 /// Can be generated by raw address of expressions (`&raw const x`),
2056 /// or when casting a reference to a raw pointer.
2057 AddressOf(Mutability, Place<'tcx>),
2059 /// length of a [X] or [X;n] value
2062 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2064 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2065 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2067 NullaryOp(NullOp, Ty<'tcx>),
2068 UnaryOp(UnOp, Operand<'tcx>),
2070 /// Read the discriminant of an ADT.
2072 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2073 /// be defined to return, say, a 0) if ADT is not an enum.
2074 Discriminant(Place<'tcx>),
2076 /// Creates an aggregate value, like a tuple or struct. This is
2077 /// only needed because we want to distinguish `dest = Foo { x:
2078 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2079 /// that `Foo` has a destructor. These rvalues can be optimized
2080 /// away after type-checking and before lowering.
2081 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2084 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2087 Pointer(PointerCast),
2090 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2091 pub enum AggregateKind<'tcx> {
2092 /// The type is of the element
2096 /// The second field is the variant index. It's equal to 0 for struct
2097 /// and union expressions. The fourth field is
2098 /// active field number and is present only for union expressions
2099 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2100 /// active field index would identity the field `c`
2101 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2103 Closure(DefId, SubstsRef<'tcx>),
2104 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2107 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2109 /// The `+` operator (addition)
2111 /// The `-` operator (subtraction)
2113 /// The `*` operator (multiplication)
2115 /// The `/` operator (division)
2117 /// The `%` operator (modulus)
2119 /// The `^` operator (bitwise xor)
2121 /// The `&` operator (bitwise and)
2123 /// The `|` operator (bitwise or)
2125 /// The `<<` operator (shift left)
2127 /// The `>>` operator (shift right)
2129 /// The `==` operator (equality)
2131 /// The `<` operator (less than)
2133 /// The `<=` operator (less than or equal to)
2135 /// The `!=` operator (not equal to)
2137 /// The `>=` operator (greater than or equal to)
2139 /// The `>` operator (greater than)
2141 /// The `ptr.offset` operator
2146 pub fn is_checkable(self) -> bool {
2149 Add | Sub | Mul | Shl | Shr => true,
2155 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2157 /// Returns the size of a value of that type
2159 /// Creates a new uninitialized box for a value of that type
2163 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2165 /// The `!` operator for logical inversion
2167 /// The `-` operator for negation
2171 impl<'tcx> Debug for Rvalue<'tcx> {
2172 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2173 use self::Rvalue::*;
2176 Use(ref place) => write!(fmt, "{:?}", place),
2177 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2178 Len(ref a) => write!(fmt, "Len({:?})", a),
2179 Cast(ref kind, ref place, ref ty) => {
2180 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2182 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2183 CheckedBinaryOp(ref op, ref a, ref b) => {
2184 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2186 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2187 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2188 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2189 Ref(region, borrow_kind, ref place) => {
2190 let kind_str = match borrow_kind {
2191 BorrowKind::Shared => "",
2192 BorrowKind::Shallow => "shallow ",
2193 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2196 // When printing regions, add trailing space if necessary.
2197 let print_region = ty::tls::with(|tcx| {
2198 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2200 let region = if print_region {
2201 let mut region = region.to_string();
2202 if region.len() > 0 {
2207 // Do not even print 'static
2210 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2213 AddressOf(mutability, ref place) => {
2214 let kind_str = match mutability {
2215 Mutability::Mut => "mut",
2216 Mutability::Not => "const",
2219 write!(fmt, "&raw {} {:?}", kind_str, place)
2222 Aggregate(ref kind, ref places) => {
2223 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2224 let mut tuple_fmt = fmt.debug_tuple("");
2225 for place in places {
2226 tuple_fmt.field(place);
2232 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2234 AggregateKind::Tuple => match places.len() {
2235 0 => write!(fmt, "()"),
2236 1 => write!(fmt, "({:?},)", places[0]),
2237 _ => fmt_tuple(fmt, places),
2240 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2241 let variant_def = &adt_def.variants[variant];
2244 ty::tls::with(|tcx| {
2245 let substs = tcx.lift(&substs).expect("could not lift for printing");
2246 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2247 .print_def_path(variant_def.def_id, substs)?;
2251 match variant_def.ctor_kind {
2252 CtorKind::Const => Ok(()),
2253 CtorKind::Fn => fmt_tuple(fmt, places),
2254 CtorKind::Fictive => {
2255 let mut struct_fmt = fmt.debug_struct("");
2256 for (field, place) in variant_def.fields.iter().zip(places) {
2257 struct_fmt.field(&field.ident.as_str(), place);
2264 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2265 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2266 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2267 let substs = tcx.lift(&substs).unwrap();
2270 tcx.def_path_str_with_substs(def_id, substs),
2273 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2275 let mut struct_fmt = fmt.debug_struct(&name);
2277 if let Some(upvars) = tcx.upvars(def_id) {
2278 for (&var_id, place) in upvars.keys().zip(places) {
2279 let var_name = tcx.hir().name(var_id);
2280 struct_fmt.field(&var_name.as_str(), place);
2286 write!(fmt, "[closure]")
2290 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2291 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2292 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2293 let mut struct_fmt = fmt.debug_struct(&name);
2295 if let Some(upvars) = tcx.upvars(def_id) {
2296 for (&var_id, place) in upvars.keys().zip(places) {
2297 let var_name = tcx.hir().name(var_id);
2298 struct_fmt.field(&var_name.as_str(), place);
2304 write!(fmt, "[generator]")
2313 ///////////////////////////////////////////////////////////////////////////
2316 /// Two constants are equal if they are the same constant. Note that
2317 /// this does not necessarily mean that they are "==" in Rust -- in
2318 /// particular one must be wary of `NaN`!
2320 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2321 pub struct Constant<'tcx> {
2324 /// Optional user-given type: for something like
2325 /// `collect::<Vec<_>>`, this would be present and would
2326 /// indicate that `Vec<_>` was explicitly specified.
2328 /// Needed for NLL to impose user-given type constraints.
2329 pub user_ty: Option<UserTypeAnnotationIndex>,
2331 pub literal: &'tcx ty::Const<'tcx>,
2334 impl Constant<'tcx> {
2335 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2336 match self.literal.val.try_to_scalar() {
2337 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2338 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2341 tcx.sess.delay_span_bug(DUMMY_SP, "MIR cannot contain dangling const pointers");
2350 /// A collection of projections into user types.
2352 /// They are projections because a binding can occur a part of a
2353 /// parent pattern that has been ascribed a type.
2355 /// Its a collection because there can be multiple type ascriptions on
2356 /// the path from the root of the pattern down to the binding itself.
2361 /// struct S<'a>((i32, &'a str), String);
2362 /// let S((_, w): (i32, &'static str), _): S = ...;
2363 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2364 /// // --------------------------------- ^ (2)
2367 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2368 /// ascribed the type `(i32, &'static str)`.
2370 /// The highlights labelled `(2)` show the whole pattern being
2371 /// ascribed the type `S`.
2373 /// In this example, when we descend to `w`, we will have built up the
2374 /// following two projected types:
2376 /// * base: `S`, projection: `(base.0).1`
2377 /// * base: `(i32, &'static str)`, projection: `base.1`
2379 /// The first will lead to the constraint `w: &'1 str` (for some
2380 /// inferred region `'1`). The second will lead to the constraint `w:
2382 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2383 pub struct UserTypeProjections {
2384 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2387 impl<'tcx> UserTypeProjections {
2388 pub fn none() -> Self {
2389 UserTypeProjections { contents: vec![] }
2392 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2393 UserTypeProjections { contents: projs.collect() }
2396 pub fn projections_and_spans(
2398 ) -> impl Iterator<Item = &(UserTypeProjection, Span)> + ExactSizeIterator {
2399 self.contents.iter()
2402 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> + ExactSizeIterator {
2403 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2406 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2407 self.contents.push((user_ty.clone(), span));
2413 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2415 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2419 pub fn index(self) -> Self {
2420 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2423 pub fn subslice(self, from: u32, to: u32) -> Self {
2424 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2427 pub fn deref(self) -> Self {
2428 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2431 pub fn leaf(self, field: Field) -> Self {
2432 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2435 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2436 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2440 /// Encodes the effect of a user-supplied type annotation on the
2441 /// subcomponents of a pattern. The effect is determined by applying the
2442 /// given list of proejctions to some underlying base type. Often,
2443 /// the projection element list `projs` is empty, in which case this
2444 /// directly encodes a type in `base`. But in the case of complex patterns with
2445 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2446 /// in which case the `projs` vector is used.
2450 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2452 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2453 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2454 /// determined by finding the type of the `.0` field from `T`.
2455 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2456 pub struct UserTypeProjection {
2457 pub base: UserTypeAnnotationIndex,
2458 pub projs: Vec<ProjectionKind>,
2461 impl Copy for ProjectionKind {}
2463 impl UserTypeProjection {
2464 pub(crate) fn index(mut self) -> Self {
2465 self.projs.push(ProjectionElem::Index(()));
2469 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2470 self.projs.push(ProjectionElem::Subslice { from, to, from_end: true });
2474 pub(crate) fn deref(mut self) -> Self {
2475 self.projs.push(ProjectionElem::Deref);
2479 pub(crate) fn leaf(mut self, field: Field) -> Self {
2480 self.projs.push(ProjectionElem::Field(field, ()));
2484 pub(crate) fn variant(
2486 adt_def: &'tcx AdtDef,
2487 variant_index: VariantIdx,
2490 self.projs.push(ProjectionElem::Downcast(
2491 Some(adt_def.variants[variant_index].ident.name),
2494 self.projs.push(ProjectionElem::Field(field, ()));
2499 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2501 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2502 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2503 use crate::mir::ProjectionElem::*;
2505 let base = self.base.fold_with(folder);
2506 let projs: Vec<_> = self
2509 .map(|elem| match elem {
2511 Field(f, ()) => Field(f.clone(), ()),
2512 Index(()) => Index(()),
2513 elem => elem.clone(),
2517 UserTypeProjection { base, projs }
2520 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2521 self.base.visit_with(visitor)
2522 // Note: there's nothing in `self.proj` to visit.
2526 rustc_index::newtype_index! {
2527 pub struct Promoted {
2529 DEBUG_FORMAT = "promoted[{}]"
2533 impl<'tcx> Debug for Constant<'tcx> {
2534 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2535 write!(fmt, "{}", self)
2539 impl<'tcx> Display for Constant<'tcx> {
2540 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2541 write!(fmt, "const ")?;
2542 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2543 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2544 // detailed and just not '{pointer}'.
2545 if let ty::RawPtr(_) = self.literal.ty.kind {
2546 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2548 write!(fmt, "{}", self.literal)
2553 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2554 type Node = BasicBlock;
2557 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2558 fn num_nodes(&self) -> usize {
2559 self.basic_blocks.len()
2563 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2564 fn start_node(&self) -> Self::Node {
2569 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2570 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter {
2571 self.basic_blocks[node].terminator().successors().cloned()
2575 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2576 type Item = BasicBlock;
2577 type Iter = iter::Cloned<Successors<'b>>;
2580 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2581 pub struct Location {
2582 /// The block that the location is within.
2583 pub block: BasicBlock,
2585 /// The location is the position of the start of the statement; or, if
2586 /// `statement_index` equals the number of statements, then the start of the
2588 pub statement_index: usize,
2591 impl fmt::Debug for Location {
2592 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2593 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2598 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2600 /// Returns the location immediately after this one within the enclosing block.
2602 /// Note that if this location represents a terminator, then the
2603 /// resulting location would be out of bounds and invalid.
2604 pub fn successor_within_block(&self) -> Location {
2605 Location { block: self.block, statement_index: self.statement_index + 1 }
2608 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2609 pub fn is_predecessor_of<'tcx>(
2612 body: ReadOnlyBodyAndCache<'_, 'tcx>,
2614 // If we are in the same block as the other location and are an earlier statement
2615 // then we are a predecessor of `other`.
2616 if self.block == other.block && self.statement_index < other.statement_index {
2620 // If we're in another block, then we want to check that block is a predecessor of `other`.
2621 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).to_vec();
2622 let mut visited = FxHashSet::default();
2624 while let Some(block) = queue.pop() {
2625 // If we haven't visited this block before, then make sure we visit it's predecessors.
2626 if visited.insert(block) {
2627 queue.extend(body.predecessors_for(block).iter().cloned());
2632 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2633 // we found that block by looking at the predecessors of `other`).
2634 if self.block == block {
2642 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2643 if self.block == other.block {
2644 self.statement_index <= other.statement_index
2646 dominators.is_dominated_by(other.block, self.block)
2651 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2652 pub enum UnsafetyViolationKind {
2654 /// Permitted both in `const fn`s and regular `fn`s.
2656 BorrowPacked(hir::HirId),
2659 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2660 pub struct UnsafetyViolation {
2661 pub source_info: SourceInfo,
2662 pub description: Symbol,
2663 pub details: Symbol,
2664 pub kind: UnsafetyViolationKind,
2667 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2668 pub struct UnsafetyCheckResult {
2669 /// Violations that are propagated *upwards* from this function.
2670 pub violations: Lrc<[UnsafetyViolation]>,
2671 /// `unsafe` blocks in this function, along with whether they are used. This is
2672 /// used for the "unused_unsafe" lint.
2673 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2676 rustc_index::newtype_index! {
2677 pub struct GeneratorSavedLocal {
2679 DEBUG_FORMAT = "_{}",
2683 /// The layout of generator state.
2684 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2685 pub struct GeneratorLayout<'tcx> {
2686 /// The type of every local stored inside the generator.
2687 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2689 /// Which of the above fields are in each variant. Note that one field may
2690 /// be stored in multiple variants.
2691 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2693 /// Which saved locals are storage-live at the same time. Locals that do not
2694 /// have conflicts with each other are allowed to overlap in the computed
2696 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2699 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2700 pub struct BorrowCheckResult<'tcx> {
2701 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2702 pub used_mut_upvars: SmallVec<[Field; 8]>,
2705 /// The result of the `mir_const_qualif` query.
2707 /// Each field corresponds to an implementer of the `Qualif` trait in
2708 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2710 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2711 pub struct ConstQualifs {
2712 pub has_mut_interior: bool,
2713 pub needs_drop: bool,
2716 /// After we borrow check a closure, we are left with various
2717 /// requirements that we have inferred between the free regions that
2718 /// appear in the closure's signature or on its field types. These
2719 /// requirements are then verified and proved by the closure's
2720 /// creating function. This struct encodes those requirements.
2722 /// The requirements are listed as being between various
2723 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2724 /// vids refer to the free regions that appear in the closure (or
2725 /// generator's) type, in order of appearance. (This numbering is
2726 /// actually defined by the `UniversalRegions` struct in the NLL
2727 /// region checker. See for example
2728 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2729 /// regions in the closure's type "as if" they were erased, so their
2730 /// precise identity is not important, only their position.
2732 /// Example: If type check produces a closure with the closure substs:
2735 /// ClosureSubsts = [
2736 /// i8, // the "closure kind"
2737 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2738 /// &'a String, // some upvar
2742 /// here, there is one unique free region (`'a`) but it appears
2743 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2746 /// ClosureSubsts = [
2747 /// i8, // the "closure kind"
2748 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2749 /// &'2 String, // some upvar
2753 /// Now the code might impose a requirement like `'1: '2`. When an
2754 /// instance of the closure is created, the corresponding free regions
2755 /// can be extracted from its type and constrained to have the given
2756 /// outlives relationship.
2758 /// In some cases, we have to record outlives requirements between
2759 /// types and regions as well. In that case, if those types include
2760 /// any regions, those regions are recorded as `ReClosureBound`
2761 /// instances assigned one of these same indices. Those regions will
2762 /// be substituted away by the creator. We use `ReClosureBound` in
2763 /// that case because the regions must be allocated in the global
2764 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2765 /// internally within the rest of the NLL code).
2766 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2767 pub struct ClosureRegionRequirements<'tcx> {
2768 /// The number of external regions defined on the closure. In our
2769 /// example above, it would be 3 -- one for `'static`, then `'1`
2770 /// and `'2`. This is just used for a sanity check later on, to
2771 /// make sure that the number of regions we see at the callsite
2773 pub num_external_vids: usize,
2775 /// Requirements between the various free regions defined in
2777 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2780 /// Indicates an outlives-constraint between a type or between two
2781 /// free regions declared on the closure.
2782 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2783 pub struct ClosureOutlivesRequirement<'tcx> {
2784 // This region or type ...
2785 pub subject: ClosureOutlivesSubject<'tcx>,
2787 // ... must outlive this one.
2788 pub outlived_free_region: ty::RegionVid,
2790 // If not, report an error here ...
2791 pub blame_span: Span,
2793 // ... due to this reason.
2794 pub category: ConstraintCategory,
2797 /// Outlives-constraints can be categorized to determine whether and why they
2798 /// are interesting (for error reporting). Order of variants indicates sort
2799 /// order of the category, thereby influencing diagnostic output.
2801 /// See also [rustc_mir::borrow_check::nll::constraints].
2815 pub enum ConstraintCategory {
2823 /// A constraint that came from checking the body of a closure.
2825 /// We try to get the category that the closure used when reporting this.
2833 /// A "boring" constraint (caused by the given location) is one that
2834 /// the user probably doesn't want to see described in diagnostics,
2835 /// because it is kind of an artifact of the type system setup.
2836 /// Example: `x = Foo { field: y }` technically creates
2837 /// intermediate regions representing the "type of `Foo { field: y
2838 /// }`", and data flows from `y` into those variables, but they
2839 /// are not very interesting. The assignment into `x` on the other
2842 // Boring and applicable everywhere.
2845 /// A constraint that doesn't correspond to anything the user sees.
2849 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2850 /// that must outlive some region.
2851 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2852 pub enum ClosureOutlivesSubject<'tcx> {
2853 /// Subject is a type, typically a type parameter, but could also
2854 /// be a projection. Indicates a requirement like `T: 'a` being
2855 /// passed to the caller, where the type here is `T`.
2857 /// The type here is guaranteed not to contain any free regions at
2861 /// Subject is a free region from the closure. Indicates a requirement
2862 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2863 Region(ty::RegionVid),
2867 * `TypeFoldable` implementations for MIR types
2870 CloneTypeFoldableAndLiftImpls! {
2878 SourceScopeLocalData,
2879 UserTypeAnnotationIndex,
2882 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2883 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2884 use crate::mir::TerminatorKind::*;
2886 let kind = match self.kind {
2887 Goto { target } => Goto { target },
2888 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2889 discr: discr.fold_with(folder),
2890 switch_ty: switch_ty.fold_with(folder),
2891 values: values.clone(),
2892 targets: targets.clone(),
2894 Drop { ref location, target, unwind } => {
2895 Drop { location: location.fold_with(folder), target, unwind }
2897 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2898 location: location.fold_with(folder),
2899 value: value.fold_with(folder),
2903 Yield { ref value, resume, drop } => {
2904 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
2906 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
2908 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2911 func: func.fold_with(folder),
2912 args: args.fold_with(folder),
2918 Assert { ref cond, expected, ref msg, target, cleanup } => {
2920 let msg = match msg {
2921 BoundsCheck { ref len, ref index } => {
2922 BoundsCheck { len: len.fold_with(folder), index: index.fold_with(folder) }
2929 | ResumedAfterReturn(_)
2930 | ResumedAfterPanic(_) => msg.clone(),
2932 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
2934 GeneratorDrop => GeneratorDrop,
2938 Unreachable => Unreachable,
2939 FalseEdges { real_target, imaginary_target } => {
2940 FalseEdges { real_target, imaginary_target }
2942 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
2944 Terminator { source_info: self.source_info, kind }
2947 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2948 use crate::mir::TerminatorKind::*;
2951 SwitchInt { ref discr, switch_ty, .. } => {
2952 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
2954 Drop { ref location, .. } => location.visit_with(visitor),
2955 DropAndReplace { ref location, ref value, .. } => {
2956 location.visit_with(visitor) || value.visit_with(visitor)
2958 Yield { ref value, .. } => value.visit_with(visitor),
2959 Call { ref func, ref args, ref destination, .. } => {
2960 let dest = if let Some((ref loc, _)) = *destination {
2961 loc.visit_with(visitor)
2965 dest || func.visit_with(visitor) || args.visit_with(visitor)
2967 Assert { ref cond, ref msg, .. } => {
2968 if cond.visit_with(visitor) {
2971 BoundsCheck { ref len, ref index } => {
2972 len.visit_with(visitor) || index.visit_with(visitor)
2979 | ResumedAfterReturn(_)
2980 | ResumedAfterPanic(_) => false,
2993 | FalseUnwind { .. } => false,
2998 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
2999 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3003 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3008 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3009 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3010 Place { base: self.base.fold_with(folder), projection: self.projection.fold_with(folder) }
3013 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3014 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3018 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3019 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3021 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3022 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3026 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3028 PlaceBase::Local(local) => local.visit_with(visitor),
3029 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3034 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3035 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3036 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3037 folder.tcx().intern_place_elems(&v)
3040 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3041 self.iter().any(|t| t.visit_with(visitor))
3045 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3046 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3048 ty: self.ty.fold_with(folder),
3049 kind: self.kind.fold_with(folder),
3050 def_id: self.def_id,
3054 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3055 let Static { ty, kind, def_id: _ } = self;
3057 ty.visit_with(visitor) || kind.visit_with(visitor)
3061 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3062 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3064 StaticKind::Promoted(promoted, substs) => {
3065 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder))
3067 StaticKind::Static => StaticKind::Static,
3071 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3073 StaticKind::Promoted(promoted, substs) => {
3074 promoted.visit_with(visitor) || substs.visit_with(visitor)
3076 StaticKind::Static => false,
3081 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3082 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3083 use crate::mir::Rvalue::*;
3085 Use(ref op) => Use(op.fold_with(folder)),
3086 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3087 Ref(region, bk, ref place) => {
3088 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3090 AddressOf(mutability, ref place) => AddressOf(mutability, place.fold_with(folder)),
3091 Len(ref place) => Len(place.fold_with(folder)),
3092 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3093 BinaryOp(op, ref rhs, ref lhs) => {
3094 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3096 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3097 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3099 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3100 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3101 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3102 Aggregate(ref kind, ref fields) => {
3103 let kind = box match **kind {
3104 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3105 AggregateKind::Tuple => AggregateKind::Tuple,
3106 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3109 substs.fold_with(folder),
3110 user_ty.fold_with(folder),
3113 AggregateKind::Closure(id, substs) => {
3114 AggregateKind::Closure(id, substs.fold_with(folder))
3116 AggregateKind::Generator(id, substs, movablity) => {
3117 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3120 Aggregate(kind, fields.fold_with(folder))
3125 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3126 use crate::mir::Rvalue::*;
3128 Use(ref op) => op.visit_with(visitor),
3129 Repeat(ref op, _) => op.visit_with(visitor),
3130 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3131 AddressOf(_, ref place) => place.visit_with(visitor),
3132 Len(ref place) => place.visit_with(visitor),
3133 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3134 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3135 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3137 UnaryOp(_, ref val) => val.visit_with(visitor),
3138 Discriminant(ref place) => place.visit_with(visitor),
3139 NullaryOp(_, ty) => ty.visit_with(visitor),
3140 Aggregate(ref kind, ref fields) => {
3142 AggregateKind::Array(ty) => ty.visit_with(visitor),
3143 AggregateKind::Tuple => false,
3144 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3145 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3147 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3148 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3149 }) || fields.visit_with(visitor)
3155 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3156 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3158 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3159 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3160 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3164 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3166 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3167 Operand::Constant(ref c) => c.visit_with(visitor),
3172 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3173 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3174 use crate::mir::ProjectionElem::*;
3178 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3179 Index(v) => Index(v.fold_with(folder)),
3180 elem => elem.clone(),
3184 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3185 use crate::mir::ProjectionElem::*;
3188 Field(_, ty) => ty.visit_with(visitor),
3189 Index(v) => v.visit_with(visitor),
3195 impl<'tcx> TypeFoldable<'tcx> for Field {
3196 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3199 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3204 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3205 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3208 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3213 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3214 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3217 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3222 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3223 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3225 span: self.span.clone(),
3226 user_ty: self.user_ty.fold_with(folder),
3227 literal: self.literal.fold_with(folder),
3230 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3231 self.literal.visit_with(visitor)