1 // ignore-tidy-filelength
3 //! MIR datatypes and passes. See the [rustc guide] for more info.
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/mir/index.html
7 use crate::hir::def::{CtorKind, Namespace};
8 use crate::hir::def_id::DefId;
9 use crate::hir::{self, GeneratorKind};
10 use crate::mir::interpret::{GlobalAlloc, PanicInfo, Scalar};
11 use crate::mir::visit::MirVisitable;
12 use crate::ty::adjustment::PointerCast;
13 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
14 use crate::ty::layout::VariantIdx;
15 use crate::ty::print::{FmtPrinter, Printer};
16 use crate::ty::subst::{Subst, SubstsRef};
18 self, AdtDef, CanonicalUserTypeAnnotations, List, Region, Ty, TyCtxt, UserTypeAnnotationIndex,
21 use polonius_engine::Atom;
22 use rustc_index::bit_set::BitMatrix;
23 use rustc_data_structures::fx::FxHashSet;
24 use rustc_data_structures::graph::dominators::{dominators, Dominators};
25 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_data_structures::sync::Lrc;
28 use rustc_data_structures::sync::MappedReadGuard;
29 use rustc_macros::HashStable;
30 use rustc_serialize::{Encodable, Decodable};
31 use smallvec::SmallVec;
33 use std::fmt::{self, Debug, Display, Formatter, Write};
34 use std::ops::{Index, IndexMut};
36 use std::vec::IntoIter;
37 use std::{iter, mem, option, u32};
38 use syntax::ast::Name;
39 use syntax::symbol::Symbol;
40 use syntax_pos::{Span, DUMMY_SP};
42 pub use crate::mir::interpret::AssertMessage;
52 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
54 pub trait HasLocalDecls<'tcx> {
55 fn local_decls(&self) -> &LocalDecls<'tcx>;
58 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
59 fn local_decls(&self) -> &LocalDecls<'tcx> {
64 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
65 fn local_decls(&self) -> &LocalDecls<'tcx> {
70 /// The various "big phases" that MIR goes through.
72 /// Warning: ordering of variants is significant.
73 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable,
74 Debug, PartialEq, Eq, PartialOrd, Ord)]
83 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
84 pub fn phase_index(&self) -> usize {
89 /// The lowered representation of a single function.
90 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
91 pub struct Body<'tcx> {
92 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
93 /// that indexes into this vector.
94 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
96 /// Records how far through the "desugaring and optimization" process this particular
97 /// MIR has traversed. This is particularly useful when inlining, since in that context
98 /// we instantiate the promoted constants and add them to our promoted vector -- but those
99 /// promoted items have already been optimized, whereas ours have not. This field allows
100 /// us to see the difference and forego optimization on the inlined promoted items.
103 /// A list of source scopes; these are referenced by statements
104 /// and used for debuginfo. Indexed by a `SourceScope`.
105 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
107 /// The yield type of the function, if it is a generator.
108 pub yield_ty: Option<Ty<'tcx>>,
110 /// Generator drop glue.
111 pub generator_drop: Option<Box<Body<'tcx>>>,
113 /// The layout of a generator. Produced by the state transformation.
114 pub generator_layout: Option<GeneratorLayout<'tcx>>,
116 /// If this is a generator then record the type of source expression that caused this generator
118 pub generator_kind: Option<GeneratorKind>,
120 /// Declarations of locals.
122 /// The first local is the return value pointer, followed by `arg_count`
123 /// locals for the function arguments, followed by any user-declared
124 /// variables and temporaries.
125 pub local_decls: LocalDecls<'tcx>,
127 /// User type annotations.
128 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
130 /// The number of arguments this function takes.
132 /// Starting at local 1, `arg_count` locals will be provided by the caller
133 /// and can be assumed to be initialized.
135 /// If this MIR was built for a constant, this will be 0.
136 pub arg_count: usize,
138 /// Mark an argument local (which must be a tuple) as getting passed as
139 /// its individual components at the LLVM level.
141 /// This is used for the "rust-call" ABI.
142 pub spread_arg: Option<Local>,
144 /// Debug information pertaining to user variables, including captures.
145 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
147 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
148 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
149 /// this conversion from happening and use short circuiting, we will cause the following code
150 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
152 /// List of places where control flow was destroyed. Used for error reporting.
153 pub control_flow_destroyed: Vec<(Span, String)>,
155 /// A span representing this MIR, for error reporting.
158 /// A cache for various calculations.
162 impl<'tcx> Body<'tcx> {
164 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
165 source_scopes: IndexVec<SourceScope, SourceScopeData>,
166 local_decls: LocalDecls<'tcx>,
167 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
169 var_debug_info: Vec<VarDebugInfo<'tcx>>,
171 control_flow_destroyed: Vec<(Span, String)>,
172 generator_kind : Option<GeneratorKind>,
174 // We need `arg_count` locals, and one for the return place.
176 local_decls.len() >= arg_count + 1,
177 "expected at least {} locals, got {}",
183 phase: MirPhase::Build,
187 generator_drop: None,
188 generator_layout: None,
191 user_type_annotations,
196 cache: cache::Cache::new(),
197 control_flow_destroyed,
202 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
207 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
208 self.cache.invalidate();
209 &mut self.basic_blocks
213 pub fn basic_blocks_and_local_decls_mut(
215 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
216 self.cache.invalidate();
217 (&mut self.basic_blocks, &mut self.local_decls)
221 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
222 self.cache.predecessors(self)
226 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
227 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
231 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
232 let if_zero_locations = if loc.statement_index == 0 {
233 let predecessor_blocks = self.predecessors_for(loc.block);
234 let num_predecessor_blocks = predecessor_blocks.len();
236 (0..num_predecessor_blocks)
237 .map(move |i| predecessor_blocks[i])
238 .map(move |bb| self.terminator_loc(bb)),
244 let if_not_zero_locations = if loc.statement_index == 0 {
247 Some(Location { block: loc.block, statement_index: loc.statement_index - 1 })
250 if_zero_locations.into_iter().flatten().chain(if_not_zero_locations)
254 pub fn dominators(&self) -> Dominators<BasicBlock> {
258 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
260 pub fn is_cfg_cyclic(&self) -> bool {
261 graph::is_cyclic(self)
265 pub fn local_kind(&self, local: Local) -> LocalKind {
266 let index = local.as_usize();
269 self.local_decls[local].mutability == Mutability::Mut,
270 "return place should be mutable"
273 LocalKind::ReturnPointer
274 } else if index < self.arg_count + 1 {
276 } else if self.local_decls[local].is_user_variable() {
283 /// Returns an iterator over all temporaries.
285 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
286 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
287 let local = Local::new(index);
288 if self.local_decls[local].is_user_variable() {
296 /// Returns an iterator over all user-declared locals.
298 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
299 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
300 let local = Local::new(index);
301 if self.local_decls[local].is_user_variable() {
309 /// Returns an iterator over all user-declared mutable locals.
311 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
312 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
313 let local = Local::new(index);
314 let decl = &self.local_decls[local];
315 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
323 /// Returns an iterator over all user-declared mutable arguments and locals.
325 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
326 (1..self.local_decls.len()).filter_map(move |index| {
327 let local = Local::new(index);
328 let decl = &self.local_decls[local];
329 if (decl.is_user_variable() || index < self.arg_count + 1)
330 && decl.mutability == Mutability::Mut
339 /// Returns an iterator over all function arguments.
341 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
342 let arg_count = self.arg_count;
343 (1..=arg_count).map(Local::new)
346 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
347 /// locals that are neither arguments nor the return place).
349 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
350 let arg_count = self.arg_count;
351 let local_count = self.local_decls.len();
352 (arg_count + 1..local_count).map(Local::new)
355 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
356 /// invalidating statement indices in `Location`s.
357 pub fn make_statement_nop(&mut self, location: Location) {
358 let block = &mut self[location.block];
359 debug_assert!(location.statement_index < block.statements.len());
360 block.statements[location.statement_index].make_nop()
363 /// Returns the source info associated with `location`.
364 pub fn source_info(&self, location: Location) -> &SourceInfo {
365 let block = &self[location.block];
366 let stmts = &block.statements;
367 let idx = location.statement_index;
368 if idx < stmts.len() {
369 &stmts[idx].source_info
371 assert_eq!(idx, stmts.len());
372 &block.terminator().source_info
376 /// Checks if `sub` is a sub scope of `sup`
377 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
379 match self.source_scopes[sub].parent_scope {
380 None => return false,
387 /// Returns the return type; it always return first element from `local_decls` array.
388 pub fn return_ty(&self) -> Ty<'tcx> {
389 self.local_decls[RETURN_PLACE].ty
392 /// Gets the location of the terminator for the given block.
393 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
394 Location { block: bb, statement_index: self[bb].statements.len() }
398 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
401 /// Unsafe because of a PushUnsafeBlock
403 /// Unsafe because of an unsafe fn
405 /// Unsafe because of an `unsafe` block
406 ExplicitUnsafe(hir::HirId),
409 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
410 type Output = BasicBlockData<'tcx>;
413 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
414 &self.basic_blocks()[index]
418 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
420 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
421 &mut self.basic_blocks_mut()[index]
425 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
426 pub enum ClearCrossCrate<T> {
431 impl<T> ClearCrossCrate<T> {
432 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
434 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
435 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
439 pub fn assert_crate_local(self) -> T {
441 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
442 ClearCrossCrate::Set(v) => v,
447 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
448 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
450 /// Grouped information about the source code origin of a MIR entity.
451 /// Intended to be inspected by diagnostics and debuginfo.
452 /// Most passes can work with it as a whole, within a single function.
453 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
454 // `Hash`. Please ping @bjorn3 if removing them.
455 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
456 pub struct SourceInfo {
457 /// The source span for the AST pertaining to this MIR entity.
460 /// The source scope, keeping track of which bindings can be
461 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
462 pub scope: SourceScope,
465 ///////////////////////////////////////////////////////////////////////////
466 // Mutability and borrow kinds
468 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
469 pub enum Mutability {
474 impl From<Mutability> for hir::Mutability {
475 fn from(m: Mutability) -> Self {
477 Mutability::Mut => hir::Mutability::Mutable,
478 Mutability::Not => hir::Mutability::Immutable,
484 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
486 pub enum BorrowKind {
487 /// Data must be immutable and is aliasable.
490 /// The immediately borrowed place must be immutable, but projections from
491 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
492 /// conflict with a mutable borrow of `a.b.c`.
494 /// This is used when lowering matches: when matching on a place we want to
495 /// ensure that place have the same value from the start of the match until
496 /// an arm is selected. This prevents this code from compiling:
498 /// let mut x = &Some(0);
501 /// Some(_) if { x = &None; false } => (),
505 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
506 /// should not prevent `if let None = x { ... }`, for example, because the
507 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
508 /// We can also report errors with this kind of borrow differently.
511 /// Data must be immutable but not aliasable. This kind of borrow
512 /// cannot currently be expressed by the user and is used only in
513 /// implicit closure bindings. It is needed when the closure is
514 /// borrowing or mutating a mutable referent, e.g.:
516 /// let x: &mut isize = ...;
517 /// let y = || *x += 5;
519 /// If we were to try to translate this closure into a more explicit
520 /// form, we'd encounter an error with the code as written:
522 /// struct Env { x: & &mut isize }
523 /// let x: &mut isize = ...;
524 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
525 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
527 /// This is then illegal because you cannot mutate an `&mut` found
528 /// in an aliasable location. To solve, you'd have to translate with
529 /// an `&mut` borrow:
531 /// struct Env { x: & &mut isize }
532 /// let x: &mut isize = ...;
533 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
534 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
536 /// Now the assignment to `**env.x` is legal, but creating a
537 /// mutable pointer to `x` is not because `x` is not mutable. We
538 /// could fix this by declaring `x` as `let mut x`. This is ok in
539 /// user code, if awkward, but extra weird for closures, since the
540 /// borrow is hidden.
542 /// So we introduce a "unique imm" borrow -- the referent is
543 /// immutable, but not aliasable. This solves the problem. For
544 /// simplicity, we don't give users the way to express this
545 /// borrow, it's just used when translating closures.
548 /// Data is mutable and not aliasable.
550 /// `true` if this borrow arose from method-call auto-ref
551 /// (i.e., `adjustment::Adjust::Borrow`).
552 allow_two_phase_borrow: bool,
557 pub fn allows_two_phase_borrow(&self) -> bool {
559 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
560 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
565 ///////////////////////////////////////////////////////////////////////////
566 // Variables and temps
568 rustc_index::newtype_index! {
571 DEBUG_FORMAT = "_{}",
572 const RETURN_PLACE = 0,
576 impl Atom for Local {
577 fn index(self) -> usize {
582 /// Classifies locals into categories. See `Body::local_kind`.
583 #[derive(PartialEq, Eq, Debug, HashStable)]
585 /// User-declared variable binding.
587 /// Compiler-introduced temporary.
589 /// Function argument.
591 /// Location of function's return value.
595 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
596 pub struct VarBindingForm<'tcx> {
597 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
598 pub binding_mode: ty::BindingMode,
599 /// If an explicit type was provided for this variable binding,
600 /// this holds the source Span of that type.
602 /// NOTE: if you want to change this to a `HirId`, be wary that
603 /// doing so breaks incremental compilation (as of this writing),
604 /// while a `Span` does not cause our tests to fail.
605 pub opt_ty_info: Option<Span>,
606 /// Place of the RHS of the =, or the subject of the `match` where this
607 /// variable is initialized. None in the case of `let PATTERN;`.
608 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
609 /// (a) the right-hand side isn't evaluated as a place expression.
610 /// (b) it gives a way to separate this case from the remaining cases
612 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
613 /// The span of the pattern in which this variable was bound.
617 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
618 pub enum BindingForm<'tcx> {
619 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
620 Var(VarBindingForm<'tcx>),
621 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
622 ImplicitSelf(ImplicitSelfKind),
623 /// Reference used in a guard expression to ensure immutability.
627 /// Represents what type of implicit self a function has, if any.
628 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
629 pub enum ImplicitSelfKind {
630 /// Represents a `fn x(self);`.
632 /// Represents a `fn x(mut self);`.
634 /// Represents a `fn x(&self);`.
636 /// Represents a `fn x(&mut self);`.
638 /// Represents when a function does not have a self argument or
639 /// when a function has a `self: X` argument.
643 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
645 mod binding_form_impl {
646 use crate::ich::StableHashingContext;
647 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
649 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
650 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
651 use super::BindingForm::*;
652 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
655 Var(binding) => binding.hash_stable(hcx, hasher),
656 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
663 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
664 /// created during evaluation of expressions in a block tail
665 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
667 /// It is used to improve diagnostics when such temporaries are
668 /// involved in borrow_check errors, e.g., explanations of where the
669 /// temporaries come from, when their destructors are run, and/or how
670 /// one might revise the code to satisfy the borrow checker's rules.
671 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
672 pub struct BlockTailInfo {
673 /// If `true`, then the value resulting from evaluating this tail
674 /// expression is ignored by the block's expression context.
676 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
677 /// but not e.g., `let _x = { ...; tail };`
678 pub tail_result_is_ignored: bool,
683 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
684 /// argument, or the return place.
685 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
686 pub struct LocalDecl<'tcx> {
687 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
689 /// Temporaries and the return place are always mutable.
690 pub mutability: Mutability,
692 // FIXME(matthewjasper) Don't store in this in `Body`
693 pub local_info: LocalInfo<'tcx>,
695 /// `true` if this is an internal local.
697 /// These locals are not based on types in the source code and are only used
698 /// for a few desugarings at the moment.
700 /// The generator transformation will sanity check the locals which are live
701 /// across a suspension point against the type components of the generator
702 /// which type checking knows are live across a suspension point. We need to
703 /// flag drop flags to avoid triggering this check as they are introduced
706 /// Unsafety checking will also ignore dereferences of these locals,
707 /// so they can be used for raw pointers only used in a desugaring.
709 /// This should be sound because the drop flags are fully algebraic, and
710 /// therefore don't affect the OIBIT or outlives properties of the
714 /// If this local is a temporary and `is_block_tail` is `Some`,
715 /// then it is a temporary created for evaluation of some
716 /// subexpression of some block's tail expression (with no
717 /// intervening statement context).
718 // FIXME(matthewjasper) Don't store in this in `Body`
719 pub is_block_tail: Option<BlockTailInfo>,
721 /// The type of this local.
724 /// If the user manually ascribed a type to this variable,
725 /// e.g., via `let x: T`, then we carry that type here. The MIR
726 /// borrow checker needs this information since it can affect
727 /// region inference.
728 // FIXME(matthewjasper) Don't store in this in `Body`
729 pub user_ty: UserTypeProjections,
731 /// The *syntactic* (i.e., not visibility) source scope the local is defined
732 /// in. If the local was defined in a let-statement, this
733 /// is *within* the let-statement, rather than outside
736 /// This is needed because the visibility source scope of locals within
737 /// a let-statement is weird.
739 /// The reason is that we want the local to be *within* the let-statement
740 /// for lint purposes, but we want the local to be *after* the let-statement
741 /// for names-in-scope purposes.
743 /// That's it, if we have a let-statement like the one in this
747 /// fn foo(x: &str) {
748 /// #[allow(unused_mut)]
749 /// let mut x: u32 = { // <- one unused mut
750 /// let mut y: u32 = x.parse().unwrap();
757 /// Then, from a lint point of view, the declaration of `x: u32`
758 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
759 /// lint scopes are the same as the AST/HIR nesting.
761 /// However, from a name lookup point of view, the scopes look more like
762 /// as if the let-statements were `match` expressions:
765 /// fn foo(x: &str) {
767 /// match x.parse().unwrap() {
776 /// We care about the name-lookup scopes for debuginfo - if the
777 /// debuginfo instruction pointer is at the call to `x.parse()`, we
778 /// want `x` to refer to `x: &str`, but if it is at the call to
779 /// `drop(x)`, we want it to refer to `x: u32`.
781 /// To allow both uses to work, we need to have more than a single scope
782 /// for a local. We have the `source_info.scope` represent the "syntactic"
783 /// lint scope (with a variable being under its let block) while the
784 /// `var_debug_info.source_info.scope` represents the "local variable"
785 /// scope (where the "rest" of a block is under all prior let-statements).
787 /// The end result looks like this:
791 /// │{ argument x: &str }
793 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
794 /// │ │ // in practice because I'm lazy.
796 /// │ │← x.source_info.scope
797 /// │ │← `x.parse().unwrap()`
799 /// │ │ │← y.source_info.scope
801 /// │ │ │{ let y: u32 }
803 /// │ │ │← y.var_debug_info.source_info.scope
806 /// │ │{ let x: u32 }
807 /// │ │← x.var_debug_info.source_info.scope
808 /// │ │← `drop(x)` // This accesses `x: u32`.
810 pub source_info: SourceInfo,
813 /// Extra information about a local that's used for diagnostics.
814 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
815 pub enum LocalInfo<'tcx> {
816 /// A user-defined local variable or function parameter
818 /// The `BindingForm` is solely used for local diagnostics when generating
819 /// warnings/errors when compiling the current crate, and therefore it need
820 /// not be visible across crates.
821 User(ClearCrossCrate<BindingForm<'tcx>>),
822 /// A temporary created that references the static with the given `DefId`.
823 StaticRef { def_id: DefId, is_thread_local: bool },
824 /// Any other temporary, the return place, or an anonymous function parameter.
828 impl<'tcx> LocalDecl<'tcx> {
829 /// Returns `true` only if local is a binding that can itself be
830 /// made mutable via the addition of the `mut` keyword, namely
831 /// something like the occurrences of `x` in:
832 /// - `fn foo(x: Type) { ... }`,
834 /// - or `match ... { C(x) => ... }`
835 pub fn can_be_made_mutable(&self) -> bool {
836 match self.local_info {
837 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
838 binding_mode: ty::BindingMode::BindByValue(_),
845 ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)),
852 /// Returns `true` if local is definitely not a `ref ident` or
853 /// `ref mut ident` binding. (Such bindings cannot be made into
854 /// mutable bindings, but the inverse does not necessarily hold).
855 pub fn is_nonref_binding(&self) -> bool {
856 match self.local_info {
857 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
858 binding_mode: ty::BindingMode::BindByValue(_),
864 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
870 /// Returns `true` if this variable is a named variable or function
871 /// parameter declared by the user.
873 pub fn is_user_variable(&self) -> bool {
874 match self.local_info {
875 LocalInfo::User(_) => true,
880 /// Returns `true` if this is a reference to a variable bound in a `match`
881 /// expression that is used to access said variable for the guard of the
883 pub fn is_ref_for_guard(&self) -> bool {
884 match self.local_info {
885 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
890 /// Returns `Some` if this is a reference to a static item that is used to
891 /// access that static
892 pub fn is_ref_to_static(&self) -> bool {
893 match self.local_info {
894 LocalInfo::StaticRef { .. } => true,
899 /// Returns `Some` if this is a reference to a static item that is used to
900 /// access that static
901 pub fn is_ref_to_thread_local(&self) -> bool {
902 match self.local_info {
903 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
908 /// Returns `true` is the local is from a compiler desugaring, e.g.,
909 /// `__next` from a `for` loop.
911 pub fn from_compiler_desugaring(&self) -> bool {
912 self.source_info.span.desugaring_kind().is_some()
915 /// Creates a new `LocalDecl` for a temporary.
917 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
918 Self::new_local(ty, Mutability::Mut, false, span)
921 /// Converts `self` into same `LocalDecl` except tagged as immutable.
923 pub fn immutable(mut self) -> Self {
924 self.mutability = Mutability::Not;
928 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
930 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
931 assert!(self.is_block_tail.is_none());
932 self.is_block_tail = Some(info);
936 /// Creates a new `LocalDecl` for a internal temporary.
938 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
939 Self::new_local(ty, Mutability::Mut, true, span)
943 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
947 user_ty: UserTypeProjections::none(),
948 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
950 local_info: LocalInfo::Other,
955 /// Builds a `LocalDecl` for the return place.
957 /// This must be inserted into the `local_decls` list as the first local.
959 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
961 mutability: Mutability::Mut,
963 user_ty: UserTypeProjections::none(),
964 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
967 local_info: LocalInfo::Other,
972 /// Debug information pertaining to a user variable.
973 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
974 pub struct VarDebugInfo<'tcx> {
977 /// Source info of the user variable, including the scope
978 /// within which the variable is visible (to debuginfo)
979 /// (see `LocalDecl`'s `source_info` field for more details).
980 pub source_info: SourceInfo,
982 /// Where the data for this user variable is to be found.
983 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
984 /// based on a `Local`, not a `Static`, and contains no indexing.
985 pub place: Place<'tcx>,
988 ///////////////////////////////////////////////////////////////////////////
991 rustc_index::newtype_index! {
992 pub struct BasicBlock {
994 DEBUG_FORMAT = "bb{}",
995 const START_BLOCK = 0,
1000 pub fn start_location(self) -> Location {
1001 Location { block: self, statement_index: 0 }
1005 ///////////////////////////////////////////////////////////////////////////
1006 // BasicBlockData and Terminator
1008 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1009 pub struct BasicBlockData<'tcx> {
1010 /// List of statements in this block.
1011 pub statements: Vec<Statement<'tcx>>,
1013 /// Terminator for this block.
1015 /// N.B., this should generally ONLY be `None` during construction.
1016 /// Therefore, you should generally access it via the
1017 /// `terminator()` or `terminator_mut()` methods. The only
1018 /// exception is that certain passes, such as `simplify_cfg`, swap
1019 /// out the terminator temporarily with `None` while they continue
1020 /// to recurse over the set of basic blocks.
1021 pub terminator: Option<Terminator<'tcx>>,
1023 /// If true, this block lies on an unwind path. This is used
1024 /// during codegen where distinct kinds of basic blocks may be
1025 /// generated (particularly for MSVC cleanup). Unwind blocks must
1026 /// only branch to other unwind blocks.
1027 pub is_cleanup: bool,
1030 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1031 pub struct Terminator<'tcx> {
1032 pub source_info: SourceInfo,
1033 pub kind: TerminatorKind<'tcx>,
1036 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1037 pub enum TerminatorKind<'tcx> {
1038 /// Block should have one successor in the graph; we jump there.
1039 Goto { target: BasicBlock },
1041 /// Operand evaluates to an integer; jump depending on its value
1042 /// to one of the targets, and otherwise fallback to `otherwise`.
1044 /// The discriminant value being tested.
1045 discr: Operand<'tcx>,
1047 /// The type of value being tested.
1048 switch_ty: Ty<'tcx>,
1050 /// Possible values. The locations to branch to in each case
1051 /// are found in the corresponding indices from the `targets` vector.
1052 values: Cow<'tcx, [u128]>,
1054 /// Possible branch sites. The last element of this vector is used
1055 /// for the otherwise branch, so targets.len() == values.len() + 1
1058 // This invariant is quite non-obvious and also could be improved.
1059 // One way to make this invariant is to have something like this instead:
1061 // branches: Vec<(ConstInt, BasicBlock)>,
1062 // otherwise: Option<BasicBlock> // exhaustive if None
1064 // However we’ve decided to keep this as-is until we figure a case
1065 // where some other approach seems to be strictly better than other.
1066 targets: Vec<BasicBlock>,
1069 /// Indicates that the landing pad is finished and unwinding should
1070 /// continue. Emitted by `build::scope::diverge_cleanup`.
1073 /// Indicates that the landing pad is finished and that the process
1074 /// should abort. Used to prevent unwinding for foreign items.
1077 /// Indicates a normal return. The return place should have
1078 /// been filled in by now. This should occur at most once.
1081 /// Indicates a terminator that can never be reached.
1084 /// Drop the `Place`.
1085 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1087 /// Drop the `Place` and assign the new value over it. This ensures
1088 /// that the assignment to `P` occurs *even if* the destructor for
1089 /// place unwinds. Its semantics are best explained by the
1094 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1102 /// Drop(P, goto BB1, unwind BB2)
1105 /// // P is now uninitialized
1109 /// // P is now uninitialized -- its dtor panicked
1114 location: Place<'tcx>,
1115 value: Operand<'tcx>,
1117 unwind: Option<BasicBlock>,
1120 /// Block ends with a call of a converging function.
1122 /// The function that’s being called.
1123 func: Operand<'tcx>,
1124 /// Arguments the function is called with.
1125 /// These are owned by the callee, which is free to modify them.
1126 /// This allows the memory occupied by "by-value" arguments to be
1127 /// reused across function calls without duplicating the contents.
1128 args: Vec<Operand<'tcx>>,
1129 /// Destination for the return value. If some, the call is converging.
1130 destination: Option<(Place<'tcx>, BasicBlock)>,
1131 /// Cleanups to be done if the call unwinds.
1132 cleanup: Option<BasicBlock>,
1133 /// `true` if this is from a call in HIR rather than from an overloaded
1134 /// operator. True for overloaded function call.
1135 from_hir_call: bool,
1138 /// Jump to the target if the condition has the expected value,
1139 /// otherwise panic with a message and a cleanup target.
1141 cond: Operand<'tcx>,
1143 msg: AssertMessage<'tcx>,
1145 cleanup: Option<BasicBlock>,
1148 /// A suspend point.
1150 /// The value to return.
1151 value: Operand<'tcx>,
1152 /// Where to resume to.
1154 /// Cleanup to be done if the generator is dropped at this suspend point.
1155 drop: Option<BasicBlock>,
1158 /// Indicates the end of the dropping of a generator.
1161 /// A block where control flow only ever takes one real path, but borrowck
1162 /// needs to be more conservative.
1164 /// The target normal control flow will take.
1165 real_target: BasicBlock,
1166 /// A block control flow could conceptually jump to, but won't in
1168 imaginary_target: BasicBlock,
1170 /// A terminator for blocks that only take one path in reality, but where we
1171 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1172 /// This can arise in infinite loops with no function calls for example.
1174 /// The target normal control flow will take.
1175 real_target: BasicBlock,
1176 /// The imaginary cleanup block link. This particular path will never be taken
1177 /// in practice, but in order to avoid fragility we want to always
1178 /// consider it in borrowck. We don't want to accept programs which
1179 /// pass borrowck only when `panic=abort` or some assertions are disabled
1180 /// due to release vs. debug mode builds. This needs to be an `Option` because
1181 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1182 unwind: Option<BasicBlock>,
1186 pub type Successors<'a> =
1187 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1188 pub type SuccessorsMut<'a> =
1189 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1191 impl<'tcx> Terminator<'tcx> {
1192 pub fn successors(&self) -> Successors<'_> {
1193 self.kind.successors()
1196 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1197 self.kind.successors_mut()
1200 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1204 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1205 self.kind.unwind_mut()
1209 impl<'tcx> TerminatorKind<'tcx> {
1212 cond: Operand<'tcx>,
1215 ) -> TerminatorKind<'tcx> {
1216 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1217 TerminatorKind::SwitchInt {
1219 switch_ty: tcx.types.bool,
1220 values: From::from(BOOL_SWITCH_FALSE),
1221 targets: vec![f, t],
1225 pub fn successors(&self) -> Successors<'_> {
1226 use self::TerminatorKind::*;
1233 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1234 Goto { target: ref t }
1235 | Call { destination: None, cleanup: Some(ref t), .. }
1236 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1237 | Yield { resume: ref t, drop: None, .. }
1238 | DropAndReplace { target: ref t, unwind: None, .. }
1239 | Drop { target: ref t, unwind: None, .. }
1240 | Assert { target: ref t, cleanup: None, .. }
1241 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1242 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1243 | Yield { resume: ref t, drop: Some(ref u), .. }
1244 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1245 | Drop { target: ref t, unwind: Some(ref u), .. }
1246 | Assert { target: ref t, cleanup: Some(ref u), .. }
1247 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1248 Some(t).into_iter().chain(slice::from_ref(u))
1250 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1251 FalseEdges { ref real_target, ref imaginary_target } => {
1252 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1257 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1258 use self::TerminatorKind::*;
1265 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1266 Goto { target: ref mut t }
1267 | Call { destination: None, cleanup: Some(ref mut t), .. }
1268 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1269 | Yield { resume: ref mut t, drop: None, .. }
1270 | DropAndReplace { target: ref mut t, unwind: None, .. }
1271 | Drop { target: ref mut t, unwind: None, .. }
1272 | Assert { target: ref mut t, cleanup: None, .. }
1273 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1274 Some(t).into_iter().chain(&mut [])
1276 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1277 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1278 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1279 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1280 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1281 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1282 Some(t).into_iter().chain(slice::from_mut(u))
1284 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1285 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1286 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1291 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1293 TerminatorKind::Goto { .. }
1294 | TerminatorKind::Resume
1295 | TerminatorKind::Abort
1296 | TerminatorKind::Return
1297 | TerminatorKind::Unreachable
1298 | TerminatorKind::GeneratorDrop
1299 | TerminatorKind::Yield { .. }
1300 | TerminatorKind::SwitchInt { .. }
1301 | TerminatorKind::FalseEdges { .. } => None,
1302 TerminatorKind::Call { cleanup: ref unwind, .. }
1303 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1304 | TerminatorKind::DropAndReplace { ref unwind, .. }
1305 | TerminatorKind::Drop { ref unwind, .. }
1306 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1310 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1312 TerminatorKind::Goto { .. }
1313 | TerminatorKind::Resume
1314 | TerminatorKind::Abort
1315 | TerminatorKind::Return
1316 | TerminatorKind::Unreachable
1317 | TerminatorKind::GeneratorDrop
1318 | TerminatorKind::Yield { .. }
1319 | TerminatorKind::SwitchInt { .. }
1320 | TerminatorKind::FalseEdges { .. } => None,
1321 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1322 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1323 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1324 | TerminatorKind::Drop { ref mut unwind, .. }
1325 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1330 impl<'tcx> BasicBlockData<'tcx> {
1331 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1332 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1335 /// Accessor for terminator.
1337 /// Terminator may not be None after construction of the basic block is complete. This accessor
1338 /// provides a convenience way to reach the terminator.
1339 pub fn terminator(&self) -> &Terminator<'tcx> {
1340 self.terminator.as_ref().expect("invalid terminator state")
1343 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1344 self.terminator.as_mut().expect("invalid terminator state")
1347 pub fn retain_statements<F>(&mut self, mut f: F)
1349 F: FnMut(&mut Statement<'_>) -> bool,
1351 for s in &mut self.statements {
1358 pub fn expand_statements<F, I>(&mut self, mut f: F)
1360 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1361 I: iter::TrustedLen<Item = Statement<'tcx>>,
1363 // Gather all the iterators we'll need to splice in, and their positions.
1364 let mut splices: Vec<(usize, I)> = vec![];
1365 let mut extra_stmts = 0;
1366 for (i, s) in self.statements.iter_mut().enumerate() {
1367 if let Some(mut new_stmts) = f(s) {
1368 if let Some(first) = new_stmts.next() {
1369 // We can already store the first new statement.
1372 // Save the other statements for optimized splicing.
1373 let remaining = new_stmts.size_hint().0;
1375 splices.push((i + 1 + extra_stmts, new_stmts));
1376 extra_stmts += remaining;
1384 // Splice in the new statements, from the end of the block.
1385 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1386 // where a range of elements ("gap") is left uninitialized, with
1387 // splicing adding new elements to the end of that gap and moving
1388 // existing elements from before the gap to the end of the gap.
1389 // For now, this is safe code, emulating a gap but initializing it.
1390 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1391 self.statements.resize(
1394 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1395 kind: StatementKind::Nop,
1398 for (splice_start, new_stmts) in splices.into_iter().rev() {
1399 let splice_end = splice_start + new_stmts.size_hint().0;
1400 while gap.end > splice_end {
1403 self.statements.swap(gap.start, gap.end);
1405 self.statements.splice(splice_start..splice_end, new_stmts);
1406 gap.end = splice_start;
1410 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1411 if index < self.statements.len() {
1412 &self.statements[index]
1419 impl<'tcx> Debug for TerminatorKind<'tcx> {
1420 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1421 self.fmt_head(fmt)?;
1422 let successor_count = self.successors().count();
1423 let labels = self.fmt_successor_labels();
1424 assert_eq!(successor_count, labels.len());
1426 match successor_count {
1429 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1432 write!(fmt, " -> [")?;
1433 for (i, target) in self.successors().enumerate() {
1437 write!(fmt, "{}: {:?}", labels[i], target)?;
1445 impl<'tcx> TerminatorKind<'tcx> {
1446 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1447 /// successor basic block, if any. The only information not included is the list of possible
1448 /// successors, which may be rendered differently between the text and the graphviz format.
1449 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1450 use self::TerminatorKind::*;
1452 Goto { .. } => write!(fmt, "goto"),
1453 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1454 Return => write!(fmt, "return"),
1455 GeneratorDrop => write!(fmt, "generator_drop"),
1456 Resume => write!(fmt, "resume"),
1457 Abort => write!(fmt, "abort"),
1458 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1459 Unreachable => write!(fmt, "unreachable"),
1460 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1461 DropAndReplace { ref location, ref value, .. } => {
1462 write!(fmt, "replace({:?} <- {:?})", location, value)
1464 Call { ref func, ref args, ref destination, .. } => {
1465 if let Some((ref destination, _)) = *destination {
1466 write!(fmt, "{:?} = ", destination)?;
1468 write!(fmt, "{:?}(", func)?;
1469 for (index, arg) in args.iter().enumerate() {
1473 write!(fmt, "{:?}", arg)?;
1477 Assert { ref cond, expected, ref msg, .. } => {
1478 write!(fmt, "assert(")?;
1482 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1484 FalseEdges { .. } => write!(fmt, "falseEdges"),
1485 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1489 /// Returns the list of labels for the edges to the successor basic blocks.
1490 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1491 use self::TerminatorKind::*;
1493 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1494 Goto { .. } => vec!["".into()],
1495 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1496 let param_env = ty::ParamEnv::empty();
1497 let switch_ty = tcx.lift(&switch_ty).unwrap();
1498 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1502 ty::Const::from_scalar(
1504 Scalar::from_uint(u, size).into(),
1510 .chain(iter::once("otherwise".into()))
1513 Call { destination: Some(_), cleanup: Some(_), .. } => {
1514 vec!["return".into(), "unwind".into()]
1516 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1517 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1518 Call { destination: None, cleanup: None, .. } => vec![],
1519 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1520 Yield { drop: None, .. } => vec!["resume".into()],
1521 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1522 vec!["return".into()]
1524 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1525 vec!["return".into(), "unwind".into()]
1527 Assert { cleanup: None, .. } => vec!["".into()],
1528 Assert { .. } => vec!["success".into(), "unwind".into()],
1529 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1530 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1531 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1536 ///////////////////////////////////////////////////////////////////////////
1539 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1540 pub struct Statement<'tcx> {
1541 pub source_info: SourceInfo,
1542 pub kind: StatementKind<'tcx>,
1545 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1546 #[cfg(target_arch = "x86_64")]
1547 static_assert_size!(Statement<'_>, 32);
1549 impl Statement<'_> {
1550 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1551 /// invalidating statement indices in `Location`s.
1552 pub fn make_nop(&mut self) {
1553 self.kind = StatementKind::Nop
1556 /// Changes a statement to a nop and returns the original statement.
1557 pub fn replace_nop(&mut self) -> Self {
1559 source_info: self.source_info,
1560 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1565 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1566 pub enum StatementKind<'tcx> {
1567 /// Write the RHS Rvalue to the LHS Place.
1568 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1570 /// This represents all the reading that a pattern match may do
1571 /// (e.g., inspecting constants and discriminant values), and the
1572 /// kind of pattern it comes from. This is in order to adapt potential
1573 /// error messages to these specific patterns.
1575 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1576 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1577 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1579 /// Write the discriminant for a variant to the enum Place.
1580 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1582 /// Start a live range for the storage of the local.
1585 /// End the current live range for the storage of the local.
1588 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1589 /// of `StatementKind` low.
1590 InlineAsm(Box<InlineAsm<'tcx>>),
1592 /// Retag references in the given place, ensuring they got fresh tags. This is
1593 /// part of the Stacked Borrows model. These statements are currently only interpreted
1594 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1595 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1596 /// for more details.
1597 Retag(RetagKind, Box<Place<'tcx>>),
1599 /// Encodes a user's type ascription. These need to be preserved
1600 /// intact so that NLL can respect them. For example:
1604 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1605 /// to the user-given type `T`. The effect depends on the specified variance:
1607 /// - `Covariant` -- requires that `T_y <: T`
1608 /// - `Contravariant` -- requires that `T_y :> T`
1609 /// - `Invariant` -- requires that `T_y == T`
1610 /// - `Bivariant` -- no effect
1611 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1613 /// No-op. Useful for deleting instructions without affecting statement indices.
1617 /// Describes what kind of retag is to be performed.
1618 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1619 pub enum RetagKind {
1620 /// The initial retag when entering a function.
1622 /// Retag preparing for a two-phase borrow.
1624 /// Retagging raw pointers.
1626 /// A "normal" retag.
1630 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1631 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1632 pub enum FakeReadCause {
1633 /// Inject a fake read of the borrowed input at the end of each guards
1636 /// This should ensure that you cannot change the variant for an enum while
1637 /// you are in the midst of matching on it.
1640 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1641 /// generate a read of x to check that it is initialized and safe.
1644 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1645 /// in a match guard to ensure that it's value hasn't change by the time
1646 /// we create the OutsideGuard version.
1649 /// Officially, the semantics of
1651 /// `let pattern = <expr>;`
1653 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1654 /// into the pattern.
1656 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1657 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1658 /// but in some cases it can affect the borrow checker, as in #53695.
1659 /// Therefore, we insert a "fake read" here to ensure that we get
1660 /// appropriate errors.
1663 /// If we have an index expression like
1665 /// (*x)[1][{ x = y; 4}]
1667 /// then the first bounds check is invalidated when we evaluate the second
1668 /// index expression. Thus we create a fake borrow of `x` across the second
1669 /// indexer, which will cause a borrow check error.
1673 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1674 pub struct InlineAsm<'tcx> {
1675 pub asm: hir::InlineAsmInner,
1676 pub outputs: Box<[Place<'tcx>]>,
1677 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1680 impl Debug for Statement<'_> {
1681 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1682 use self::StatementKind::*;
1684 Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1685 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1686 Retag(ref kind, ref place) => write!(
1690 RetagKind::FnEntry => "[fn entry] ",
1691 RetagKind::TwoPhase => "[2phase] ",
1692 RetagKind::Raw => "[raw] ",
1693 RetagKind::Default => "",
1697 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1698 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1699 SetDiscriminant { ref place, variant_index } => {
1700 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1702 InlineAsm(ref asm) => {
1703 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1705 AscribeUserType(box(ref place, ref c_ty), ref variance) => {
1706 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1708 Nop => write!(fmt, "nop"),
1713 ///////////////////////////////////////////////////////////////////////////
1716 /// A path to a value; something that can be evaluated without
1717 /// changing or disturbing program state.
1719 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable,
1721 pub struct Place<'tcx> {
1722 pub base: PlaceBase<'tcx>,
1724 /// projection out of a place (access a field, deref a pointer, etc)
1725 pub projection: &'tcx List<PlaceElem<'tcx>>,
1728 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1731 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1733 pub enum PlaceBase<'tcx> {
1737 /// static or static mut variable
1738 Static(Box<Static<'tcx>>),
1741 /// We store the normalized type to avoid requiring normalization when reading MIR
1742 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1743 RustcEncodable, RustcDecodable, HashStable)]
1744 pub struct Static<'tcx> {
1746 pub kind: StaticKind<'tcx>,
1747 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1748 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1749 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1750 /// into the calling frame.
1755 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1757 pub enum StaticKind<'tcx> {
1758 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1759 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1760 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1761 Promoted(Promoted, SubstsRef<'tcx>),
1765 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1766 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1767 pub enum ProjectionElem<V, T> {
1772 /// These indices are generated by slice patterns. Easiest to explain
1776 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1777 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1778 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1779 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1782 /// index or -index (in Python terms), depending on from_end
1784 /// thing being indexed must be at least this long
1786 /// counting backwards from end?
1790 /// These indices are generated by slice patterns.
1792 /// slice[from:-to] in Python terms.
1798 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1799 /// this for ADTs with more than one variant. It may be better to
1800 /// just introduce it always, or always for enums.
1802 /// The included Symbol is the name of the variant, used for printing MIR.
1803 Downcast(Option<Symbol>, VariantIdx),
1806 impl<V, T> ProjectionElem<V, T> {
1807 /// Returns `true` if the target of this projection may refer to a different region of memory
1809 fn is_indirect(&self) -> bool {
1811 Self::Deref => true,
1815 | Self::ConstantIndex { .. }
1816 | Self::Subslice { .. }
1817 | Self::Downcast(_, _)
1823 /// Alias for projections as they appear in places, where the base is a place
1824 /// and the index is a local.
1825 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1827 impl<'tcx> Copy for PlaceElem<'tcx> { }
1829 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1830 #[cfg(target_arch = "x86_64")]
1831 static_assert_size!(PlaceElem<'_>, 16);
1833 /// Alias for projections as they appear in `UserTypeProjection`, where we
1834 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1835 pub type ProjectionKind = ProjectionElem<(), ()>;
1837 rustc_index::newtype_index! {
1840 DEBUG_FORMAT = "field[{}]"
1844 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1845 pub struct PlaceRef<'a, 'tcx> {
1846 pub base: &'a PlaceBase<'tcx>,
1847 pub projection: &'a [PlaceElem<'tcx>],
1850 impl<'tcx> Place<'tcx> {
1851 // FIXME change this to a const fn by also making List::empty a const fn.
1852 pub fn return_place() -> Place<'tcx> {
1854 base: PlaceBase::Local(RETURN_PLACE),
1855 projection: List::empty(),
1859 /// Returns `true` if this `Place` contains a `Deref` projection.
1861 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1862 /// same region of memory as its base.
1863 pub fn is_indirect(&self) -> bool {
1864 self.projection.iter().any(|elem| elem.is_indirect())
1867 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1868 /// a single deref of a local.
1870 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1871 pub fn local_or_deref_local(&self) -> Option<Local> {
1872 match self.as_ref() {
1874 base: &PlaceBase::Local(local),
1878 base: &PlaceBase::Local(local),
1879 projection: &[ProjectionElem::Deref],
1885 /// If this place represents a local variable like `_X` with no
1886 /// projections, return `Some(_X)`.
1887 pub fn as_local(&self) -> Option<Local> {
1888 self.as_ref().as_local()
1891 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1894 projection: &self.projection,
1899 impl From<Local> for Place<'_> {
1900 fn from(local: Local) -> Self {
1903 projection: List::empty(),
1908 impl From<Local> for PlaceBase<'_> {
1909 fn from(local: Local) -> Self {
1910 PlaceBase::Local(local)
1914 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1915 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1916 /// a single deref of a local.
1918 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1919 pub fn local_or_deref_local(&self) -> Option<Local> {
1922 base: PlaceBase::Local(local),
1926 base: PlaceBase::Local(local),
1927 projection: [ProjectionElem::Deref],
1933 /// If this place represents a local variable like `_X` with no
1934 /// projections, return `Some(_X)`.
1935 pub fn as_local(&self) -> Option<Local> {
1937 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1943 impl Debug for Place<'_> {
1944 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1945 for elem in self.projection.iter().rev() {
1947 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1948 write!(fmt, "(").unwrap();
1950 ProjectionElem::Deref => {
1951 write!(fmt, "(*").unwrap();
1953 ProjectionElem::Index(_)
1954 | ProjectionElem::ConstantIndex { .. }
1955 | ProjectionElem::Subslice { .. } => {}
1959 write!(fmt, "{:?}", self.base)?;
1961 for elem in self.projection.iter() {
1963 ProjectionElem::Downcast(Some(name), _index) => {
1964 write!(fmt, " as {})", name)?;
1966 ProjectionElem::Downcast(None, index) => {
1967 write!(fmt, " as variant#{:?})", index)?;
1969 ProjectionElem::Deref => {
1972 ProjectionElem::Field(field, ty) => {
1973 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1975 ProjectionElem::Index(ref index) => {
1976 write!(fmt, "[{:?}]", index)?;
1978 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1979 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
1981 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1982 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
1984 ProjectionElem::Subslice { from, to } if *to == 0 => {
1985 write!(fmt, "[{:?}:]", from)?;
1987 ProjectionElem::Subslice { from, to } if *from == 0 => {
1988 write!(fmt, "[:-{:?}]", to)?;
1990 ProjectionElem::Subslice { from, to } => {
1991 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2000 impl Debug for PlaceBase<'_> {
2001 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2003 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2004 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
2005 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
2007 PlaceBase::Static(box self::Static {
2008 ty, kind: StaticKind::Promoted(promoted, _), def_id: _
2010 write!(fmt, "({:?}: {:?})", promoted, ty)
2016 ///////////////////////////////////////////////////////////////////////////
2019 rustc_index::newtype_index! {
2020 pub struct SourceScope {
2022 DEBUG_FORMAT = "scope[{}]",
2023 const OUTERMOST_SOURCE_SCOPE = 0,
2027 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2028 pub struct SourceScopeData {
2030 pub parent_scope: Option<SourceScope>,
2032 /// Crate-local information for this source scope, that can't (and
2033 /// needn't) be tracked across crates.
2034 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
2037 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2038 pub struct SourceScopeLocalData {
2039 /// An `HirId` with lint levels equivalent to this scope's lint levels.
2040 pub lint_root: hir::HirId,
2041 /// The unsafe block that contains this node.
2045 ///////////////////////////////////////////////////////////////////////////
2048 /// These are values that can appear inside an rvalue. They are intentionally
2049 /// limited to prevent rvalues from being nested in one another.
2050 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2051 pub enum Operand<'tcx> {
2052 /// Copy: The value must be available for use afterwards.
2054 /// This implies that the type of the place must be `Copy`; this is true
2055 /// by construction during build, but also checked by the MIR type checker.
2058 /// Move: The value (including old borrows of it) will not be used again.
2060 /// Safe for values of all types (modulo future developments towards `?Move`).
2061 /// Correct usage patterns are enforced by the borrow checker for safe code.
2062 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2065 /// Synthesizes a constant value.
2066 Constant(Box<Constant<'tcx>>),
2069 impl<'tcx> Debug for Operand<'tcx> {
2070 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2071 use self::Operand::*;
2073 Constant(ref a) => write!(fmt, "{:?}", a),
2074 Copy(ref place) => write!(fmt, "{:?}", place),
2075 Move(ref place) => write!(fmt, "move {:?}", place),
2080 impl<'tcx> Operand<'tcx> {
2081 /// Convenience helper to make a constant that refers to the fn
2082 /// with given `DefId` and substs. Since this is used to synthesize
2083 /// MIR, assumes `user_ty` is None.
2084 pub fn function_handle(
2087 substs: SubstsRef<'tcx>,
2090 let ty = tcx.type_of(def_id).subst(tcx, substs);
2091 Operand::Constant(box Constant {
2094 literal: ty::Const::zero_sized(tcx, ty),
2098 pub fn to_copy(&self) -> Self {
2100 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2101 Operand::Move(ref place) => Operand::Copy(place.clone()),
2106 ///////////////////////////////////////////////////////////////////////////
2109 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2110 pub enum Rvalue<'tcx> {
2111 /// x (either a move or copy, depending on type of x)
2115 Repeat(Operand<'tcx>, u64),
2118 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2120 /// length of a [X] or [X;n] value
2123 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2125 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2126 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2128 NullaryOp(NullOp, Ty<'tcx>),
2129 UnaryOp(UnOp, Operand<'tcx>),
2131 /// Read the discriminant of an ADT.
2133 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2134 /// be defined to return, say, a 0) if ADT is not an enum.
2135 Discriminant(Place<'tcx>),
2137 /// Creates an aggregate value, like a tuple or struct. This is
2138 /// only needed because we want to distinguish `dest = Foo { x:
2139 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2140 /// that `Foo` has a destructor. These rvalues can be optimized
2141 /// away after type-checking and before lowering.
2142 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2145 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2148 Pointer(PointerCast),
2151 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2152 pub enum AggregateKind<'tcx> {
2153 /// The type is of the element
2157 /// The second field is the variant index. It's equal to 0 for struct
2158 /// and union expressions. The fourth field is
2159 /// active field number and is present only for union expressions
2160 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2161 /// active field index would identity the field `c`
2162 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2164 Closure(DefId, SubstsRef<'tcx>),
2165 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2168 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2170 /// The `+` operator (addition)
2172 /// The `-` operator (subtraction)
2174 /// The `*` operator (multiplication)
2176 /// The `/` operator (division)
2178 /// The `%` operator (modulus)
2180 /// The `^` operator (bitwise xor)
2182 /// The `&` operator (bitwise and)
2184 /// The `|` operator (bitwise or)
2186 /// The `<<` operator (shift left)
2188 /// The `>>` operator (shift right)
2190 /// The `==` operator (equality)
2192 /// The `<` operator (less than)
2194 /// The `<=` operator (less than or equal to)
2196 /// The `!=` operator (not equal to)
2198 /// The `>=` operator (greater than or equal to)
2200 /// The `>` operator (greater than)
2202 /// The `ptr.offset` operator
2207 pub fn is_checkable(self) -> bool {
2210 Add | Sub | Mul | Shl | Shr => true,
2216 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2218 /// Returns the size of a value of that type
2220 /// Creates a new uninitialized box for a value of that type
2224 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2226 /// The `!` operator for logical inversion
2228 /// The `-` operator for negation
2232 impl<'tcx> Debug for Rvalue<'tcx> {
2233 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2234 use self::Rvalue::*;
2237 Use(ref place) => write!(fmt, "{:?}", place),
2238 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2239 Len(ref a) => write!(fmt, "Len({:?})", a),
2240 Cast(ref kind, ref place, ref ty) => {
2241 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2243 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2244 CheckedBinaryOp(ref op, ref a, ref b) => {
2245 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2247 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2248 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2249 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2250 Ref(region, borrow_kind, ref place) => {
2251 let kind_str = match borrow_kind {
2252 BorrowKind::Shared => "",
2253 BorrowKind::Shallow => "shallow ",
2254 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2257 // When printing regions, add trailing space if necessary.
2258 let print_region = ty::tls::with(|tcx| {
2259 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2261 let region = if print_region {
2262 let mut region = region.to_string();
2263 if region.len() > 0 {
2268 // Do not even print 'static
2271 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2274 Aggregate(ref kind, ref places) => {
2275 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2276 let mut tuple_fmt = fmt.debug_tuple("");
2277 for place in places {
2278 tuple_fmt.field(place);
2284 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2286 AggregateKind::Tuple => match places.len() {
2287 0 => write!(fmt, "()"),
2288 1 => write!(fmt, "({:?},)", places[0]),
2289 _ => fmt_tuple(fmt, places),
2292 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2293 let variant_def = &adt_def.variants[variant];
2296 ty::tls::with(|tcx| {
2297 let substs = tcx.lift(&substs).expect("could not lift for printing");
2298 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2299 .print_def_path(variant_def.def_id, substs)?;
2303 match variant_def.ctor_kind {
2304 CtorKind::Const => Ok(()),
2305 CtorKind::Fn => fmt_tuple(fmt, places),
2306 CtorKind::Fictive => {
2307 let mut struct_fmt = fmt.debug_struct("");
2308 for (field, place) in variant_def.fields.iter().zip(places) {
2309 struct_fmt.field(&field.ident.as_str(), place);
2316 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2317 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2318 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2319 let substs = tcx.lift(&substs).unwrap();
2322 tcx.def_path_str_with_substs(def_id, substs),
2325 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2327 let mut struct_fmt = fmt.debug_struct(&name);
2329 if let Some(upvars) = tcx.upvars(def_id) {
2330 for (&var_id, place) in upvars.keys().zip(places) {
2331 let var_name = tcx.hir().name(var_id);
2332 struct_fmt.field(&var_name.as_str(), place);
2338 write!(fmt, "[closure]")
2342 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2343 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2344 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2345 let mut struct_fmt = fmt.debug_struct(&name);
2347 if let Some(upvars) = tcx.upvars(def_id) {
2348 for (&var_id, place) in upvars.keys().zip(places) {
2349 let var_name = tcx.hir().name(var_id);
2350 struct_fmt.field(&var_name.as_str(), place);
2356 write!(fmt, "[generator]")
2365 ///////////////////////////////////////////////////////////////////////////
2368 /// Two constants are equal if they are the same constant. Note that
2369 /// this does not necessarily mean that they are "==" in Rust -- in
2370 /// particular one must be wary of `NaN`!
2372 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2373 pub struct Constant<'tcx> {
2376 /// Optional user-given type: for something like
2377 /// `collect::<Vec<_>>`, this would be present and would
2378 /// indicate that `Vec<_>` was explicitly specified.
2380 /// Needed for NLL to impose user-given type constraints.
2381 pub user_ty: Option<UserTypeAnnotationIndex>,
2383 pub literal: &'tcx ty::Const<'tcx>,
2386 impl Constant<'tcx> {
2387 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2388 match self.literal.val.try_to_scalar() {
2389 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2390 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2393 tcx.sess.delay_span_bug(
2394 DUMMY_SP, "MIR cannot contain dangling const pointers",
2404 /// A collection of projections into user types.
2406 /// They are projections because a binding can occur a part of a
2407 /// parent pattern that has been ascribed a type.
2409 /// Its a collection because there can be multiple type ascriptions on
2410 /// the path from the root of the pattern down to the binding itself.
2415 /// struct S<'a>((i32, &'a str), String);
2416 /// let S((_, w): (i32, &'static str), _): S = ...;
2417 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2418 /// // --------------------------------- ^ (2)
2421 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2422 /// ascribed the type `(i32, &'static str)`.
2424 /// The highlights labelled `(2)` show the whole pattern being
2425 /// ascribed the type `S`.
2427 /// In this example, when we descend to `w`, we will have built up the
2428 /// following two projected types:
2430 /// * base: `S`, projection: `(base.0).1`
2431 /// * base: `(i32, &'static str)`, projection: `base.1`
2433 /// The first will lead to the constraint `w: &'1 str` (for some
2434 /// inferred region `'1`). The second will lead to the constraint `w:
2436 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2437 pub struct UserTypeProjections {
2438 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2441 impl<'tcx> UserTypeProjections {
2442 pub fn none() -> Self {
2443 UserTypeProjections { contents: vec![] }
2446 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2447 UserTypeProjections { contents: projs.collect() }
2450 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2451 self.contents.iter()
2454 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2455 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2458 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2459 self.contents.push((user_ty.clone(), span));
2465 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2467 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2471 pub fn index(self) -> Self {
2472 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2475 pub fn subslice(self, from: u32, to: u32) -> Self {
2476 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2479 pub fn deref(self) -> Self {
2480 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2483 pub fn leaf(self, field: Field) -> Self {
2484 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2487 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2488 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2492 /// Encodes the effect of a user-supplied type annotation on the
2493 /// subcomponents of a pattern. The effect is determined by applying the
2494 /// given list of proejctions to some underlying base type. Often,
2495 /// the projection element list `projs` is empty, in which case this
2496 /// directly encodes a type in `base`. But in the case of complex patterns with
2497 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2498 /// in which case the `projs` vector is used.
2502 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2504 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2505 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2506 /// determined by finding the type of the `.0` field from `T`.
2507 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2508 pub struct UserTypeProjection {
2509 pub base: UserTypeAnnotationIndex,
2510 pub projs: Vec<ProjectionKind>,
2513 impl Copy for ProjectionKind {}
2515 impl UserTypeProjection {
2516 pub(crate) fn index(mut self) -> Self {
2517 self.projs.push(ProjectionElem::Index(()));
2521 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2522 self.projs.push(ProjectionElem::Subslice { from, to });
2526 pub(crate) fn deref(mut self) -> Self {
2527 self.projs.push(ProjectionElem::Deref);
2531 pub(crate) fn leaf(mut self, field: Field) -> Self {
2532 self.projs.push(ProjectionElem::Field(field, ()));
2536 pub(crate) fn variant(
2538 adt_def: &'tcx AdtDef,
2539 variant_index: VariantIdx,
2542 self.projs.push(ProjectionElem::Downcast(
2543 Some(adt_def.variants[variant_index].ident.name),
2546 self.projs.push(ProjectionElem::Field(field, ()));
2551 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2553 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2554 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2555 use crate::mir::ProjectionElem::*;
2557 let base = self.base.fold_with(folder);
2558 let projs: Vec<_> = self
2561 .map(|elem| match elem {
2563 Field(f, ()) => Field(f.clone(), ()),
2564 Index(()) => Index(()),
2565 elem => elem.clone(),
2569 UserTypeProjection { base, projs }
2572 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2573 self.base.visit_with(visitor)
2574 // Note: there's nothing in `self.proj` to visit.
2578 rustc_index::newtype_index! {
2579 pub struct Promoted {
2581 DEBUG_FORMAT = "promoted[{}]"
2585 impl<'tcx> Debug for Constant<'tcx> {
2586 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2587 write!(fmt, "{}", self)
2591 impl<'tcx> Display for Constant<'tcx> {
2592 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2593 write!(fmt, "const ")?;
2594 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2595 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2596 // detailed and just not '{pointer}'.
2597 if let ty::RawPtr(_) = self.literal.ty.kind {
2598 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2600 write!(fmt, "{}", self.literal)
2605 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2606 type Node = BasicBlock;
2609 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2610 fn num_nodes(&self) -> usize {
2611 self.basic_blocks.len()
2615 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2616 fn start_node(&self) -> Self::Node {
2621 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2625 ) -> <Self as GraphPredecessors<'_>>::Iter {
2626 self.predecessors_for(node).clone().into_iter()
2630 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2634 ) -> <Self as GraphSuccessors<'_>>::Iter {
2635 self.basic_blocks[node].terminator().successors().cloned()
2639 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2640 type Item = BasicBlock;
2641 type Iter = IntoIter<BasicBlock>;
2644 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2645 type Item = BasicBlock;
2646 type Iter = iter::Cloned<Successors<'b>>;
2649 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2650 pub struct Location {
2651 /// The block that the location is within.
2652 pub block: BasicBlock,
2654 /// The location is the position of the start of the statement; or, if
2655 /// `statement_index` equals the number of statements, then the start of the
2657 pub statement_index: usize,
2660 impl fmt::Debug for Location {
2661 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2662 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2667 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2669 /// Returns the location immediately after this one within the enclosing block.
2671 /// Note that if this location represents a terminator, then the
2672 /// resulting location would be out of bounds and invalid.
2673 pub fn successor_within_block(&self) -> Location {
2674 Location { block: self.block, statement_index: self.statement_index + 1 }
2677 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2678 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2679 // If we are in the same block as the other location and are an earlier statement
2680 // then we are a predecessor of `other`.
2681 if self.block == other.block && self.statement_index < other.statement_index {
2685 // If we're in another block, then we want to check that block is a predecessor of `other`.
2686 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).clone();
2687 let mut visited = FxHashSet::default();
2689 while let Some(block) = queue.pop() {
2690 // If we haven't visited this block before, then make sure we visit it's predecessors.
2691 if visited.insert(block) {
2692 queue.append(&mut body.predecessors_for(block).clone());
2697 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2698 // we found that block by looking at the predecessors of `other`).
2699 if self.block == block {
2707 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2708 if self.block == other.block {
2709 self.statement_index <= other.statement_index
2711 dominators.is_dominated_by(other.block, self.block)
2716 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2717 pub enum UnsafetyViolationKind {
2719 /// Permitted both in `const fn`s and regular `fn`s.
2721 BorrowPacked(hir::HirId),
2724 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2725 pub struct UnsafetyViolation {
2726 pub source_info: SourceInfo,
2727 pub description: Symbol,
2728 pub details: Symbol,
2729 pub kind: UnsafetyViolationKind,
2732 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2733 pub struct UnsafetyCheckResult {
2734 /// Violations that are propagated *upwards* from this function.
2735 pub violations: Lrc<[UnsafetyViolation]>,
2736 /// `unsafe` blocks in this function, along with whether they are used. This is
2737 /// used for the "unused_unsafe" lint.
2738 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2741 rustc_index::newtype_index! {
2742 pub struct GeneratorSavedLocal {
2744 DEBUG_FORMAT = "_{}",
2748 /// The layout of generator state.
2749 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2750 pub struct GeneratorLayout<'tcx> {
2751 /// The type of every local stored inside the generator.
2752 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2754 /// Which of the above fields are in each variant. Note that one field may
2755 /// be stored in multiple variants.
2756 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2758 /// Which saved locals are storage-live at the same time. Locals that do not
2759 /// have conflicts with each other are allowed to overlap in the computed
2761 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2764 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2765 pub struct BorrowCheckResult<'tcx> {
2766 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2767 pub used_mut_upvars: SmallVec<[Field; 8]>,
2770 /// The result of the `mir_const_qualif` query.
2772 /// Each field corresponds to an implementer of the `Qualif` trait in
2773 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2775 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2776 pub struct ConstQualifs {
2777 pub has_mut_interior: bool,
2778 pub needs_drop: bool,
2781 /// After we borrow check a closure, we are left with various
2782 /// requirements that we have inferred between the free regions that
2783 /// appear in the closure's signature or on its field types. These
2784 /// requirements are then verified and proved by the closure's
2785 /// creating function. This struct encodes those requirements.
2787 /// The requirements are listed as being between various
2788 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2789 /// vids refer to the free regions that appear in the closure (or
2790 /// generator's) type, in order of appearance. (This numbering is
2791 /// actually defined by the `UniversalRegions` struct in the NLL
2792 /// region checker. See for example
2793 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2794 /// regions in the closure's type "as if" they were erased, so their
2795 /// precise identity is not important, only their position.
2797 /// Example: If type check produces a closure with the closure substs:
2800 /// ClosureSubsts = [
2801 /// i8, // the "closure kind"
2802 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2803 /// &'a String, // some upvar
2807 /// here, there is one unique free region (`'a`) but it appears
2808 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2811 /// ClosureSubsts = [
2812 /// i8, // the "closure kind"
2813 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2814 /// &'2 String, // some upvar
2818 /// Now the code might impose a requirement like `'1: '2`. When an
2819 /// instance of the closure is created, the corresponding free regions
2820 /// can be extracted from its type and constrained to have the given
2821 /// outlives relationship.
2823 /// In some cases, we have to record outlives requirements between
2824 /// types and regions as well. In that case, if those types include
2825 /// any regions, those regions are recorded as `ReClosureBound`
2826 /// instances assigned one of these same indices. Those regions will
2827 /// be substituted away by the creator. We use `ReClosureBound` in
2828 /// that case because the regions must be allocated in the global
2829 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2830 /// internally within the rest of the NLL code).
2831 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2832 pub struct ClosureRegionRequirements<'tcx> {
2833 /// The number of external regions defined on the closure. In our
2834 /// example above, it would be 3 -- one for `'static`, then `'1`
2835 /// and `'2`. This is just used for a sanity check later on, to
2836 /// make sure that the number of regions we see at the callsite
2838 pub num_external_vids: usize,
2840 /// Requirements between the various free regions defined in
2842 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2845 /// Indicates an outlives-constraint between a type or between two
2846 /// free regions declared on the closure.
2847 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2848 pub struct ClosureOutlivesRequirement<'tcx> {
2849 // This region or type ...
2850 pub subject: ClosureOutlivesSubject<'tcx>,
2852 // ... must outlive this one.
2853 pub outlived_free_region: ty::RegionVid,
2855 // If not, report an error here ...
2856 pub blame_span: Span,
2858 // ... due to this reason.
2859 pub category: ConstraintCategory,
2862 /// Outlives-constraints can be categorized to determine whether and why they
2863 /// are interesting (for error reporting). Order of variants indicates sort
2864 /// order of the category, thereby influencing diagnostic output.
2866 /// See also [rustc_mir::borrow_check::nll::constraints].
2880 pub enum ConstraintCategory {
2888 /// A constraint that came from checking the body of a closure.
2890 /// We try to get the category that the closure used when reporting this.
2898 /// A "boring" constraint (caused by the given location) is one that
2899 /// the user probably doesn't want to see described in diagnostics,
2900 /// because it is kind of an artifact of the type system setup.
2901 /// Example: `x = Foo { field: y }` technically creates
2902 /// intermediate regions representing the "type of `Foo { field: y
2903 /// }`", and data flows from `y` into those variables, but they
2904 /// are not very interesting. The assignment into `x` on the other
2907 // Boring and applicable everywhere.
2910 /// A constraint that doesn't correspond to anything the user sees.
2914 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2915 /// that must outlive some region.
2916 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2917 pub enum ClosureOutlivesSubject<'tcx> {
2918 /// Subject is a type, typically a type parameter, but could also
2919 /// be a projection. Indicates a requirement like `T: 'a` being
2920 /// passed to the caller, where the type here is `T`.
2922 /// The type here is guaranteed not to contain any free regions at
2926 /// Subject is a free region from the closure. Indicates a requirement
2927 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2928 Region(ty::RegionVid),
2932 * `TypeFoldable` implementations for MIR types
2935 CloneTypeFoldableAndLiftImpls! {
2944 SourceScopeLocalData,
2945 UserTypeAnnotationIndex,
2948 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2949 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2950 use crate::mir::TerminatorKind::*;
2952 let kind = match self.kind {
2953 Goto { target } => Goto { target },
2954 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2955 discr: discr.fold_with(folder),
2956 switch_ty: switch_ty.fold_with(folder),
2957 values: values.clone(),
2958 targets: targets.clone(),
2960 Drop { ref location, target, unwind } => {
2961 Drop { location: location.fold_with(folder), target, unwind }
2963 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2964 location: location.fold_with(folder),
2965 value: value.fold_with(folder),
2969 Yield { ref value, resume, drop } => {
2970 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
2972 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
2974 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2977 func: func.fold_with(folder),
2978 args: args.fold_with(folder),
2984 Assert { ref cond, expected, ref msg, target, cleanup } => {
2986 let msg = match msg {
2987 BoundsCheck { ref len, ref index } =>
2989 len: len.fold_with(folder),
2990 index: index.fold_with(folder),
2992 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
2993 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
2996 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
2998 GeneratorDrop => GeneratorDrop,
3002 Unreachable => Unreachable,
3003 FalseEdges { real_target, imaginary_target } => {
3004 FalseEdges { real_target, imaginary_target }
3006 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
3008 Terminator { source_info: self.source_info, kind }
3011 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3012 use crate::mir::TerminatorKind::*;
3015 SwitchInt { ref discr, switch_ty, .. } => {
3016 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
3018 Drop { ref location, .. } => location.visit_with(visitor),
3019 DropAndReplace { ref location, ref value, .. } => {
3020 location.visit_with(visitor) || value.visit_with(visitor)
3022 Yield { ref value, .. } => value.visit_with(visitor),
3023 Call { ref func, ref args, ref destination, .. } => {
3024 let dest = if let Some((ref loc, _)) = *destination {
3025 loc.visit_with(visitor)
3029 dest || func.visit_with(visitor) || args.visit_with(visitor)
3031 Assert { ref cond, ref msg, .. } => {
3032 if cond.visit_with(visitor) {
3035 BoundsCheck { ref len, ref index } =>
3036 len.visit_with(visitor) || index.visit_with(visitor),
3037 Panic { .. } | Overflow(_) | OverflowNeg |
3038 DivisionByZero | RemainderByZero |
3039 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
3053 | FalseUnwind { .. } => false,
3058 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
3059 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3063 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3068 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3069 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3071 base: self.base.fold_with(folder),
3072 projection: self.projection.fold_with(folder),
3076 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3077 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3081 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3082 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3084 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3085 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3089 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3091 PlaceBase::Local(local) => local.visit_with(visitor),
3092 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3097 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3098 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3099 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3100 folder.tcx().intern_place_elems(&v)
3103 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3104 self.iter().any(|t| t.visit_with(visitor))
3108 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3109 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3111 ty: self.ty.fold_with(folder),
3112 kind: self.kind.fold_with(folder),
3113 def_id: self.def_id,
3117 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3118 let Static { ty, kind, def_id: _ } = self;
3120 ty.visit_with(visitor) || kind.visit_with(visitor)
3124 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3125 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3127 StaticKind::Promoted(promoted, substs) =>
3128 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)),
3129 StaticKind::Static => StaticKind::Static
3133 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3135 StaticKind::Promoted(promoted, substs) =>
3136 promoted.visit_with(visitor) || substs.visit_with(visitor),
3137 StaticKind::Static => { false }
3142 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3143 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3144 use crate::mir::Rvalue::*;
3146 Use(ref op) => Use(op.fold_with(folder)),
3147 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3148 Ref(region, bk, ref place) => {
3149 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3151 Len(ref place) => Len(place.fold_with(folder)),
3152 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3153 BinaryOp(op, ref rhs, ref lhs) => {
3154 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3156 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3157 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3159 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3160 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3161 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3162 Aggregate(ref kind, ref fields) => {
3163 let kind = box match **kind {
3164 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3165 AggregateKind::Tuple => AggregateKind::Tuple,
3166 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3169 substs.fold_with(folder),
3170 user_ty.fold_with(folder),
3173 AggregateKind::Closure(id, substs) => {
3174 AggregateKind::Closure(id, substs.fold_with(folder))
3176 AggregateKind::Generator(id, substs, movablity) => {
3177 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3180 Aggregate(kind, fields.fold_with(folder))
3185 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3186 use crate::mir::Rvalue::*;
3188 Use(ref op) => op.visit_with(visitor),
3189 Repeat(ref op, _) => op.visit_with(visitor),
3190 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3191 Len(ref place) => place.visit_with(visitor),
3192 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3193 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3194 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3196 UnaryOp(_, ref val) => val.visit_with(visitor),
3197 Discriminant(ref place) => place.visit_with(visitor),
3198 NullaryOp(_, ty) => ty.visit_with(visitor),
3199 Aggregate(ref kind, ref fields) => {
3201 AggregateKind::Array(ty) => ty.visit_with(visitor),
3202 AggregateKind::Tuple => false,
3203 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3204 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3206 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3207 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3208 }) || fields.visit_with(visitor)
3214 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3215 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3217 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3218 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3219 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3223 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3225 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3226 Operand::Constant(ref c) => c.visit_with(visitor),
3231 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3232 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3233 use crate::mir::ProjectionElem::*;
3237 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3238 Index(v) => Index(v.fold_with(folder)),
3239 elem => elem.clone(),
3243 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3244 use crate::mir::ProjectionElem::*;
3247 Field(_, ty) => ty.visit_with(visitor),
3248 Index(v) => v.visit_with(visitor),
3254 impl<'tcx> TypeFoldable<'tcx> for Field {
3255 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3258 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3263 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3264 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3267 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3272 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3273 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3276 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3281 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3282 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3284 span: self.span.clone(),
3285 user_ty: self.user_ty.fold_with(folder),
3286 literal: self.literal.fold_with(folder),
3289 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3290 self.literal.visit_with(visitor)