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_macros::HashStable;
29 use rustc_serialize::{Encodable, Decodable};
30 use smallvec::SmallVec;
32 use std::fmt::{self, Debug, Display, Formatter, Write};
33 use std::ops::{Index, IndexMut};
35 use std::vec::IntoIter;
36 use std::{iter, mem, option, u32};
37 use syntax::ast::Name;
38 use syntax::symbol::Symbol;
39 use syntax_pos::{Span, DUMMY_SP};
41 pub use crate::mir::interpret::AssertMessage;
51 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
53 pub trait HasLocalDecls<'tcx> {
54 fn local_decls(&self) -> &LocalDecls<'tcx>;
57 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
58 fn local_decls(&self) -> &LocalDecls<'tcx> {
63 impl<'tcx> HasLocalDecls<'tcx> for Body<'tcx> {
64 fn local_decls(&self) -> &LocalDecls<'tcx> {
69 /// The various "big phases" that MIR goes through.
71 /// Warning: ordering of variants is significant.
72 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable,
73 Debug, PartialEq, Eq, PartialOrd, Ord)]
82 /// Gets the index of the current MirPhase within the set of all `MirPhase`s.
83 pub fn phase_index(&self) -> usize {
88 /// The lowered representation of a single function.
89 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable, TypeFoldable)]
90 pub struct Body<'tcx> {
91 /// A list of basic blocks. References to basic block use a newtyped index type `BasicBlock`
92 /// that indexes into this vector.
93 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
95 /// Records how far through the "desugaring and optimization" process this particular
96 /// MIR has traversed. This is particularly useful when inlining, since in that context
97 /// we instantiate the promoted constants and add them to our promoted vector -- but those
98 /// promoted items have already been optimized, whereas ours have not. This field allows
99 /// us to see the difference and forego optimization on the inlined promoted items.
102 /// A list of source scopes; these are referenced by statements
103 /// and used for debuginfo. Indexed by a `SourceScope`.
104 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
106 /// The yield type of the function, if it is a generator.
107 pub yield_ty: Option<Ty<'tcx>>,
109 /// Generator drop glue.
110 pub generator_drop: Option<Box<Body<'tcx>>>,
112 /// The layout of a generator. Produced by the state transformation.
113 pub generator_layout: Option<GeneratorLayout<'tcx>>,
115 /// If this is a generator then record the type of source expression that caused this generator
117 pub generator_kind: Option<GeneratorKind>,
119 /// Declarations of locals.
121 /// The first local is the return value pointer, followed by `arg_count`
122 /// locals for the function arguments, followed by any user-declared
123 /// variables and temporaries.
124 pub local_decls: LocalDecls<'tcx>,
126 /// User type annotations.
127 pub user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
129 /// The number of arguments this function takes.
131 /// Starting at local 1, `arg_count` locals will be provided by the caller
132 /// and can be assumed to be initialized.
134 /// If this MIR was built for a constant, this will be 0.
135 pub arg_count: usize,
137 /// Mark an argument local (which must be a tuple) as getting passed as
138 /// its individual components at the LLVM level.
140 /// This is used for the "rust-call" ABI.
141 pub spread_arg: Option<Local>,
143 /// Debug information pertaining to user variables, including captures.
144 pub var_debug_info: Vec<VarDebugInfo<'tcx>>,
146 /// Mark this MIR of a const context other than const functions as having converted a `&&` or
147 /// `||` expression into `&` or `|` respectively. This is problematic because if we ever stop
148 /// this conversion from happening and use short circuiting, we will cause the following code
149 /// to change the value of `x`: `let mut x = 42; false && { x = 55; true };`
151 /// List of places where control flow was destroyed. Used for error reporting.
152 pub control_flow_destroyed: Vec<(Span, String)>,
154 /// A span representing this MIR, for error reporting.
157 /// A cache for various calculations.
161 impl<'tcx> Body<'tcx> {
163 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
164 source_scopes: IndexVec<SourceScope, SourceScopeData>,
165 local_decls: LocalDecls<'tcx>,
166 user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
168 var_debug_info: Vec<VarDebugInfo<'tcx>>,
170 control_flow_destroyed: Vec<(Span, String)>,
171 generator_kind : Option<GeneratorKind>,
173 // We need `arg_count` locals, and one for the return place.
175 local_decls.len() >= arg_count + 1,
176 "expected at least {} locals, got {}",
182 phase: MirPhase::Build,
186 generator_drop: None,
187 generator_layout: None,
190 user_type_annotations,
195 cache: cache::Cache::new(),
196 control_flow_destroyed,
201 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
206 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
207 debug!("bbm: Clearing predecessors cache for body at: {:?}", self.span.data());
208 self.cache.invalidate_predecessors();
209 &mut self.basic_blocks
213 pub fn basic_blocks_and_local_decls_mut(
215 ) -> (&mut IndexVec<BasicBlock, BasicBlockData<'tcx>>, &mut LocalDecls<'tcx>) {
216 debug!("bbaldm: Clearing predecessors cache for body at: {:?}", self.span.data());
217 self.cache.invalidate_predecessors();
218 (&mut self.basic_blocks, &mut self.local_decls)
222 pub fn unwrap_predecessors(&self) -> &IndexVec<BasicBlock, Vec<BasicBlock>> {
224 self.cache.predecessors.is_some(),
225 "Expected cache.predecessors to be `Some(...)` for block at: {:?}",
228 self.cache.predecessors.as_ref().unwrap()
232 pub fn ensure_predecessors(&mut self) {
233 if self.cache.predecessors.is_none() {
234 let mut result = IndexVec::from_elem(vec![], self.basic_blocks());
235 for (bb, data) in self.basic_blocks().iter_enumerated() {
236 if let Some(ref term) = data.terminator {
237 for &tgt in term.successors() {
238 result[tgt].push(bb);
243 self.cache.predecessors = Some(result)
248 /// This will recompute the predecessors cache if it is not available
249 pub fn predecessors(&mut self) -> &IndexVec<BasicBlock, Vec<BasicBlock>> {
250 self.ensure_predecessors();
251 self.cache.predecessors.as_ref().unwrap()
255 pub fn predecessors_for(&self, bb: BasicBlock) -> &[BasicBlock] {
256 &self.unwrap_predecessors()[bb]
260 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
261 let if_zero_locations = if loc.statement_index == 0 {
262 let predecessor_blocks = self.predecessors_for(loc.block);
263 let num_predecessor_blocks = predecessor_blocks.len();
265 (0..num_predecessor_blocks)
266 .map(move |i| predecessor_blocks[i])
267 .map(move |bb| self.terminator_loc(bb)),
273 let if_not_zero_locations = if loc.statement_index == 0 {
276 Some(Location { block: loc.block, statement_index: loc.statement_index - 1 })
279 if_zero_locations.into_iter().flatten().chain(if_not_zero_locations)
283 pub fn dominators(&self) -> Dominators<BasicBlock> {
287 /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the
289 pub fn is_cfg_cyclic(&self) -> bool {
290 graph::is_cyclic(self)
294 pub fn local_kind(&self, local: Local) -> LocalKind {
295 let index = local.as_usize();
298 self.local_decls[local].mutability == Mutability::Mut,
299 "return place should be mutable"
302 LocalKind::ReturnPointer
303 } else if index < self.arg_count + 1 {
305 } else if self.local_decls[local].is_user_variable() {
312 /// Returns an iterator over all temporaries.
314 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
315 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
316 let local = Local::new(index);
317 if self.local_decls[local].is_user_variable() {
325 /// Returns an iterator over all user-declared locals.
327 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
328 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
329 let local = Local::new(index);
330 if self.local_decls[local].is_user_variable() {
338 /// Returns an iterator over all user-declared mutable locals.
340 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
341 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
342 let local = Local::new(index);
343 let decl = &self.local_decls[local];
344 if decl.is_user_variable() && decl.mutability == Mutability::Mut {
352 /// Returns an iterator over all user-declared mutable arguments and locals.
354 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
355 (1..self.local_decls.len()).filter_map(move |index| {
356 let local = Local::new(index);
357 let decl = &self.local_decls[local];
358 if (decl.is_user_variable() || index < self.arg_count + 1)
359 && decl.mutability == Mutability::Mut
368 /// Returns an iterator over all function arguments.
370 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
371 let arg_count = self.arg_count;
372 (1..=arg_count).map(Local::new)
375 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
376 /// locals that are neither arguments nor the return place).
378 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
379 let arg_count = self.arg_count;
380 let local_count = self.local_decls.len();
381 (arg_count + 1..local_count).map(Local::new)
384 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
385 /// invalidating statement indices in `Location`s.
386 pub fn make_statement_nop(&mut self, location: Location) {
387 let block = &mut self[location.block];
388 debug_assert!(location.statement_index < block.statements.len());
389 block.statements[location.statement_index].make_nop()
392 /// Returns the source info associated with `location`.
393 pub fn source_info(&self, location: Location) -> &SourceInfo {
394 let block = &self[location.block];
395 let stmts = &block.statements;
396 let idx = location.statement_index;
397 if idx < stmts.len() {
398 &stmts[idx].source_info
400 assert_eq!(idx, stmts.len());
401 &block.terminator().source_info
405 /// Checks if `sub` is a sub scope of `sup`
406 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
408 match self.source_scopes[sub].parent_scope {
409 None => return false,
416 /// Returns the return type; it always return first element from `local_decls` array.
417 pub fn return_ty(&self) -> Ty<'tcx> {
418 self.local_decls[RETURN_PLACE].ty
421 /// Gets the location of the terminator for the given block.
422 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
423 Location { block: bb, statement_index: self[bb].statements.len() }
427 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
430 /// Unsafe because of a PushUnsafeBlock
432 /// Unsafe because of an unsafe fn
434 /// Unsafe because of an `unsafe` block
435 ExplicitUnsafe(hir::HirId),
438 impl<'tcx> Index<BasicBlock> for Body<'tcx> {
439 type Output = BasicBlockData<'tcx>;
442 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
443 &self.basic_blocks()[index]
447 impl<'tcx> IndexMut<BasicBlock> for Body<'tcx> {
449 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
450 &mut self.basic_blocks_mut()[index]
454 #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)]
455 pub enum ClearCrossCrate<T> {
460 impl<T> ClearCrossCrate<T> {
461 pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
463 ClearCrossCrate::Clear => ClearCrossCrate::Clear,
464 ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
468 pub fn assert_crate_local(self) -> T {
470 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
471 ClearCrossCrate::Set(v) => v,
476 impl<T: Encodable> rustc_serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
477 impl<T: Decodable> rustc_serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
479 /// Grouped information about the source code origin of a MIR entity.
480 /// Intended to be inspected by diagnostics and debuginfo.
481 /// Most passes can work with it as a whole, within a single function.
482 // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and
483 // `Hash`. Please ping @bjorn3 if removing them.
484 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
485 pub struct SourceInfo {
486 /// The source span for the AST pertaining to this MIR entity.
489 /// The source scope, keeping track of which bindings can be
490 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
491 pub scope: SourceScope,
494 ///////////////////////////////////////////////////////////////////////////
495 // Mutability and borrow kinds
497 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
498 pub enum Mutability {
503 impl From<Mutability> for hir::Mutability {
504 fn from(m: Mutability) -> Self {
506 Mutability::Mut => hir::Mutability::Mutable,
507 Mutability::Not => hir::Mutability::Immutable,
513 Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable, HashStable,
515 pub enum BorrowKind {
516 /// Data must be immutable and is aliasable.
519 /// The immediately borrowed place must be immutable, but projections from
520 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
521 /// conflict with a mutable borrow of `a.b.c`.
523 /// This is used when lowering matches: when matching on a place we want to
524 /// ensure that place have the same value from the start of the match until
525 /// an arm is selected. This prevents this code from compiling:
527 /// let mut x = &Some(0);
530 /// Some(_) if { x = &None; false } => (),
534 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
535 /// should not prevent `if let None = x { ... }`, for example, because the
536 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
537 /// We can also report errors with this kind of borrow differently.
540 /// Data must be immutable but not aliasable. This kind of borrow
541 /// cannot currently be expressed by the user and is used only in
542 /// implicit closure bindings. It is needed when the closure is
543 /// borrowing or mutating a mutable referent, e.g.:
545 /// let x: &mut isize = ...;
546 /// let y = || *x += 5;
548 /// If we were to try to translate this closure into a more explicit
549 /// form, we'd encounter an error with the code as written:
551 /// struct Env { x: & &mut isize }
552 /// let x: &mut isize = ...;
553 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
554 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
556 /// This is then illegal because you cannot mutate an `&mut` found
557 /// in an aliasable location. To solve, you'd have to translate with
558 /// an `&mut` borrow:
560 /// struct Env { x: & &mut isize }
561 /// let x: &mut isize = ...;
562 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
563 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
565 /// Now the assignment to `**env.x` is legal, but creating a
566 /// mutable pointer to `x` is not because `x` is not mutable. We
567 /// could fix this by declaring `x` as `let mut x`. This is ok in
568 /// user code, if awkward, but extra weird for closures, since the
569 /// borrow is hidden.
571 /// So we introduce a "unique imm" borrow -- the referent is
572 /// immutable, but not aliasable. This solves the problem. For
573 /// simplicity, we don't give users the way to express this
574 /// borrow, it's just used when translating closures.
577 /// Data is mutable and not aliasable.
579 /// `true` if this borrow arose from method-call auto-ref
580 /// (i.e., `adjustment::Adjust::Borrow`).
581 allow_two_phase_borrow: bool,
586 pub fn allows_two_phase_borrow(&self) -> bool {
588 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
589 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
594 ///////////////////////////////////////////////////////////////////////////
595 // Variables and temps
597 rustc_index::newtype_index! {
600 DEBUG_FORMAT = "_{}",
601 const RETURN_PLACE = 0,
605 impl Atom for Local {
606 fn index(self) -> usize {
611 /// Classifies locals into categories. See `Body::local_kind`.
612 #[derive(PartialEq, Eq, Debug, HashStable)]
614 /// User-declared variable binding.
616 /// Compiler-introduced temporary.
618 /// Function argument.
620 /// Location of function's return value.
624 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
625 pub struct VarBindingForm<'tcx> {
626 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
627 pub binding_mode: ty::BindingMode,
628 /// If an explicit type was provided for this variable binding,
629 /// this holds the source Span of that type.
631 /// NOTE: if you want to change this to a `HirId`, be wary that
632 /// doing so breaks incremental compilation (as of this writing),
633 /// while a `Span` does not cause our tests to fail.
634 pub opt_ty_info: Option<Span>,
635 /// Place of the RHS of the =, or the subject of the `match` where this
636 /// variable is initialized. None in the case of `let PATTERN;`.
637 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
638 /// (a) the right-hand side isn't evaluated as a place expression.
639 /// (b) it gives a way to separate this case from the remaining cases
641 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
642 /// The span of the pattern in which this variable was bound.
646 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
647 pub enum BindingForm<'tcx> {
648 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
649 Var(VarBindingForm<'tcx>),
650 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
651 ImplicitSelf(ImplicitSelfKind),
652 /// Reference used in a guard expression to ensure immutability.
656 /// Represents what type of implicit self a function has, if any.
657 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable)]
658 pub enum ImplicitSelfKind {
659 /// Represents a `fn x(self);`.
661 /// Represents a `fn x(mut self);`.
663 /// Represents a `fn x(&self);`.
665 /// Represents a `fn x(&mut self);`.
667 /// Represents when a function does not have a self argument or
668 /// when a function has a `self: X` argument.
672 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
674 mod binding_form_impl {
675 use crate::ich::StableHashingContext;
676 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
678 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
679 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
680 use super::BindingForm::*;
681 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
684 Var(binding) => binding.hash_stable(hcx, hasher),
685 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
692 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
693 /// created during evaluation of expressions in a block tail
694 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
696 /// It is used to improve diagnostics when such temporaries are
697 /// involved in borrow_check errors, e.g., explanations of where the
698 /// temporaries come from, when their destructors are run, and/or how
699 /// one might revise the code to satisfy the borrow checker's rules.
700 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
701 pub struct BlockTailInfo {
702 /// If `true`, then the value resulting from evaluating this tail
703 /// expression is ignored by the block's expression context.
705 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
706 /// but not e.g., `let _x = { ...; tail };`
707 pub tail_result_is_ignored: bool,
712 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
713 /// argument, or the return place.
714 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
715 pub struct LocalDecl<'tcx> {
716 /// Whether this is a mutable minding (i.e., `let x` or `let mut x`).
718 /// Temporaries and the return place are always mutable.
719 pub mutability: Mutability,
721 // FIXME(matthewjasper) Don't store in this in `Body`
722 pub local_info: LocalInfo<'tcx>,
724 /// `true` if this is an internal local.
726 /// These locals are not based on types in the source code and are only used
727 /// for a few desugarings at the moment.
729 /// The generator transformation will sanity check the locals which are live
730 /// across a suspension point against the type components of the generator
731 /// which type checking knows are live across a suspension point. We need to
732 /// flag drop flags to avoid triggering this check as they are introduced
735 /// Unsafety checking will also ignore dereferences of these locals,
736 /// so they can be used for raw pointers only used in a desugaring.
738 /// This should be sound because the drop flags are fully algebraic, and
739 /// therefore don't affect the OIBIT or outlives properties of the
743 /// If this local is a temporary and `is_block_tail` is `Some`,
744 /// then it is a temporary created for evaluation of some
745 /// subexpression of some block's tail expression (with no
746 /// intervening statement context).
747 // FIXME(matthewjasper) Don't store in this in `Body`
748 pub is_block_tail: Option<BlockTailInfo>,
750 /// The type of this local.
753 /// If the user manually ascribed a type to this variable,
754 /// e.g., via `let x: T`, then we carry that type here. The MIR
755 /// borrow checker needs this information since it can affect
756 /// region inference.
757 // FIXME(matthewjasper) Don't store in this in `Body`
758 pub user_ty: UserTypeProjections,
760 /// The *syntactic* (i.e., not visibility) source scope the local is defined
761 /// in. If the local was defined in a let-statement, this
762 /// is *within* the let-statement, rather than outside
765 /// This is needed because the visibility source scope of locals within
766 /// a let-statement is weird.
768 /// The reason is that we want the local to be *within* the let-statement
769 /// for lint purposes, but we want the local to be *after* the let-statement
770 /// for names-in-scope purposes.
772 /// That's it, if we have a let-statement like the one in this
776 /// fn foo(x: &str) {
777 /// #[allow(unused_mut)]
778 /// let mut x: u32 = { // <- one unused mut
779 /// let mut y: u32 = x.parse().unwrap();
786 /// Then, from a lint point of view, the declaration of `x: u32`
787 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
788 /// lint scopes are the same as the AST/HIR nesting.
790 /// However, from a name lookup point of view, the scopes look more like
791 /// as if the let-statements were `match` expressions:
794 /// fn foo(x: &str) {
796 /// match x.parse().unwrap() {
805 /// We care about the name-lookup scopes for debuginfo - if the
806 /// debuginfo instruction pointer is at the call to `x.parse()`, we
807 /// want `x` to refer to `x: &str`, but if it is at the call to
808 /// `drop(x)`, we want it to refer to `x: u32`.
810 /// To allow both uses to work, we need to have more than a single scope
811 /// for a local. We have the `source_info.scope` represent the "syntactic"
812 /// lint scope (with a variable being under its let block) while the
813 /// `var_debug_info.source_info.scope` represents the "local variable"
814 /// scope (where the "rest" of a block is under all prior let-statements).
816 /// The end result looks like this:
820 /// │{ argument x: &str }
822 /// │ │{ #[allow(unused_mut)] } // This is actually split into 2 scopes
823 /// │ │ // in practice because I'm lazy.
825 /// │ │← x.source_info.scope
826 /// │ │← `x.parse().unwrap()`
828 /// │ │ │← y.source_info.scope
830 /// │ │ │{ let y: u32 }
832 /// │ │ │← y.var_debug_info.source_info.scope
835 /// │ │{ let x: u32 }
836 /// │ │← x.var_debug_info.source_info.scope
837 /// │ │← `drop(x)` // This accesses `x: u32`.
839 pub source_info: SourceInfo,
842 /// Extra information about a local that's used for diagnostics.
843 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
844 pub enum LocalInfo<'tcx> {
845 /// A user-defined local variable or function parameter
847 /// The `BindingForm` is solely used for local diagnostics when generating
848 /// warnings/errors when compiling the current crate, and therefore it need
849 /// not be visible across crates.
850 User(ClearCrossCrate<BindingForm<'tcx>>),
851 /// A temporary created that references the static with the given `DefId`.
852 StaticRef { def_id: DefId, is_thread_local: bool },
853 /// Any other temporary, the return place, or an anonymous function parameter.
857 impl<'tcx> LocalDecl<'tcx> {
858 /// Returns `true` only if local is a binding that can itself be
859 /// made mutable via the addition of the `mut` keyword, namely
860 /// something like the occurrences of `x` in:
861 /// - `fn foo(x: Type) { ... }`,
863 /// - or `match ... { C(x) => ... }`
864 pub fn can_be_made_mutable(&self) -> bool {
865 match self.local_info {
866 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
867 binding_mode: ty::BindingMode::BindByValue(_),
874 ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)),
881 /// Returns `true` if local is definitely not a `ref ident` or
882 /// `ref mut ident` binding. (Such bindings cannot be made into
883 /// mutable bindings, but the inverse does not necessarily hold).
884 pub fn is_nonref_binding(&self) -> bool {
885 match self.local_info {
886 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
887 binding_mode: ty::BindingMode::BindByValue(_),
893 LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
899 /// Returns `true` if this variable is a named variable or function
900 /// parameter declared by the user.
902 pub fn is_user_variable(&self) -> bool {
903 match self.local_info {
904 LocalInfo::User(_) => true,
909 /// Returns `true` if this is a reference to a variable bound in a `match`
910 /// expression that is used to access said variable for the guard of the
912 pub fn is_ref_for_guard(&self) -> bool {
913 match self.local_info {
914 LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)) => true,
919 /// Returns `Some` if this is a reference to a static item that is used to
920 /// access that static
921 pub fn is_ref_to_static(&self) -> bool {
922 match self.local_info {
923 LocalInfo::StaticRef { .. } => true,
928 /// Returns `Some` if this is a reference to a static item that is used to
929 /// access that static
930 pub fn is_ref_to_thread_local(&self) -> bool {
931 match self.local_info {
932 LocalInfo::StaticRef { is_thread_local, .. } => is_thread_local,
937 /// Returns `true` is the local is from a compiler desugaring, e.g.,
938 /// `__next` from a `for` loop.
940 pub fn from_compiler_desugaring(&self) -> bool {
941 self.source_info.span.desugaring_kind().is_some()
944 /// Creates a new `LocalDecl` for a temporary.
946 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
947 Self::new_local(ty, Mutability::Mut, false, span)
950 /// Converts `self` into same `LocalDecl` except tagged as immutable.
952 pub fn immutable(mut self) -> Self {
953 self.mutability = Mutability::Not;
957 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
959 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
960 assert!(self.is_block_tail.is_none());
961 self.is_block_tail = Some(info);
965 /// Creates a new `LocalDecl` for a internal temporary.
967 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
968 Self::new_local(ty, Mutability::Mut, true, span)
972 fn new_local(ty: Ty<'tcx>, mutability: Mutability, internal: bool, span: Span) -> Self {
976 user_ty: UserTypeProjections::none(),
977 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
979 local_info: LocalInfo::Other,
984 /// Builds a `LocalDecl` for the return place.
986 /// This must be inserted into the `local_decls` list as the first local.
988 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
990 mutability: Mutability::Mut,
992 user_ty: UserTypeProjections::none(),
993 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
996 local_info: LocalInfo::Other,
1001 /// Debug information pertaining to a user variable.
1002 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1003 pub struct VarDebugInfo<'tcx> {
1006 /// Source info of the user variable, including the scope
1007 /// within which the variable is visible (to debuginfo)
1008 /// (see `LocalDecl`'s `source_info` field for more details).
1009 pub source_info: SourceInfo,
1011 /// Where the data for this user variable is to be found.
1012 /// NOTE(eddyb) There's an unenforced invariant that this `Place` is
1013 /// based on a `Local`, not a `Static`, and contains no indexing.
1014 pub place: Place<'tcx>,
1017 ///////////////////////////////////////////////////////////////////////////
1020 rustc_index::newtype_index! {
1021 pub struct BasicBlock {
1023 DEBUG_FORMAT = "bb{}",
1024 const START_BLOCK = 0,
1029 pub fn start_location(self) -> Location {
1030 Location { block: self, statement_index: 0 }
1034 ///////////////////////////////////////////////////////////////////////////
1035 // BasicBlockData and Terminator
1037 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1038 pub struct BasicBlockData<'tcx> {
1039 /// List of statements in this block.
1040 pub statements: Vec<Statement<'tcx>>,
1042 /// Terminator for this block.
1044 /// N.B., this should generally ONLY be `None` during construction.
1045 /// Therefore, you should generally access it via the
1046 /// `terminator()` or `terminator_mut()` methods. The only
1047 /// exception is that certain passes, such as `simplify_cfg`, swap
1048 /// out the terminator temporarily with `None` while they continue
1049 /// to recurse over the set of basic blocks.
1050 pub terminator: Option<Terminator<'tcx>>,
1052 /// If true, this block lies on an unwind path. This is used
1053 /// during codegen where distinct kinds of basic blocks may be
1054 /// generated (particularly for MSVC cleanup). Unwind blocks must
1055 /// only branch to other unwind blocks.
1056 pub is_cleanup: bool,
1059 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
1060 pub struct Terminator<'tcx> {
1061 pub source_info: SourceInfo,
1062 pub kind: TerminatorKind<'tcx>,
1065 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
1066 pub enum TerminatorKind<'tcx> {
1067 /// Block should have one successor in the graph; we jump there.
1068 Goto { target: BasicBlock },
1070 /// Operand evaluates to an integer; jump depending on its value
1071 /// to one of the targets, and otherwise fallback to `otherwise`.
1073 /// The discriminant value being tested.
1074 discr: Operand<'tcx>,
1076 /// The type of value being tested.
1077 switch_ty: Ty<'tcx>,
1079 /// Possible values. The locations to branch to in each case
1080 /// are found in the corresponding indices from the `targets` vector.
1081 values: Cow<'tcx, [u128]>,
1083 /// Possible branch sites. The last element of this vector is used
1084 /// for the otherwise branch, so targets.len() == values.len() + 1
1087 // This invariant is quite non-obvious and also could be improved.
1088 // One way to make this invariant is to have something like this instead:
1090 // branches: Vec<(ConstInt, BasicBlock)>,
1091 // otherwise: Option<BasicBlock> // exhaustive if None
1093 // However we’ve decided to keep this as-is until we figure a case
1094 // where some other approach seems to be strictly better than other.
1095 targets: Vec<BasicBlock>,
1098 /// Indicates that the landing pad is finished and unwinding should
1099 /// continue. Emitted by `build::scope::diverge_cleanup`.
1102 /// Indicates that the landing pad is finished and that the process
1103 /// should abort. Used to prevent unwinding for foreign items.
1106 /// Indicates a normal return. The return place should have
1107 /// been filled in by now. This should occur at most once.
1110 /// Indicates a terminator that can never be reached.
1113 /// Drop the `Place`.
1114 Drop { location: Place<'tcx>, target: BasicBlock, unwind: Option<BasicBlock> },
1116 /// Drop the `Place` and assign the new value over it. This ensures
1117 /// that the assignment to `P` occurs *even if* the destructor for
1118 /// place unwinds. Its semantics are best explained by the
1123 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1131 /// Drop(P, goto BB1, unwind BB2)
1134 /// // P is now uninitialized
1138 /// // P is now uninitialized -- its dtor panicked
1143 location: Place<'tcx>,
1144 value: Operand<'tcx>,
1146 unwind: Option<BasicBlock>,
1149 /// Block ends with a call of a converging function.
1151 /// The function that’s being called.
1152 func: Operand<'tcx>,
1153 /// Arguments the function is called with.
1154 /// These are owned by the callee, which is free to modify them.
1155 /// This allows the memory occupied by "by-value" arguments to be
1156 /// reused across function calls without duplicating the contents.
1157 args: Vec<Operand<'tcx>>,
1158 /// Destination for the return value. If some, the call is converging.
1159 destination: Option<(Place<'tcx>, BasicBlock)>,
1160 /// Cleanups to be done if the call unwinds.
1161 cleanup: Option<BasicBlock>,
1162 /// `true` if this is from a call in HIR rather than from an overloaded
1163 /// operator. True for overloaded function call.
1164 from_hir_call: bool,
1167 /// Jump to the target if the condition has the expected value,
1168 /// otherwise panic with a message and a cleanup target.
1170 cond: Operand<'tcx>,
1172 msg: AssertMessage<'tcx>,
1174 cleanup: Option<BasicBlock>,
1177 /// A suspend point.
1179 /// The value to return.
1180 value: Operand<'tcx>,
1181 /// Where to resume to.
1183 /// Cleanup to be done if the generator is dropped at this suspend point.
1184 drop: Option<BasicBlock>,
1187 /// Indicates the end of the dropping of a generator.
1190 /// A block where control flow only ever takes one real path, but borrowck
1191 /// needs to be more conservative.
1193 /// The target normal control flow will take.
1194 real_target: BasicBlock,
1195 /// A block control flow could conceptually jump to, but won't in
1197 imaginary_target: BasicBlock,
1199 /// A terminator for blocks that only take one path in reality, but where we
1200 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1201 /// This can arise in infinite loops with no function calls for example.
1203 /// The target normal control flow will take.
1204 real_target: BasicBlock,
1205 /// The imaginary cleanup block link. This particular path will never be taken
1206 /// in practice, but in order to avoid fragility we want to always
1207 /// consider it in borrowck. We don't want to accept programs which
1208 /// pass borrowck only when `panic=abort` or some assertions are disabled
1209 /// due to release vs. debug mode builds. This needs to be an `Option` because
1210 /// of the `remove_noop_landing_pads` and `no_landing_pads` passes.
1211 unwind: Option<BasicBlock>,
1215 pub type Successors<'a> =
1216 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1217 pub type SuccessorsMut<'a> =
1218 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1220 impl<'tcx> Terminator<'tcx> {
1221 pub fn successors(&self) -> Successors<'_> {
1222 self.kind.successors()
1225 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1226 self.kind.successors_mut()
1229 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1233 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1234 self.kind.unwind_mut()
1238 impl<'tcx> TerminatorKind<'tcx> {
1241 cond: Operand<'tcx>,
1244 ) -> TerminatorKind<'tcx> {
1245 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1246 TerminatorKind::SwitchInt {
1248 switch_ty: tcx.types.bool,
1249 values: From::from(BOOL_SWITCH_FALSE),
1250 targets: vec![f, t],
1254 pub fn successors(&self) -> Successors<'_> {
1255 use self::TerminatorKind::*;
1262 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&[]),
1263 Goto { target: ref t }
1264 | Call { destination: None, cleanup: Some(ref t), .. }
1265 | Call { destination: Some((_, ref t)), cleanup: None, .. }
1266 | Yield { resume: ref t, drop: None, .. }
1267 | DropAndReplace { target: ref t, unwind: None, .. }
1268 | Drop { target: ref t, unwind: None, .. }
1269 | Assert { target: ref t, cleanup: None, .. }
1270 | FalseUnwind { real_target: ref t, unwind: None } => Some(t).into_iter().chain(&[]),
1271 Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. }
1272 | Yield { resume: ref t, drop: Some(ref u), .. }
1273 | DropAndReplace { target: ref t, unwind: Some(ref u), .. }
1274 | Drop { target: ref t, unwind: Some(ref u), .. }
1275 | Assert { target: ref t, cleanup: Some(ref u), .. }
1276 | FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
1277 Some(t).into_iter().chain(slice::from_ref(u))
1279 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1280 FalseEdges { ref real_target, ref imaginary_target } => {
1281 Some(real_target).into_iter().chain(slice::from_ref(imaginary_target))
1286 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1287 use self::TerminatorKind::*;
1294 | Call { destination: None, cleanup: None, .. } => None.into_iter().chain(&mut []),
1295 Goto { target: ref mut t }
1296 | Call { destination: None, cleanup: Some(ref mut t), .. }
1297 | Call { destination: Some((_, ref mut t)), cleanup: None, .. }
1298 | Yield { resume: ref mut t, drop: None, .. }
1299 | DropAndReplace { target: ref mut t, unwind: None, .. }
1300 | Drop { target: ref mut t, unwind: None, .. }
1301 | Assert { target: ref mut t, cleanup: None, .. }
1302 | FalseUnwind { real_target: ref mut t, unwind: None } => {
1303 Some(t).into_iter().chain(&mut [])
1305 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. }
1306 | Yield { resume: ref mut t, drop: Some(ref mut u), .. }
1307 | DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. }
1308 | Drop { target: ref mut t, unwind: Some(ref mut u), .. }
1309 | Assert { target: ref mut t, cleanup: Some(ref mut u), .. }
1310 | FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
1311 Some(t).into_iter().chain(slice::from_mut(u))
1313 SwitchInt { ref mut targets, .. } => None.into_iter().chain(&mut targets[..]),
1314 FalseEdges { ref mut real_target, ref mut imaginary_target } => {
1315 Some(real_target).into_iter().chain(slice::from_mut(imaginary_target))
1320 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1322 TerminatorKind::Goto { .. }
1323 | TerminatorKind::Resume
1324 | TerminatorKind::Abort
1325 | TerminatorKind::Return
1326 | TerminatorKind::Unreachable
1327 | TerminatorKind::GeneratorDrop
1328 | TerminatorKind::Yield { .. }
1329 | TerminatorKind::SwitchInt { .. }
1330 | TerminatorKind::FalseEdges { .. } => None,
1331 TerminatorKind::Call { cleanup: ref unwind, .. }
1332 | TerminatorKind::Assert { cleanup: ref unwind, .. }
1333 | TerminatorKind::DropAndReplace { ref unwind, .. }
1334 | TerminatorKind::Drop { ref unwind, .. }
1335 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1339 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1341 TerminatorKind::Goto { .. }
1342 | TerminatorKind::Resume
1343 | TerminatorKind::Abort
1344 | TerminatorKind::Return
1345 | TerminatorKind::Unreachable
1346 | TerminatorKind::GeneratorDrop
1347 | TerminatorKind::Yield { .. }
1348 | TerminatorKind::SwitchInt { .. }
1349 | TerminatorKind::FalseEdges { .. } => None,
1350 TerminatorKind::Call { cleanup: ref mut unwind, .. }
1351 | TerminatorKind::Assert { cleanup: ref mut unwind, .. }
1352 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1353 | TerminatorKind::Drop { ref mut unwind, .. }
1354 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1359 impl<'tcx> BasicBlockData<'tcx> {
1360 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1361 BasicBlockData { statements: vec![], terminator, is_cleanup: false }
1364 /// Accessor for terminator.
1366 /// Terminator may not be None after construction of the basic block is complete. This accessor
1367 /// provides a convenience way to reach the terminator.
1368 pub fn terminator(&self) -> &Terminator<'tcx> {
1369 self.terminator.as_ref().expect("invalid terminator state")
1372 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1373 self.terminator.as_mut().expect("invalid terminator state")
1376 pub fn retain_statements<F>(&mut self, mut f: F)
1378 F: FnMut(&mut Statement<'_>) -> bool,
1380 for s in &mut self.statements {
1387 pub fn expand_statements<F, I>(&mut self, mut f: F)
1389 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1390 I: iter::TrustedLen<Item = Statement<'tcx>>,
1392 // Gather all the iterators we'll need to splice in, and their positions.
1393 let mut splices: Vec<(usize, I)> = vec![];
1394 let mut extra_stmts = 0;
1395 for (i, s) in self.statements.iter_mut().enumerate() {
1396 if let Some(mut new_stmts) = f(s) {
1397 if let Some(first) = new_stmts.next() {
1398 // We can already store the first new statement.
1401 // Save the other statements for optimized splicing.
1402 let remaining = new_stmts.size_hint().0;
1404 splices.push((i + 1 + extra_stmts, new_stmts));
1405 extra_stmts += remaining;
1413 // Splice in the new statements, from the end of the block.
1414 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1415 // where a range of elements ("gap") is left uninitialized, with
1416 // splicing adding new elements to the end of that gap and moving
1417 // existing elements from before the gap to the end of the gap.
1418 // For now, this is safe code, emulating a gap but initializing it.
1419 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1420 self.statements.resize(
1423 source_info: SourceInfo { span: DUMMY_SP, scope: OUTERMOST_SOURCE_SCOPE },
1424 kind: StatementKind::Nop,
1427 for (splice_start, new_stmts) in splices.into_iter().rev() {
1428 let splice_end = splice_start + new_stmts.size_hint().0;
1429 while gap.end > splice_end {
1432 self.statements.swap(gap.start, gap.end);
1434 self.statements.splice(splice_start..splice_end, new_stmts);
1435 gap.end = splice_start;
1439 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1440 if index < self.statements.len() {
1441 &self.statements[index]
1448 impl<'tcx> Debug for TerminatorKind<'tcx> {
1449 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1450 self.fmt_head(fmt)?;
1451 let successor_count = self.successors().count();
1452 let labels = self.fmt_successor_labels();
1453 assert_eq!(successor_count, labels.len());
1455 match successor_count {
1458 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1461 write!(fmt, " -> [")?;
1462 for (i, target) in self.successors().enumerate() {
1466 write!(fmt, "{}: {:?}", labels[i], target)?;
1474 impl<'tcx> TerminatorKind<'tcx> {
1475 /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
1476 /// successor basic block, if any. The only information not included is the list of possible
1477 /// successors, which may be rendered differently between the text and the graphviz format.
1478 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1479 use self::TerminatorKind::*;
1481 Goto { .. } => write!(fmt, "goto"),
1482 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1483 Return => write!(fmt, "return"),
1484 GeneratorDrop => write!(fmt, "generator_drop"),
1485 Resume => write!(fmt, "resume"),
1486 Abort => write!(fmt, "abort"),
1487 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1488 Unreachable => write!(fmt, "unreachable"),
1489 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1490 DropAndReplace { ref location, ref value, .. } => {
1491 write!(fmt, "replace({:?} <- {:?})", location, value)
1493 Call { ref func, ref args, ref destination, .. } => {
1494 if let Some((ref destination, _)) = *destination {
1495 write!(fmt, "{:?} = ", destination)?;
1497 write!(fmt, "{:?}(", func)?;
1498 for (index, arg) in args.iter().enumerate() {
1502 write!(fmt, "{:?}", arg)?;
1506 Assert { ref cond, expected, ref msg, .. } => {
1507 write!(fmt, "assert(")?;
1511 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1513 FalseEdges { .. } => write!(fmt, "falseEdges"),
1514 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1518 /// Returns the list of labels for the edges to the successor basic blocks.
1519 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1520 use self::TerminatorKind::*;
1522 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1523 Goto { .. } => vec!["".into()],
1524 SwitchInt { ref values, switch_ty, .. } => ty::tls::with(|tcx| {
1525 let param_env = ty::ParamEnv::empty();
1526 let switch_ty = tcx.lift(&switch_ty).unwrap();
1527 let size = tcx.layout_of(param_env.and(switch_ty)).unwrap().size;
1531 ty::Const::from_scalar(
1533 Scalar::from_uint(u, size).into(),
1539 .chain(iter::once("otherwise".into()))
1542 Call { destination: Some(_), cleanup: Some(_), .. } => {
1543 vec!["return".into(), "unwind".into()]
1545 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into()],
1546 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into()],
1547 Call { destination: None, cleanup: None, .. } => vec![],
1548 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1549 Yield { drop: None, .. } => vec!["resume".into()],
1550 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1551 vec!["return".into()]
1553 DropAndReplace { unwind: Some(_), .. } | Drop { unwind: Some(_), .. } => {
1554 vec!["return".into(), "unwind".into()]
1556 Assert { cleanup: None, .. } => vec!["".into()],
1557 Assert { .. } => vec!["success".into(), "unwind".into()],
1558 FalseEdges { .. } => vec!["real".into(), "imaginary".into()],
1559 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1560 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1565 ///////////////////////////////////////////////////////////////////////////
1568 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1569 pub struct Statement<'tcx> {
1570 pub source_info: SourceInfo,
1571 pub kind: StatementKind<'tcx>,
1574 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1575 #[cfg(target_arch = "x86_64")]
1576 static_assert_size!(Statement<'_>, 32);
1578 impl Statement<'_> {
1579 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1580 /// invalidating statement indices in `Location`s.
1581 pub fn make_nop(&mut self) {
1582 self.kind = StatementKind::Nop
1585 /// Changes a statement to a nop and returns the original statement.
1586 pub fn replace_nop(&mut self) -> Self {
1588 source_info: self.source_info,
1589 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1594 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1595 pub enum StatementKind<'tcx> {
1596 /// Write the RHS Rvalue to the LHS Place.
1597 Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
1599 /// This represents all the reading that a pattern match may do
1600 /// (e.g., inspecting constants and discriminant values), and the
1601 /// kind of pattern it comes from. This is in order to adapt potential
1602 /// error messages to these specific patterns.
1604 /// Note that this also is emitted for regular `let` bindings to ensure that locals that are
1605 /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;`
1606 FakeRead(FakeReadCause, Box<Place<'tcx>>),
1608 /// Write the discriminant for a variant to the enum Place.
1609 SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
1611 /// Start a live range for the storage of the local.
1614 /// End the current live range for the storage of the local.
1617 /// Executes a piece of inline Assembly. Stored in a Box to keep the size
1618 /// of `StatementKind` low.
1619 InlineAsm(Box<InlineAsm<'tcx>>),
1621 /// Retag references in the given place, ensuring they got fresh tags. This is
1622 /// part of the Stacked Borrows model. These statements are currently only interpreted
1623 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1624 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1625 /// for more details.
1626 Retag(RetagKind, Box<Place<'tcx>>),
1628 /// Encodes a user's type ascription. These need to be preserved
1629 /// intact so that NLL can respect them. For example:
1633 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1634 /// to the user-given type `T`. The effect depends on the specified variance:
1636 /// - `Covariant` -- requires that `T_y <: T`
1637 /// - `Contravariant` -- requires that `T_y :> T`
1638 /// - `Invariant` -- requires that `T_y == T`
1639 /// - `Bivariant` -- no effect
1640 AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
1642 /// No-op. Useful for deleting instructions without affecting statement indices.
1646 /// Describes what kind of retag is to be performed.
1647 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, HashStable)]
1648 pub enum RetagKind {
1649 /// The initial retag when entering a function.
1651 /// Retag preparing for a two-phase borrow.
1653 /// Retagging raw pointers.
1655 /// A "normal" retag.
1659 /// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
1660 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable, PartialEq)]
1661 pub enum FakeReadCause {
1662 /// Inject a fake read of the borrowed input at the end of each guards
1665 /// This should ensure that you cannot change the variant for an enum while
1666 /// you are in the midst of matching on it.
1669 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1670 /// generate a read of x to check that it is initialized and safe.
1673 /// A fake read of the RefWithinGuard version of a bind-by-value variable
1674 /// in a match guard to ensure that it's value hasn't change by the time
1675 /// we create the OutsideGuard version.
1678 /// Officially, the semantics of
1680 /// `let pattern = <expr>;`
1682 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1683 /// into the pattern.
1685 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1686 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1687 /// but in some cases it can affect the borrow checker, as in #53695.
1688 /// Therefore, we insert a "fake read" here to ensure that we get
1689 /// appropriate errors.
1692 /// If we have an index expression like
1694 /// (*x)[1][{ x = y; 4}]
1696 /// then the first bounds check is invalidated when we evaluate the second
1697 /// index expression. Thus we create a fake borrow of `x` across the second
1698 /// indexer, which will cause a borrow check error.
1702 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
1703 pub struct InlineAsm<'tcx> {
1704 pub asm: hir::InlineAsmInner,
1705 pub outputs: Box<[Place<'tcx>]>,
1706 pub inputs: Box<[(Span, Operand<'tcx>)]>,
1709 impl Debug for Statement<'_> {
1710 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1711 use self::StatementKind::*;
1713 Assign(box(ref place, ref rv)) => write!(fmt, "{:?} = {:?}", place, rv),
1714 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1715 Retag(ref kind, ref place) => write!(
1719 RetagKind::FnEntry => "[fn entry] ",
1720 RetagKind::TwoPhase => "[2phase] ",
1721 RetagKind::Raw => "[raw] ",
1722 RetagKind::Default => "",
1726 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1727 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1728 SetDiscriminant { ref place, variant_index } => {
1729 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1731 InlineAsm(ref asm) => {
1732 write!(fmt, "asm!({:?} : {:?} : {:?})", asm.asm, asm.outputs, asm.inputs)
1734 AscribeUserType(box(ref place, ref c_ty), ref variance) => {
1735 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1737 Nop => write!(fmt, "nop"),
1742 ///////////////////////////////////////////////////////////////////////////
1745 /// A path to a value; something that can be evaluated without
1746 /// changing or disturbing program state.
1748 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, HashStable,
1750 pub struct Place<'tcx> {
1751 pub base: PlaceBase<'tcx>,
1753 /// projection out of a place (access a field, deref a pointer, etc)
1754 pub projection: &'tcx List<PlaceElem<'tcx>>,
1757 impl<'tcx> rustc_serialize::UseSpecializedDecodable for Place<'tcx> {}
1760 Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, HashStable,
1762 pub enum PlaceBase<'tcx> {
1766 /// static or static mut variable
1767 Static(Box<Static<'tcx>>),
1770 /// We store the normalized type to avoid requiring normalization when reading MIR
1771 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
1772 RustcEncodable, RustcDecodable, HashStable)]
1773 pub struct Static<'tcx> {
1775 pub kind: StaticKind<'tcx>,
1776 /// The `DefId` of the item this static was declared in. For promoted values, usually, this is
1777 /// the same as the `DefId` of the `mir::Body` containing the `Place` this promoted appears in.
1778 /// However, after inlining, that might no longer be the case as inlined `Place`s are copied
1779 /// into the calling frame.
1784 Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable, RustcEncodable, RustcDecodable,
1786 pub enum StaticKind<'tcx> {
1787 /// Promoted references consist of an id (`Promoted`) and the substs necessary to monomorphize
1788 /// it. Usually, these substs are just the identity substs for the item. However, the inliner
1789 /// will adjust these substs when it inlines a function based on the substs at the callsite.
1790 Promoted(Promoted, SubstsRef<'tcx>),
1794 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1795 #[derive(RustcEncodable, RustcDecodable, HashStable)]
1796 pub enum ProjectionElem<V, T> {
1801 /// These indices are generated by slice patterns. Easiest to explain
1805 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1806 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1807 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1808 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1811 /// index or -index (in Python terms), depending on from_end
1813 /// thing being indexed must be at least this long
1815 /// counting backwards from end?
1819 /// These indices are generated by slice patterns.
1821 /// slice[from:-to] in Python terms.
1827 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1828 /// this for ADTs with more than one variant. It may be better to
1829 /// just introduce it always, or always for enums.
1831 /// The included Symbol is the name of the variant, used for printing MIR.
1832 Downcast(Option<Symbol>, VariantIdx),
1835 impl<V, T> ProjectionElem<V, T> {
1836 /// Returns `true` if the target of this projection may refer to a different region of memory
1838 fn is_indirect(&self) -> bool {
1840 Self::Deref => true,
1844 | Self::ConstantIndex { .. }
1845 | Self::Subslice { .. }
1846 | Self::Downcast(_, _)
1852 /// Alias for projections as they appear in places, where the base is a place
1853 /// and the index is a local.
1854 pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
1856 impl<'tcx> Copy for PlaceElem<'tcx> { }
1858 // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers.
1859 #[cfg(target_arch = "x86_64")]
1860 static_assert_size!(PlaceElem<'_>, 16);
1862 /// Alias for projections as they appear in `UserTypeProjection`, where we
1863 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1864 pub type ProjectionKind = ProjectionElem<(), ()>;
1866 rustc_index::newtype_index! {
1869 DEBUG_FORMAT = "field[{}]"
1873 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1874 pub struct PlaceRef<'a, 'tcx> {
1875 pub base: &'a PlaceBase<'tcx>,
1876 pub projection: &'a [PlaceElem<'tcx>],
1879 impl<'tcx> Place<'tcx> {
1880 // FIXME change this to a const fn by also making List::empty a const fn.
1881 pub fn return_place() -> Place<'tcx> {
1883 base: PlaceBase::Local(RETURN_PLACE),
1884 projection: List::empty(),
1888 /// Returns `true` if this `Place` contains a `Deref` projection.
1890 /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
1891 /// same region of memory as its base.
1892 pub fn is_indirect(&self) -> bool {
1893 self.projection.iter().any(|elem| elem.is_indirect())
1896 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1897 /// a single deref of a local.
1899 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1900 pub fn local_or_deref_local(&self) -> Option<Local> {
1901 match self.as_ref() {
1903 base: &PlaceBase::Local(local),
1907 base: &PlaceBase::Local(local),
1908 projection: &[ProjectionElem::Deref],
1914 /// If this place represents a local variable like `_X` with no
1915 /// projections, return `Some(_X)`.
1916 pub fn as_local(&self) -> Option<Local> {
1917 self.as_ref().as_local()
1920 pub fn as_ref(&self) -> PlaceRef<'_, 'tcx> {
1923 projection: &self.projection,
1928 impl From<Local> for Place<'_> {
1929 fn from(local: Local) -> Self {
1932 projection: List::empty(),
1937 impl From<Local> for PlaceBase<'_> {
1938 fn from(local: Local) -> Self {
1939 PlaceBase::Local(local)
1943 impl<'a, 'tcx> PlaceRef<'a, 'tcx> {
1944 /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
1945 /// a single deref of a local.
1947 // FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
1948 pub fn local_or_deref_local(&self) -> Option<Local> {
1951 base: PlaceBase::Local(local),
1955 base: PlaceBase::Local(local),
1956 projection: [ProjectionElem::Deref],
1962 /// If this place represents a local variable like `_X` with no
1963 /// projections, return `Some(_X)`.
1964 pub fn as_local(&self) -> Option<Local> {
1966 PlaceRef { base: PlaceBase::Local(l), projection: [] } => Some(*l),
1972 impl Debug for Place<'_> {
1973 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1974 for elem in self.projection.iter().rev() {
1976 ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => {
1977 write!(fmt, "(").unwrap();
1979 ProjectionElem::Deref => {
1980 write!(fmt, "(*").unwrap();
1982 ProjectionElem::Index(_)
1983 | ProjectionElem::ConstantIndex { .. }
1984 | ProjectionElem::Subslice { .. } => {}
1988 write!(fmt, "{:?}", self.base)?;
1990 for elem in self.projection.iter() {
1992 ProjectionElem::Downcast(Some(name), _index) => {
1993 write!(fmt, " as {})", name)?;
1995 ProjectionElem::Downcast(None, index) => {
1996 write!(fmt, " as variant#{:?})", index)?;
1998 ProjectionElem::Deref => {
2001 ProjectionElem::Field(field, ty) => {
2002 write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
2004 ProjectionElem::Index(ref index) => {
2005 write!(fmt, "[{:?}]", index)?;
2007 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
2008 write!(fmt, "[{:?} of {:?}]", offset, min_length)?;
2010 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
2011 write!(fmt, "[-{:?} of {:?}]", offset, min_length)?;
2013 ProjectionElem::Subslice { from, to } if *to == 0 => {
2014 write!(fmt, "[{:?}:]", from)?;
2016 ProjectionElem::Subslice { from, to } if *from == 0 => {
2017 write!(fmt, "[:-{:?}]", to)?;
2019 ProjectionElem::Subslice { from, to } => {
2020 write!(fmt, "[{:?}:-{:?}]", from, to)?;
2029 impl Debug for PlaceBase<'_> {
2030 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2032 PlaceBase::Local(id) => write!(fmt, "{:?}", id),
2033 PlaceBase::Static(box self::Static { ty, kind: StaticKind::Static, def_id }) => {
2034 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.def_path_str(def_id)), ty)
2036 PlaceBase::Static(box self::Static {
2037 ty, kind: StaticKind::Promoted(promoted, _), def_id: _
2039 write!(fmt, "({:?}: {:?})", promoted, ty)
2045 ///////////////////////////////////////////////////////////////////////////
2048 rustc_index::newtype_index! {
2049 pub struct SourceScope {
2051 DEBUG_FORMAT = "scope[{}]",
2052 const OUTERMOST_SOURCE_SCOPE = 0,
2056 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2057 pub struct SourceScopeData {
2059 pub parent_scope: Option<SourceScope>,
2061 /// Crate-local information for this source scope, that can't (and
2062 /// needn't) be tracked across crates.
2063 pub local_data: ClearCrossCrate<SourceScopeLocalData>,
2066 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2067 pub struct SourceScopeLocalData {
2068 /// An `HirId` with lint levels equivalent to this scope's lint levels.
2069 pub lint_root: hir::HirId,
2070 /// The unsafe block that contains this node.
2074 ///////////////////////////////////////////////////////////////////////////
2077 /// These are values that can appear inside an rvalue. They are intentionally
2078 /// limited to prevent rvalues from being nested in one another.
2079 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2080 pub enum Operand<'tcx> {
2081 /// Copy: The value must be available for use afterwards.
2083 /// This implies that the type of the place must be `Copy`; this is true
2084 /// by construction during build, but also checked by the MIR type checker.
2087 /// Move: The value (including old borrows of it) will not be used again.
2089 /// Safe for values of all types (modulo future developments towards `?Move`).
2090 /// Correct usage patterns are enforced by the borrow checker for safe code.
2091 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2094 /// Synthesizes a constant value.
2095 Constant(Box<Constant<'tcx>>),
2098 impl<'tcx> Debug for Operand<'tcx> {
2099 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2100 use self::Operand::*;
2102 Constant(ref a) => write!(fmt, "{:?}", a),
2103 Copy(ref place) => write!(fmt, "{:?}", place),
2104 Move(ref place) => write!(fmt, "move {:?}", place),
2109 impl<'tcx> Operand<'tcx> {
2110 /// Convenience helper to make a constant that refers to the fn
2111 /// with given `DefId` and substs. Since this is used to synthesize
2112 /// MIR, assumes `user_ty` is None.
2113 pub fn function_handle(
2116 substs: SubstsRef<'tcx>,
2119 let ty = tcx.type_of(def_id).subst(tcx, substs);
2120 Operand::Constant(box Constant {
2123 literal: ty::Const::zero_sized(tcx, ty),
2127 pub fn to_copy(&self) -> Self {
2129 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2130 Operand::Move(ref place) => Operand::Copy(place.clone()),
2135 ///////////////////////////////////////////////////////////////////////////
2138 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2139 pub enum Rvalue<'tcx> {
2140 /// x (either a move or copy, depending on type of x)
2144 Repeat(Operand<'tcx>, u64),
2147 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2149 /// length of a [X] or [X;n] value
2152 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2154 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2155 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2157 NullaryOp(NullOp, Ty<'tcx>),
2158 UnaryOp(UnOp, Operand<'tcx>),
2160 /// Read the discriminant of an ADT.
2162 /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot
2163 /// be defined to return, say, a 0) if ADT is not an enum.
2164 Discriminant(Place<'tcx>),
2166 /// Creates an aggregate value, like a tuple or struct. This is
2167 /// only needed because we want to distinguish `dest = Foo { x:
2168 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2169 /// that `Foo` has a destructor. These rvalues can be optimized
2170 /// away after type-checking and before lowering.
2171 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2174 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2177 Pointer(PointerCast),
2180 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2181 pub enum AggregateKind<'tcx> {
2182 /// The type is of the element
2186 /// The second field is the variant index. It's equal to 0 for struct
2187 /// and union expressions. The fourth field is
2188 /// active field number and is present only for union expressions
2189 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
2190 /// active field index would identity the field `c`
2191 Adt(&'tcx AdtDef, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
2193 Closure(DefId, SubstsRef<'tcx>),
2194 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
2197 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2199 /// The `+` operator (addition)
2201 /// The `-` operator (subtraction)
2203 /// The `*` operator (multiplication)
2205 /// The `/` operator (division)
2207 /// The `%` operator (modulus)
2209 /// The `^` operator (bitwise xor)
2211 /// The `&` operator (bitwise and)
2213 /// The `|` operator (bitwise or)
2215 /// The `<<` operator (shift left)
2217 /// The `>>` operator (shift right)
2219 /// The `==` operator (equality)
2221 /// The `<` operator (less than)
2223 /// The `<=` operator (less than or equal to)
2225 /// The `!=` operator (not equal to)
2227 /// The `>=` operator (greater than or equal to)
2229 /// The `>` operator (greater than)
2231 /// The `ptr.offset` operator
2236 pub fn is_checkable(self) -> bool {
2239 Add | Sub | Mul | Shl | Shr => true,
2245 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2247 /// Returns the size of a value of that type
2249 /// Creates a new uninitialized box for a value of that type
2253 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
2255 /// The `!` operator for logical inversion
2257 /// The `-` operator for negation
2261 impl<'tcx> Debug for Rvalue<'tcx> {
2262 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2263 use self::Rvalue::*;
2266 Use(ref place) => write!(fmt, "{:?}", place),
2267 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2268 Len(ref a) => write!(fmt, "Len({:?})", a),
2269 Cast(ref kind, ref place, ref ty) => {
2270 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2272 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2273 CheckedBinaryOp(ref op, ref a, ref b) => {
2274 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2276 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2277 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2278 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2279 Ref(region, borrow_kind, ref place) => {
2280 let kind_str = match borrow_kind {
2281 BorrowKind::Shared => "",
2282 BorrowKind::Shallow => "shallow ",
2283 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2286 // When printing regions, add trailing space if necessary.
2287 let print_region = ty::tls::with(|tcx| {
2288 tcx.sess.verbose() || tcx.sess.opts.debugging_opts.identify_regions
2290 let region = if print_region {
2291 let mut region = region.to_string();
2292 if region.len() > 0 {
2297 // Do not even print 'static
2300 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2303 Aggregate(ref kind, ref places) => {
2304 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2305 let mut tuple_fmt = fmt.debug_tuple("");
2306 for place in places {
2307 tuple_fmt.field(place);
2313 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2315 AggregateKind::Tuple => match places.len() {
2316 0 => write!(fmt, "()"),
2317 1 => write!(fmt, "({:?},)", places[0]),
2318 _ => fmt_tuple(fmt, places),
2321 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2322 let variant_def = &adt_def.variants[variant];
2325 ty::tls::with(|tcx| {
2326 let substs = tcx.lift(&substs).expect("could not lift for printing");
2327 FmtPrinter::new(tcx, f, Namespace::ValueNS)
2328 .print_def_path(variant_def.def_id, substs)?;
2332 match variant_def.ctor_kind {
2333 CtorKind::Const => Ok(()),
2334 CtorKind::Fn => fmt_tuple(fmt, places),
2335 CtorKind::Fictive => {
2336 let mut struct_fmt = fmt.debug_struct("");
2337 for (field, place) in variant_def.fields.iter().zip(places) {
2338 struct_fmt.field(&field.ident.as_str(), place);
2345 AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
2346 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2347 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2348 let substs = tcx.lift(&substs).unwrap();
2351 tcx.def_path_str_with_substs(def_id, substs),
2354 format!("[closure@{:?}]", tcx.hir().span(hir_id))
2356 let mut struct_fmt = fmt.debug_struct(&name);
2358 if let Some(upvars) = tcx.upvars(def_id) {
2359 for (&var_id, place) in upvars.keys().zip(places) {
2360 let var_name = tcx.hir().name(var_id);
2361 struct_fmt.field(&var_name.as_str(), place);
2367 write!(fmt, "[closure]")
2371 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2372 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
2373 let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
2374 let mut struct_fmt = fmt.debug_struct(&name);
2376 if let Some(upvars) = tcx.upvars(def_id) {
2377 for (&var_id, place) in upvars.keys().zip(places) {
2378 let var_name = tcx.hir().name(var_id);
2379 struct_fmt.field(&var_name.as_str(), place);
2385 write!(fmt, "[generator]")
2394 ///////////////////////////////////////////////////////////////////////////
2397 /// Two constants are equal if they are the same constant. Note that
2398 /// this does not necessarily mean that they are "==" in Rust -- in
2399 /// particular one must be wary of `NaN`!
2401 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2402 pub struct Constant<'tcx> {
2405 /// Optional user-given type: for something like
2406 /// `collect::<Vec<_>>`, this would be present and would
2407 /// indicate that `Vec<_>` was explicitly specified.
2409 /// Needed for NLL to impose user-given type constraints.
2410 pub user_ty: Option<UserTypeAnnotationIndex>,
2412 pub literal: &'tcx ty::Const<'tcx>,
2415 impl Constant<'tcx> {
2416 pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
2417 match self.literal.val.try_to_scalar() {
2418 Some(Scalar::Ptr(ptr)) => match tcx.alloc_map.lock().get(ptr.alloc_id) {
2419 Some(GlobalAlloc::Static(def_id)) => Some(def_id),
2422 tcx.sess.delay_span_bug(
2423 DUMMY_SP, "MIR cannot contain dangling const pointers",
2433 /// A collection of projections into user types.
2435 /// They are projections because a binding can occur a part of a
2436 /// parent pattern that has been ascribed a type.
2438 /// Its a collection because there can be multiple type ascriptions on
2439 /// the path from the root of the pattern down to the binding itself.
2444 /// struct S<'a>((i32, &'a str), String);
2445 /// let S((_, w): (i32, &'static str), _): S = ...;
2446 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2447 /// // --------------------------------- ^ (2)
2450 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2451 /// ascribed the type `(i32, &'static str)`.
2453 /// The highlights labelled `(2)` show the whole pattern being
2454 /// ascribed the type `S`.
2456 /// In this example, when we descend to `w`, we will have built up the
2457 /// following two projected types:
2459 /// * base: `S`, projection: `(base.0).1`
2460 /// * base: `(i32, &'static str)`, projection: `base.1`
2462 /// The first will lead to the constraint `w: &'1 str` (for some
2463 /// inferred region `'1`). The second will lead to the constraint `w:
2465 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2466 pub struct UserTypeProjections {
2467 pub(crate) contents: Vec<(UserTypeProjection, Span)>,
2470 impl<'tcx> UserTypeProjections {
2471 pub fn none() -> Self {
2472 UserTypeProjections { contents: vec![] }
2475 pub fn from_projections(projs: impl Iterator<Item = (UserTypeProjection, Span)>) -> Self {
2476 UserTypeProjections { contents: projs.collect() }
2479 pub fn projections_and_spans(&self) -> impl Iterator<Item = &(UserTypeProjection, Span)> {
2480 self.contents.iter()
2483 pub fn projections(&self) -> impl Iterator<Item = &UserTypeProjection> {
2484 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2487 pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self {
2488 self.contents.push((user_ty.clone(), span));
2494 mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection,
2496 self.contents = self.contents.drain(..).map(|(proj, span)| (f(proj), span)).collect();
2500 pub fn index(self) -> Self {
2501 self.map_projections(|pat_ty_proj| pat_ty_proj.index())
2504 pub fn subslice(self, from: u32, to: u32) -> Self {
2505 self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to))
2508 pub fn deref(self) -> Self {
2509 self.map_projections(|pat_ty_proj| pat_ty_proj.deref())
2512 pub fn leaf(self, field: Field) -> Self {
2513 self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field))
2516 pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self {
2517 self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field))
2521 /// Encodes the effect of a user-supplied type annotation on the
2522 /// subcomponents of a pattern. The effect is determined by applying the
2523 /// given list of proejctions to some underlying base type. Often,
2524 /// the projection element list `projs` is empty, in which case this
2525 /// directly encodes a type in `base`. But in the case of complex patterns with
2526 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2527 /// in which case the `projs` vector is used.
2531 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2533 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2534 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2535 /// determined by finding the type of the `.0` field from `T`.
2536 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, PartialEq)]
2537 pub struct UserTypeProjection {
2538 pub base: UserTypeAnnotationIndex,
2539 pub projs: Vec<ProjectionKind>,
2542 impl Copy for ProjectionKind {}
2544 impl UserTypeProjection {
2545 pub(crate) fn index(mut self) -> Self {
2546 self.projs.push(ProjectionElem::Index(()));
2550 pub(crate) fn subslice(mut self, from: u32, to: u32) -> Self {
2551 self.projs.push(ProjectionElem::Subslice { from, to });
2555 pub(crate) fn deref(mut self) -> Self {
2556 self.projs.push(ProjectionElem::Deref);
2560 pub(crate) fn leaf(mut self, field: Field) -> Self {
2561 self.projs.push(ProjectionElem::Field(field, ()));
2565 pub(crate) fn variant(
2567 adt_def: &'tcx AdtDef,
2568 variant_index: VariantIdx,
2571 self.projs.push(ProjectionElem::Downcast(
2572 Some(adt_def.variants[variant_index].ident.name),
2575 self.projs.push(ProjectionElem::Field(field, ()));
2580 CloneTypeFoldableAndLiftImpls! { ProjectionKind, }
2582 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection {
2583 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2584 use crate::mir::ProjectionElem::*;
2586 let base = self.base.fold_with(folder);
2587 let projs: Vec<_> = self
2590 .map(|elem| match elem {
2592 Field(f, ()) => Field(f.clone(), ()),
2593 Index(()) => Index(()),
2594 elem => elem.clone(),
2598 UserTypeProjection { base, projs }
2601 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2602 self.base.visit_with(visitor)
2603 // Note: there's nothing in `self.proj` to visit.
2607 rustc_index::newtype_index! {
2608 pub struct Promoted {
2610 DEBUG_FORMAT = "promoted[{}]"
2614 impl<'tcx> Debug for Constant<'tcx> {
2615 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2616 write!(fmt, "{}", self)
2620 impl<'tcx> Display for Constant<'tcx> {
2621 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2622 write!(fmt, "const ")?;
2623 // FIXME make the default pretty printing of raw pointers more detailed. Here we output the
2624 // debug representation of raw pointers, so that the raw pointers in the mir dump output are
2625 // detailed and just not '{pointer}'.
2626 if let ty::RawPtr(_) = self.literal.ty.kind {
2627 write!(fmt, "{:?} : {}", self.literal.val, self.literal.ty)
2629 write!(fmt, "{}", self.literal)
2634 impl<'tcx> graph::DirectedGraph for Body<'tcx> {
2635 type Node = BasicBlock;
2638 impl<'tcx> graph::WithNumNodes for Body<'tcx> {
2639 fn num_nodes(&self) -> usize {
2640 self.basic_blocks.len()
2644 impl<'tcx> graph::WithStartNode for Body<'tcx> {
2645 fn start_node(&self) -> Self::Node {
2650 impl<'tcx> graph::WithPredecessors for Body<'tcx> {
2654 ) -> <Self as GraphPredecessors<'_>>::Iter {
2655 self.predecessors_for(node).to_vec().into_iter()
2659 impl<'tcx> graph::WithSuccessors for Body<'tcx> {
2663 ) -> <Self as GraphSuccessors<'_>>::Iter {
2664 self.basic_blocks[node].terminator().successors().cloned()
2668 impl<'a, 'b> graph::GraphPredecessors<'b> for Body<'a> {
2669 type Item = BasicBlock;
2670 type Iter = IntoIter<BasicBlock>;
2673 impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> {
2674 type Item = BasicBlock;
2675 type Iter = iter::Cloned<Successors<'b>>;
2678 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)]
2679 pub struct Location {
2680 /// The block that the location is within.
2681 pub block: BasicBlock,
2683 /// The location is the position of the start of the statement; or, if
2684 /// `statement_index` equals the number of statements, then the start of the
2686 pub statement_index: usize,
2689 impl fmt::Debug for Location {
2690 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2691 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2696 pub const START: Location = Location { block: START_BLOCK, statement_index: 0 };
2698 /// Returns the location immediately after this one within the enclosing block.
2700 /// Note that if this location represents a terminator, then the
2701 /// resulting location would be out of bounds and invalid.
2702 pub fn successor_within_block(&self) -> Location {
2703 Location { block: self.block, statement_index: self.statement_index + 1 }
2706 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2707 pub fn is_predecessor_of<'tcx>(&self, other: Location, body: &Body<'tcx>) -> bool {
2708 // If we are in the same block as the other location and are an earlier statement
2709 // then we are a predecessor of `other`.
2710 if self.block == other.block && self.statement_index < other.statement_index {
2714 // If we're in another block, then we want to check that block is a predecessor of `other`.
2715 let mut queue: Vec<BasicBlock> = body.predecessors_for(other.block).to_vec();
2716 let mut visited = FxHashSet::default();
2718 while let Some(block) = queue.pop() {
2719 // If we haven't visited this block before, then make sure we visit it's predecessors.
2720 if visited.insert(block) {
2721 queue.extend(body.predecessors_for(block).iter().cloned());
2726 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2727 // we found that block by looking at the predecessors of `other`).
2728 if self.block == block {
2736 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2737 if self.block == other.block {
2738 self.statement_index <= other.statement_index
2740 dominators.is_dominated_by(other.block, self.block)
2745 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2746 pub enum UnsafetyViolationKind {
2748 /// Permitted both in `const fn`s and regular `fn`s.
2750 BorrowPacked(hir::HirId),
2753 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
2754 pub struct UnsafetyViolation {
2755 pub source_info: SourceInfo,
2756 pub description: Symbol,
2757 pub details: Symbol,
2758 pub kind: UnsafetyViolationKind,
2761 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
2762 pub struct UnsafetyCheckResult {
2763 /// Violations that are propagated *upwards* from this function.
2764 pub violations: Lrc<[UnsafetyViolation]>,
2765 /// `unsafe` blocks in this function, along with whether they are used. This is
2766 /// used for the "unused_unsafe" lint.
2767 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
2770 rustc_index::newtype_index! {
2771 pub struct GeneratorSavedLocal {
2773 DEBUG_FORMAT = "_{}",
2777 /// The layout of generator state.
2778 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
2779 pub struct GeneratorLayout<'tcx> {
2780 /// The type of every local stored inside the generator.
2781 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
2783 /// Which of the above fields are in each variant. Note that one field may
2784 /// be stored in multiple variants.
2785 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
2787 /// Which saved locals are storage-live at the same time. Locals that do not
2788 /// have conflicts with each other are allowed to overlap in the computed
2790 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
2793 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2794 pub struct BorrowCheckResult<'tcx> {
2795 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
2796 pub used_mut_upvars: SmallVec<[Field; 8]>,
2799 /// The result of the `mir_const_qualif` query.
2801 /// Each field corresponds to an implementer of the `Qualif` trait in
2802 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
2804 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
2805 pub struct ConstQualifs {
2806 pub has_mut_interior: bool,
2807 pub needs_drop: bool,
2810 /// After we borrow check a closure, we are left with various
2811 /// requirements that we have inferred between the free regions that
2812 /// appear in the closure's signature or on its field types. These
2813 /// requirements are then verified and proved by the closure's
2814 /// creating function. This struct encodes those requirements.
2816 /// The requirements are listed as being between various
2817 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2818 /// vids refer to the free regions that appear in the closure (or
2819 /// generator's) type, in order of appearance. (This numbering is
2820 /// actually defined by the `UniversalRegions` struct in the NLL
2821 /// region checker. See for example
2822 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2823 /// regions in the closure's type "as if" they were erased, so their
2824 /// precise identity is not important, only their position.
2826 /// Example: If type check produces a closure with the closure substs:
2829 /// ClosureSubsts = [
2830 /// i8, // the "closure kind"
2831 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2832 /// &'a String, // some upvar
2836 /// here, there is one unique free region (`'a`) but it appears
2837 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2840 /// ClosureSubsts = [
2841 /// i8, // the "closure kind"
2842 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2843 /// &'2 String, // some upvar
2847 /// Now the code might impose a requirement like `'1: '2`. When an
2848 /// instance of the closure is created, the corresponding free regions
2849 /// can be extracted from its type and constrained to have the given
2850 /// outlives relationship.
2852 /// In some cases, we have to record outlives requirements between
2853 /// types and regions as well. In that case, if those types include
2854 /// any regions, those regions are recorded as `ReClosureBound`
2855 /// instances assigned one of these same indices. Those regions will
2856 /// be substituted away by the creator. We use `ReClosureBound` in
2857 /// that case because the regions must be allocated in the global
2858 /// `TyCtxt`, and hence we cannot use `ReVar` (which is what we use
2859 /// internally within the rest of the NLL code).
2860 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2861 pub struct ClosureRegionRequirements<'tcx> {
2862 /// The number of external regions defined on the closure. In our
2863 /// example above, it would be 3 -- one for `'static`, then `'1`
2864 /// and `'2`. This is just used for a sanity check later on, to
2865 /// make sure that the number of regions we see at the callsite
2867 pub num_external_vids: usize,
2869 /// Requirements between the various free regions defined in
2871 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
2874 /// Indicates an outlives-constraint between a type or between two
2875 /// free regions declared on the closure.
2876 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2877 pub struct ClosureOutlivesRequirement<'tcx> {
2878 // This region or type ...
2879 pub subject: ClosureOutlivesSubject<'tcx>,
2881 // ... must outlive this one.
2882 pub outlived_free_region: ty::RegionVid,
2884 // If not, report an error here ...
2885 pub blame_span: Span,
2887 // ... due to this reason.
2888 pub category: ConstraintCategory,
2891 /// Outlives-constraints can be categorized to determine whether and why they
2892 /// are interesting (for error reporting). Order of variants indicates sort
2893 /// order of the category, thereby influencing diagnostic output.
2895 /// See also [rustc_mir::borrow_check::nll::constraints].
2909 pub enum ConstraintCategory {
2917 /// A constraint that came from checking the body of a closure.
2919 /// We try to get the category that the closure used when reporting this.
2927 /// A "boring" constraint (caused by the given location) is one that
2928 /// the user probably doesn't want to see described in diagnostics,
2929 /// because it is kind of an artifact of the type system setup.
2930 /// Example: `x = Foo { field: y }` technically creates
2931 /// intermediate regions representing the "type of `Foo { field: y
2932 /// }`", and data flows from `y` into those variables, but they
2933 /// are not very interesting. The assignment into `x` on the other
2936 // Boring and applicable everywhere.
2939 /// A constraint that doesn't correspond to anything the user sees.
2943 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
2944 /// that must outlive some region.
2945 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
2946 pub enum ClosureOutlivesSubject<'tcx> {
2947 /// Subject is a type, typically a type parameter, but could also
2948 /// be a projection. Indicates a requirement like `T: 'a` being
2949 /// passed to the caller, where the type here is `T`.
2951 /// The type here is guaranteed not to contain any free regions at
2955 /// Subject is a free region from the closure. Indicates a requirement
2956 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2957 Region(ty::RegionVid),
2961 * `TypeFoldable` implementations for MIR types
2964 CloneTypeFoldableAndLiftImpls! {
2973 SourceScopeLocalData,
2974 UserTypeAnnotationIndex,
2977 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2978 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
2979 use crate::mir::TerminatorKind::*;
2981 let kind = match self.kind {
2982 Goto { target } => Goto { target },
2983 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2984 discr: discr.fold_with(folder),
2985 switch_ty: switch_ty.fold_with(folder),
2986 values: values.clone(),
2987 targets: targets.clone(),
2989 Drop { ref location, target, unwind } => {
2990 Drop { location: location.fold_with(folder), target, unwind }
2992 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2993 location: location.fold_with(folder),
2994 value: value.fold_with(folder),
2998 Yield { ref value, resume, drop } => {
2999 Yield { value: value.fold_with(folder), resume: resume, drop: drop }
3001 Call { ref func, ref args, ref destination, cleanup, from_hir_call } => {
3003 destination.as_ref().map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3006 func: func.fold_with(folder),
3007 args: args.fold_with(folder),
3013 Assert { ref cond, expected, ref msg, target, cleanup } => {
3015 let msg = match msg {
3016 BoundsCheck { ref len, ref index } =>
3018 len: len.fold_with(folder),
3019 index: index.fold_with(folder),
3021 Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
3022 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
3025 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
3027 GeneratorDrop => GeneratorDrop,
3031 Unreachable => Unreachable,
3032 FalseEdges { real_target, imaginary_target } => {
3033 FalseEdges { real_target, imaginary_target }
3035 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
3037 Terminator { source_info: self.source_info, kind }
3040 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3041 use crate::mir::TerminatorKind::*;
3044 SwitchInt { ref discr, switch_ty, .. } => {
3045 discr.visit_with(visitor) || switch_ty.visit_with(visitor)
3047 Drop { ref location, .. } => location.visit_with(visitor),
3048 DropAndReplace { ref location, ref value, .. } => {
3049 location.visit_with(visitor) || value.visit_with(visitor)
3051 Yield { ref value, .. } => value.visit_with(visitor),
3052 Call { ref func, ref args, ref destination, .. } => {
3053 let dest = if let Some((ref loc, _)) = *destination {
3054 loc.visit_with(visitor)
3058 dest || func.visit_with(visitor) || args.visit_with(visitor)
3060 Assert { ref cond, ref msg, .. } => {
3061 if cond.visit_with(visitor) {
3064 BoundsCheck { ref len, ref index } =>
3065 len.visit_with(visitor) || index.visit_with(visitor),
3066 Panic { .. } | Overflow(_) | OverflowNeg |
3067 DivisionByZero | RemainderByZero |
3068 ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
3082 | FalseUnwind { .. } => false,
3087 impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
3088 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3092 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3097 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3098 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3100 base: self.base.fold_with(folder),
3101 projection: self.projection.fold_with(folder),
3105 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3106 self.base.visit_with(visitor) || self.projection.visit_with(visitor)
3110 impl<'tcx> TypeFoldable<'tcx> for PlaceBase<'tcx> {
3111 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3113 PlaceBase::Local(local) => PlaceBase::Local(local.fold_with(folder)),
3114 PlaceBase::Static(static_) => PlaceBase::Static(static_.fold_with(folder)),
3118 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3120 PlaceBase::Local(local) => local.visit_with(visitor),
3121 PlaceBase::Static(static_) => (**static_).visit_with(visitor),
3126 impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<PlaceElem<'tcx>> {
3127 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3128 let v = self.iter().map(|t| t.fold_with(folder)).collect::<Vec<_>>();
3129 folder.tcx().intern_place_elems(&v)
3132 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3133 self.iter().any(|t| t.visit_with(visitor))
3137 impl<'tcx> TypeFoldable<'tcx> for Static<'tcx> {
3138 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3140 ty: self.ty.fold_with(folder),
3141 kind: self.kind.fold_with(folder),
3142 def_id: self.def_id,
3146 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3147 let Static { ty, kind, def_id: _ } = self;
3149 ty.visit_with(visitor) || kind.visit_with(visitor)
3153 impl<'tcx> TypeFoldable<'tcx> for StaticKind<'tcx> {
3154 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3156 StaticKind::Promoted(promoted, substs) =>
3157 StaticKind::Promoted(promoted.fold_with(folder), substs.fold_with(folder)),
3158 StaticKind::Static => StaticKind::Static
3162 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3164 StaticKind::Promoted(promoted, substs) =>
3165 promoted.visit_with(visitor) || substs.visit_with(visitor),
3166 StaticKind::Static => { false }
3171 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3172 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3173 use crate::mir::Rvalue::*;
3175 Use(ref op) => Use(op.fold_with(folder)),
3176 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3177 Ref(region, bk, ref place) => {
3178 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3180 Len(ref place) => Len(place.fold_with(folder)),
3181 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3182 BinaryOp(op, ref rhs, ref lhs) => {
3183 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3185 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3186 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3188 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3189 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3190 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3191 Aggregate(ref kind, ref fields) => {
3192 let kind = box match **kind {
3193 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3194 AggregateKind::Tuple => AggregateKind::Tuple,
3195 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3198 substs.fold_with(folder),
3199 user_ty.fold_with(folder),
3202 AggregateKind::Closure(id, substs) => {
3203 AggregateKind::Closure(id, substs.fold_with(folder))
3205 AggregateKind::Generator(id, substs, movablity) => {
3206 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3209 Aggregate(kind, fields.fold_with(folder))
3214 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3215 use crate::mir::Rvalue::*;
3217 Use(ref op) => op.visit_with(visitor),
3218 Repeat(ref op, _) => op.visit_with(visitor),
3219 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3220 Len(ref place) => place.visit_with(visitor),
3221 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3222 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3223 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3225 UnaryOp(_, ref val) => val.visit_with(visitor),
3226 Discriminant(ref place) => place.visit_with(visitor),
3227 NullaryOp(_, ty) => ty.visit_with(visitor),
3228 Aggregate(ref kind, ref fields) => {
3230 AggregateKind::Array(ty) => ty.visit_with(visitor),
3231 AggregateKind::Tuple => false,
3232 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3233 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3235 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3236 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3237 }) || fields.visit_with(visitor)
3243 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3244 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3246 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3247 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3248 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3252 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3254 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3255 Operand::Constant(ref c) => c.visit_with(visitor),
3260 impl<'tcx> TypeFoldable<'tcx> for PlaceElem<'tcx> {
3261 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3262 use crate::mir::ProjectionElem::*;
3266 Field(f, ty) => Field(*f, ty.fold_with(folder)),
3267 Index(v) => Index(v.fold_with(folder)),
3268 elem => elem.clone(),
3272 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3273 use crate::mir::ProjectionElem::*;
3276 Field(_, ty) => ty.visit_with(visitor),
3277 Index(v) => v.visit_with(visitor),
3283 impl<'tcx> TypeFoldable<'tcx> for Field {
3284 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3287 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3292 impl<'tcx> TypeFoldable<'tcx> for GeneratorSavedLocal {
3293 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3296 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3301 impl<'tcx, R: Idx, C: Idx> TypeFoldable<'tcx> for BitMatrix<R, C> {
3302 fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
3305 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3310 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3311 fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
3313 span: self.span.clone(),
3314 user_ty: self.user_ty.fold_with(folder),
3315 literal: self.literal.fold_with(folder),
3318 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3319 self.literal.visit_with(visitor)