1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! MIR datatypes and passes. See the [rustc guide] for more info.
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/mir/index.html
15 use hir::def::CtorKind;
16 use hir::def_id::DefId;
17 use hir::{self, HirId, InlineAsm};
19 use mir::interpret::{ConstValue, EvalErrorKind, Scalar};
20 use mir::visit::MirVisitable;
21 use rustc_apfloat::ieee::{Double, Single};
22 use rustc_apfloat::Float;
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_data_structures::indexed_vec::{Idx, IndexVec};
27 use rustc_data_structures::sync::Lrc;
28 use rustc_data_structures::sync::MappedReadGuard;
29 use rustc_serialize as serialize;
30 use smallvec::SmallVec;
32 use std::fmt::{self, Debug, Formatter, Write};
33 use std::ops::{Index, IndexMut};
35 use std::vec::IntoIter;
36 use std::{iter, mem, option, u32};
37 use syntax::ast::{self, Name};
38 use syntax::symbol::InternedString;
39 use syntax_pos::{Span, DUMMY_SP};
40 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
41 use ty::subst::{CanonicalUserSubsts, Subst, Substs};
42 use ty::{self, AdtDef, CanonicalTy, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt};
43 use ty::layout::VariantIdx;
46 pub use mir::interpret::AssertMessage;
56 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
58 pub trait HasLocalDecls<'tcx> {
59 fn local_decls(&self) -> &LocalDecls<'tcx>;
62 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
63 fn local_decls(&self) -> &LocalDecls<'tcx> {
68 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
69 fn local_decls(&self) -> &LocalDecls<'tcx> {
74 /// The various "big phases" that MIR goes through.
76 /// Warning: ordering of variants is significant
77 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
86 /// Gets the index of the current MirPhase within the set of all MirPhases.
87 pub fn phase_index(&self) -> usize {
92 /// Lowered representation of a single function.
93 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
94 pub struct Mir<'tcx> {
95 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
96 /// that indexes into this vector.
97 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
99 /// Records how far through the "desugaring and optimization" process this particular
100 /// MIR has traversed. This is particularly useful when inlining, since in that context
101 /// we instantiate the promoted constants and add them to our promoted vector -- but those
102 /// promoted items have already been optimized, whereas ours have not. This field allows
103 /// us to see the difference and forego optimization on the inlined promoted items.
106 /// List of source scopes; these are referenced by statements
107 /// and used for debuginfo. Indexed by a `SourceScope`.
108 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
110 /// Crate-local information for each source scope, that can't (and
111 /// needn't) be tracked across crates.
112 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
114 /// Rvalues promoted from this function, such as borrows of constants.
115 /// Each of them is the Mir of a constant with the fn's type parameters
116 /// in scope, but a separate set of locals.
117 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
119 /// Yield type of the function, if it is a generator.
120 pub yield_ty: Option<Ty<'tcx>>,
122 /// Generator drop glue
123 pub generator_drop: Option<Box<Mir<'tcx>>>,
125 /// The layout of a generator. Produced by the state transformation.
126 pub generator_layout: Option<GeneratorLayout<'tcx>>,
128 /// Declarations of locals.
130 /// The first local is the return value pointer, followed by `arg_count`
131 /// locals for the function arguments, followed by any user-declared
132 /// variables and temporaries.
133 pub local_decls: LocalDecls<'tcx>,
135 /// Number of arguments this function takes.
137 /// Starting at local 1, `arg_count` locals will be provided by the caller
138 /// and can be assumed to be initialized.
140 /// If this MIR was built for a constant, this will be 0.
141 pub arg_count: usize,
143 /// Names and capture modes of all the closure upvars, assuming
144 /// the first argument is either the closure or a reference to it.
145 pub upvar_decls: Vec<UpvarDecl>,
147 /// Mark an argument local (which must be a tuple) as getting passed as
148 /// its individual components at the LLVM level.
150 /// This is used for the "rust-call" ABI.
151 pub spread_arg: Option<Local>,
153 /// A span representing this MIR, for error reporting
156 /// A cache for various calculations
160 impl<'tcx> Mir<'tcx> {
162 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
163 source_scopes: IndexVec<SourceScope, SourceScopeData>,
164 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
165 promoted: IndexVec<Promoted, Mir<'tcx>>,
166 yield_ty: Option<Ty<'tcx>>,
167 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
169 upvar_decls: Vec<UpvarDecl>,
172 // We need `arg_count` locals, and one for the return place
174 local_decls.len() >= arg_count + 1,
175 "expected at least {} locals, got {}",
181 phase: MirPhase::Build,
184 source_scope_local_data,
187 generator_drop: None,
188 generator_layout: None,
194 cache: cache::Cache::new(),
199 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
204 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
205 self.cache.invalidate();
206 &mut self.basic_blocks
210 pub fn basic_blocks_and_local_decls_mut(
213 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
214 &mut LocalDecls<'tcx>,
216 self.cache.invalidate();
217 (&mut self.basic_blocks, &mut self.local_decls)
221 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
222 self.cache.predecessors(self)
226 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
227 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
231 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
232 let if_zero_locations = if loc.statement_index == 0 {
233 let predecessor_blocks = self.predecessors_for(loc.block);
234 let num_predecessor_blocks = predecessor_blocks.len();
236 (0..num_predecessor_blocks)
237 .map(move |i| predecessor_blocks[i])
238 .map(move |bb| self.terminator_loc(bb)),
244 let if_not_zero_locations = if loc.statement_index == 0 {
249 statement_index: loc.statement_index - 1,
256 .chain(if_not_zero_locations)
260 pub fn dominators(&self) -> Dominators<BasicBlock> {
265 pub fn local_kind(&self, local: Local) -> LocalKind {
266 let index = local.as_usize();
269 self.local_decls[local].mutability == Mutability::Mut,
270 "return place should be mutable"
273 LocalKind::ReturnPointer
274 } else if index < self.arg_count + 1 {
276 } else if self.local_decls[local].name.is_some() {
283 /// Returns an iterator over all temporaries.
285 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
286 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
287 let local = Local::new(index);
288 if self.local_decls[local].is_user_variable.is_some() {
296 /// Returns an iterator over all user-declared locals.
298 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
299 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
300 let local = Local::new(index);
301 if self.local_decls[local].is_user_variable.is_some() {
309 /// Returns an iterator over all user-declared mutable locals.
311 pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
312 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
313 let local = Local::new(index);
314 let decl = &self.local_decls[local];
315 if decl.is_user_variable.is_some() && decl.mutability == Mutability::Mut {
323 /// Returns an iterator over all user-declared mutable arguments and locals.
325 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
326 (1..self.local_decls.len()).filter_map(move |index| {
327 let local = Local::new(index);
328 let decl = &self.local_decls[local];
329 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
330 && decl.mutability == Mutability::Mut
339 /// Returns an iterator over all function arguments.
341 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
342 let arg_count = self.arg_count;
343 (1..arg_count + 1).map(Local::new)
346 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
347 /// locals that are neither arguments nor the return place).
349 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
350 let arg_count = self.arg_count;
351 let local_count = self.local_decls.len();
352 (arg_count + 1..local_count).map(Local::new)
355 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
356 /// invalidating statement indices in `Location`s.
357 pub fn make_statement_nop(&mut self, location: Location) {
358 let block = &mut self[location.block];
359 debug_assert!(location.statement_index < block.statements.len());
360 block.statements[location.statement_index].make_nop()
363 /// Returns the source info associated with `location`.
364 pub fn source_info(&self, location: Location) -> &SourceInfo {
365 let block = &self[location.block];
366 let stmts = &block.statements;
367 let idx = location.statement_index;
368 if idx < stmts.len() {
369 &stmts[idx].source_info
371 assert_eq!(idx, stmts.len());
372 &block.terminator().source_info
376 /// Check if `sub` is a sub scope of `sup`
377 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
379 match self.source_scopes[sub].parent_scope {
380 None => return false,
387 /// Return the return type, it always return first element from `local_decls` array
388 pub fn return_ty(&self) -> Ty<'tcx> {
389 self.local_decls[RETURN_PLACE].ty
392 /// Get the location of the terminator for the given block
393 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
396 statement_index: self[bb].statements.len(),
401 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
404 /// Unsafe because of a PushUnsafeBlock
406 /// Unsafe because of an unsafe fn
408 /// Unsafe because of an `unsafe` block
409 ExplicitUnsafe(ast::NodeId),
412 impl_stable_hash_for!(struct Mir<'tcx> {
416 source_scope_local_data,
429 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
430 type Output = BasicBlockData<'tcx>;
433 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
434 &self.basic_blocks()[index]
438 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
440 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
441 &mut self.basic_blocks_mut()[index]
445 #[derive(Copy, Clone, Debug)]
446 pub enum ClearCrossCrate<T> {
451 impl<T> ClearCrossCrate<T> {
452 pub fn assert_crate_local(self) -> T {
454 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
455 ClearCrossCrate::Set(v) => v,
460 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
461 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
463 /// Grouped information about the source code origin of a MIR entity.
464 /// Intended to be inspected by diagnostics and debuginfo.
465 /// Most passes can work with it as a whole, within a single function.
466 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
467 pub struct SourceInfo {
468 /// Source span for the AST pertaining to this MIR entity.
471 /// The source scope, keeping track of which bindings can be
472 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
473 pub scope: SourceScope,
476 ///////////////////////////////////////////////////////////////////////////
477 // Mutability and borrow kinds
479 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
480 pub enum Mutability {
485 impl From<Mutability> for hir::Mutability {
486 fn from(m: Mutability) -> Self {
488 Mutability::Mut => hir::MutMutable,
489 Mutability::Not => hir::MutImmutable,
494 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
495 pub enum BorrowKind {
496 /// Data must be immutable and is aliasable.
499 /// The immediately borrowed place must be immutable, but projections from
500 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
501 /// conflict with a mutable borrow of `a.b.c`.
503 /// This is used when lowering matches: when matching on a place we want to
504 /// ensure that place have the same value from the start of the match until
505 /// an arm is selected. This prevents this code from compiling:
507 /// let mut x = &Some(0);
510 /// Some(_) if { x = &None; false } => (),
514 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
515 /// should not prevent `if let None = x { ... }`, for example, because the
516 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
517 /// We can also report errors with this kind of borrow differently.
520 /// Data must be immutable but not aliasable. This kind of borrow
521 /// cannot currently be expressed by the user and is used only in
522 /// implicit closure bindings. It is needed when the closure is
523 /// borrowing or mutating a mutable referent, e.g.:
525 /// let x: &mut isize = ...;
526 /// let y = || *x += 5;
528 /// If we were to try to translate this closure into a more explicit
529 /// form, we'd encounter an error with the code as written:
531 /// struct Env { x: & &mut isize }
532 /// let x: &mut isize = ...;
533 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
534 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
536 /// This is then illegal because you cannot mutate an `&mut` found
537 /// in an aliasable location. To solve, you'd have to translate with
538 /// an `&mut` borrow:
540 /// struct Env { x: & &mut isize }
541 /// let x: &mut isize = ...;
542 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
543 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
545 /// Now the assignment to `**env.x` is legal, but creating a
546 /// mutable pointer to `x` is not because `x` is not mutable. We
547 /// could fix this by declaring `x` as `let mut x`. This is ok in
548 /// user code, if awkward, but extra weird for closures, since the
549 /// borrow is hidden.
551 /// So we introduce a "unique imm" borrow -- the referent is
552 /// immutable, but not aliasable. This solves the problem. For
553 /// simplicity, we don't give users the way to express this
554 /// borrow, it's just used when translating closures.
557 /// Data is mutable and not aliasable.
559 /// True if this borrow arose from method-call auto-ref
560 /// (i.e. `adjustment::Adjust::Borrow`)
561 allow_two_phase_borrow: bool,
566 pub fn allows_two_phase_borrow(&self) -> bool {
568 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
569 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
574 ///////////////////////////////////////////////////////////////////////////
575 // Variables and temps
579 DEBUG_FORMAT = "_{}",
580 const RETURN_PLACE = 0,
584 /// Classifies locals into categories. See `Mir::local_kind`.
585 #[derive(PartialEq, Eq, Debug)]
587 /// User-declared variable binding
589 /// Compiler-introduced temporary
591 /// Function argument
593 /// Location of function's return value
597 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
598 pub struct VarBindingForm<'tcx> {
599 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
600 pub binding_mode: ty::BindingMode,
601 /// If an explicit type was provided for this variable binding,
602 /// this holds the source Span of that type.
604 /// NOTE: If you want to change this to a `HirId`, be wary that
605 /// doing so breaks incremental compilation (as of this writing),
606 /// while a `Span` does not cause our tests to fail.
607 pub opt_ty_info: Option<Span>,
608 /// Place of the RHS of the =, or the subject of the `match` where this
609 /// variable is initialized. None in the case of `let PATTERN;`.
610 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
611 /// (a) the right-hand side isn't evaluated as a place expression.
612 /// (b) it gives a way to separate this case from the remaining cases
614 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
615 /// Span of the pattern in which this variable was bound.
619 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
620 pub enum BindingForm<'tcx> {
621 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
622 Var(VarBindingForm<'tcx>),
623 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
624 ImplicitSelf(ImplicitSelfKind),
625 /// Reference used in a guard expression to ensure immutability.
629 /// Represents what type of implicit self a function has, if any.
630 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
631 pub enum ImplicitSelfKind {
632 /// Represents a `fn x(self);`.
634 /// Represents a `fn x(mut self);`.
636 /// Represents a `fn x(&self);`.
638 /// Represents a `fn x(&mut self);`.
640 /// Represents when a function does not have a self argument or
641 /// when a function has a `self: X` argument.
645 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
647 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
654 impl_stable_hash_for!(enum self::ImplicitSelfKind {
662 impl_stable_hash_for!(enum self::MirPhase {
669 mod binding_form_impl {
670 use ich::StableHashingContext;
671 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
673 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
674 fn hash_stable<W: StableHasherResult>(
676 hcx: &mut StableHashingContext<'a>,
677 hasher: &mut StableHasher<W>,
679 use super::BindingForm::*;
680 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
683 Var(binding) => binding.hash_stable(hcx, hasher),
684 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
691 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
692 /// created during evaluation of expressions in a block tail
693 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
695 /// It is used to improve diagnostics when such temporaries are
696 /// involved in borrow_check errors, e.g. explanations of where the
697 /// temporaries come from, when their destructors are run, and/or how
698 /// one might revise the code to satisfy the borrow checker's rules.
699 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
700 pub struct BlockTailInfo {
701 /// If `true`, then the value resulting from evaluating this tail
702 /// expression is ignored by the block's expression context.
704 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
705 /// but not e.g. `let _x = { ...; tail };`
706 pub tail_result_is_ignored: bool,
709 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
713 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
714 /// argument, or the return place.
715 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
716 pub struct LocalDecl<'tcx> {
717 /// `let mut x` vs `let x`.
719 /// Temporaries and the return place are always mutable.
720 pub mutability: Mutability,
722 /// Some(binding_mode) if this corresponds to a user-declared local variable.
724 /// This is solely used for local diagnostics when generating
725 /// warnings/errors when compiling the current crate, and
726 /// therefore it need not be visible across crates. pnkfelix
727 /// currently hypothesized we *need* to wrap this in a
728 /// `ClearCrossCrate` as long as it carries as `HirId`.
729 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
731 /// True if this is an internal local
733 /// These locals are not based on types in the source code and are only used
734 /// for a few desugarings at the moment.
736 /// The generator transformation will sanity check the locals which are live
737 /// across a suspension point against the type components of the generator
738 /// which type checking knows are live across a suspension point. We need to
739 /// flag drop flags to avoid triggering this check as they are introduced
742 /// Unsafety checking will also ignore dereferences of these locals,
743 /// so they can be used for raw pointers only used in a desugaring.
745 /// This should be sound because the drop flags are fully algebraic, and
746 /// therefore don't affect the OIBIT or outlives properties of the
750 /// If this local is a temporary and `is_block_tail` is `Some`,
751 /// then it is a temporary created for evaluation of some
752 /// subexpression of some block's tail expression (with no
753 /// intervening statement context).
754 pub is_block_tail: Option<BlockTailInfo>,
756 /// Type of this local.
759 /// If the user manually ascribed a type to this variable,
760 /// e.g. via `let x: T`, then we carry that type here. The MIR
761 /// borrow checker needs this information since it can affect
762 /// region inference.
763 pub user_ty: UserTypeProjections<'tcx>,
765 /// Name of the local, used in debuginfo and pretty-printing.
767 /// Note that function arguments can also have this set to `Some(_)`
768 /// to generate better debuginfo.
769 pub name: Option<Name>,
771 /// The *syntactic* (i.e. not visibility) source scope the local is defined
772 /// in. If the local was defined in a let-statement, this
773 /// is *within* the let-statement, rather than outside
776 /// This is needed because the visibility source scope of locals within
777 /// a let-statement is weird.
779 /// The reason is that we want the local to be *within* the let-statement
780 /// for lint purposes, but we want the local to be *after* the let-statement
781 /// for names-in-scope purposes.
783 /// That's it, if we have a let-statement like the one in this
787 /// fn foo(x: &str) {
788 /// #[allow(unused_mut)]
789 /// let mut x: u32 = { // <- one unused mut
790 /// let mut y: u32 = x.parse().unwrap();
797 /// Then, from a lint point of view, the declaration of `x: u32`
798 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
799 /// lint scopes are the same as the AST/HIR nesting.
801 /// However, from a name lookup point of view, the scopes look more like
802 /// as if the let-statements were `match` expressions:
805 /// fn foo(x: &str) {
807 /// match x.parse().unwrap() {
816 /// We care about the name-lookup scopes for debuginfo - if the
817 /// debuginfo instruction pointer is at the call to `x.parse()`, we
818 /// want `x` to refer to `x: &str`, but if it is at the call to
819 /// `drop(x)`, we want it to refer to `x: u32`.
821 /// To allow both uses to work, we need to have more than a single scope
822 /// for a local. We have the `source_info.scope` represent the
823 /// "syntactic" lint scope (with a variable being under its let
824 /// block) while the `visibility_scope` represents the "local variable"
825 /// scope (where the "rest" of a block is under all prior let-statements).
827 /// The end result looks like this:
831 /// │{ argument x: &str }
833 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
834 /// │ │ // in practice because I'm lazy.
836 /// │ │← x.source_info.scope
837 /// │ │← `x.parse().unwrap()`
839 /// │ │ │← y.source_info.scope
841 /// │ │ │{ let y: u32 }
843 /// │ │ │← y.visibility_scope
846 /// │ │{ let x: u32 }
847 /// │ │← x.visibility_scope
848 /// │ │← `drop(x)` // this accesses `x: u32`
850 pub source_info: SourceInfo,
852 /// Source scope within which the local is visible (for debuginfo)
853 /// (see `source_info` for more details).
854 pub visibility_scope: SourceScope,
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.is_user_variable {
866 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
867 binding_mode: ty::BindingMode::BindByValue(_),
873 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
880 /// Returns true if local is definitely not a `ref ident` or
881 /// `ref mut ident` binding. (Such bindings cannot be made into
882 /// mutable bindings, but the inverse does not necessarily hold).
883 pub fn is_nonref_binding(&self) -> bool {
884 match self.is_user_variable {
885 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
886 binding_mode: ty::BindingMode::BindByValue(_),
892 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
898 /// Create a new `LocalDecl` for a temporary.
900 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
901 Self::new_local(ty, Mutability::Mut, false, span)
904 /// Converts `self` into same `LocalDecl` except tagged as immutable.
906 pub fn immutable(mut self) -> Self {
907 self.mutability = Mutability::Not;
911 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
913 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
914 assert!(self.is_block_tail.is_none());
915 self.is_block_tail = Some(info);
919 /// Create a new `LocalDecl` for a internal temporary.
921 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
922 Self::new_local(ty, Mutability::Mut, true, span)
928 mutability: Mutability,
935 user_ty: UserTypeProjections::none(),
937 source_info: SourceInfo {
939 scope: OUTERMOST_SOURCE_SCOPE,
941 visibility_scope: OUTERMOST_SOURCE_SCOPE,
943 is_user_variable: None,
948 /// Builds a `LocalDecl` for the return place.
950 /// This must be inserted into the `local_decls` list as the first local.
952 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
954 mutability: Mutability::Mut,
956 user_ty: UserTypeProjections::none(),
957 source_info: SourceInfo {
959 scope: OUTERMOST_SOURCE_SCOPE,
961 visibility_scope: OUTERMOST_SOURCE_SCOPE,
964 name: None, // FIXME maybe we do want some name here?
965 is_user_variable: None,
970 /// A closure capture, with its name and mode.
971 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
972 pub struct UpvarDecl {
973 pub debug_name: Name,
975 /// `HirId` of the captured variable
976 pub var_hir_id: ClearCrossCrate<HirId>,
978 /// If true, the capture is behind a reference.
981 pub mutability: Mutability,
984 ///////////////////////////////////////////////////////////////////////////
988 pub struct BasicBlock {
989 DEBUG_FORMAT = "bb{}",
990 const START_BLOCK = 0,
995 pub fn start_location(self) -> Location {
1003 ///////////////////////////////////////////////////////////////////////////
1004 // BasicBlockData and Terminator
1006 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1007 pub struct BasicBlockData<'tcx> {
1008 /// List of statements in this block.
1009 pub statements: Vec<Statement<'tcx>>,
1011 /// Terminator for this block.
1013 /// NB. This should generally ONLY be `None` during construction.
1014 /// Therefore, you should generally access it via the
1015 /// `terminator()` or `terminator_mut()` methods. The only
1016 /// exception is that certain passes, such as `simplify_cfg`, swap
1017 /// out the terminator temporarily with `None` while they continue
1018 /// to recurse over the set of basic blocks.
1019 pub terminator: Option<Terminator<'tcx>>,
1021 /// If true, this block lies on an unwind path. This is used
1022 /// during codegen where distinct kinds of basic blocks may be
1023 /// generated (particularly for MSVC cleanup). Unwind blocks must
1024 /// only branch to other unwind blocks.
1025 pub is_cleanup: bool,
1028 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1029 pub struct Terminator<'tcx> {
1030 pub source_info: SourceInfo,
1031 pub kind: TerminatorKind<'tcx>,
1034 #[derive(Clone, RustcEncodable, RustcDecodable)]
1035 pub enum TerminatorKind<'tcx> {
1036 /// block should have one successor in the graph; we jump there
1037 Goto { target: BasicBlock },
1039 /// operand evaluates to an integer; jump depending on its value
1040 /// to one of the targets, and otherwise fallback to `otherwise`
1042 /// discriminant value being tested
1043 discr: Operand<'tcx>,
1045 /// type of value being tested
1046 switch_ty: Ty<'tcx>,
1048 /// Possible values. The locations to branch to in each case
1049 /// are found in the corresponding indices from the `targets` vector.
1050 values: Cow<'tcx, [u128]>,
1052 /// Possible branch sites. The last element of this vector is used
1053 /// for the otherwise branch, so targets.len() == values.len() + 1
1055 // This invariant is quite non-obvious and also could be improved.
1056 // One way to make this invariant is to have something like this instead:
1058 // branches: Vec<(ConstInt, BasicBlock)>,
1059 // otherwise: Option<BasicBlock> // exhaustive if None
1061 // However we’ve decided to keep this as-is until we figure a case
1062 // where some other approach seems to be strictly better than other.
1063 targets: Vec<BasicBlock>,
1066 /// Indicates that the landing pad is finished and unwinding should
1067 /// continue. Emitted by build::scope::diverge_cleanup.
1070 /// Indicates that the landing pad is finished and that the process
1071 /// should abort. Used to prevent unwinding for foreign items.
1074 /// Indicates a normal return. The return place should have
1075 /// been filled in by now. This should occur at most once.
1078 /// Indicates a terminator that can never be reached.
1083 location: Place<'tcx>,
1085 unwind: Option<BasicBlock>,
1088 /// Drop the Place and assign the new value over it. This ensures
1089 /// that the assignment to `P` occurs *even if* the destructor for
1090 /// place unwinds. Its semantics are best explained by the
1095 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1103 /// Drop(P, goto BB1, unwind BB2)
1106 /// // P is now uninitialized
1110 /// // P is now uninitialized -- its dtor panicked
1115 location: Place<'tcx>,
1116 value: Operand<'tcx>,
1118 unwind: Option<BasicBlock>,
1121 /// Block ends with a call of a converging function
1123 /// The function that’s being called
1124 func: Operand<'tcx>,
1125 /// Arguments the function is called with.
1126 /// These are owned by the callee, which is free to modify them.
1127 /// This allows the memory occupied by "by-value" arguments to be
1128 /// reused across function calls without duplicating the contents.
1129 args: Vec<Operand<'tcx>>,
1130 /// Destination for the return value. If some, the call is converging.
1131 destination: Option<(Place<'tcx>, BasicBlock)>,
1132 /// Cleanups to be done if the call unwinds.
1133 cleanup: Option<BasicBlock>,
1134 /// Whether this is from a call in HIR, rather than from an overloaded
1135 /// operator. True for overloaded function call.
1136 from_hir_call: bool,
1139 /// Jump to the target if the condition has the expected value,
1140 /// otherwise panic with a message and a cleanup target.
1142 cond: Operand<'tcx>,
1144 msg: AssertMessage<'tcx>,
1146 cleanup: Option<BasicBlock>,
1151 /// The value to return
1152 value: Operand<'tcx>,
1153 /// Where to resume to
1155 /// Cleanup to be done if the generator is dropped at this suspend point
1156 drop: Option<BasicBlock>,
1159 /// Indicates the end of the dropping of a generator
1162 /// A block where control flow only ever takes one real path, but borrowck
1163 /// needs to be more conservative.
1165 /// The target normal control flow will take
1166 real_target: BasicBlock,
1167 /// The list of blocks control flow could conceptually take, but won't
1169 imaginary_targets: Vec<BasicBlock>,
1171 /// A terminator for blocks that only take one path in reality, but where we
1172 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1173 /// This can arise in infinite loops with no function calls for example.
1175 /// The target normal control flow will take
1176 real_target: BasicBlock,
1177 /// The imaginary cleanup block link. This particular path will never be taken
1178 /// in practice, but in order to avoid fragility we want to always
1179 /// consider it in borrowck. We don't want to accept programs which
1180 /// pass borrowck only when panic=abort or some assertions are disabled
1181 /// due to release vs. debug mode builds. This needs to be an Option because
1182 /// of the remove_noop_landing_pads and no_landing_pads passes
1183 unwind: Option<BasicBlock>,
1187 pub type Successors<'a> =
1188 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1189 pub type SuccessorsMut<'a> =
1190 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1192 impl<'tcx> Terminator<'tcx> {
1193 pub fn successors(&self) -> Successors<'_> {
1194 self.kind.successors()
1197 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1198 self.kind.successors_mut()
1201 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1205 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1206 self.kind.unwind_mut()
1210 impl<'tcx> TerminatorKind<'tcx> {
1211 pub fn if_<'a, 'gcx>(
1212 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1213 cond: Operand<'tcx>,
1216 ) -> TerminatorKind<'tcx> {
1217 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1218 TerminatorKind::SwitchInt {
1220 switch_ty: tcx.types.bool,
1221 values: From::from(BOOL_SWITCH_FALSE),
1222 targets: vec![f, t],
1226 pub fn successors(&self) -> Successors<'_> {
1227 use self::TerminatorKind::*;
1238 } => None.into_iter().chain(&[]),
1239 Goto { target: ref t }
1242 cleanup: Some(ref t),
1246 destination: Some((_, ref t)),
1273 } => Some(t).into_iter().chain(&[]),
1275 destination: Some((_, ref t)),
1276 cleanup: Some(ref u),
1286 unwind: Some(ref u),
1291 unwind: Some(ref u),
1296 cleanup: Some(ref u),
1301 unwind: Some(ref u),
1302 } => Some(t).into_iter().chain(slice::from_ref(u)),
1303 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1306 ref imaginary_targets,
1307 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1311 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1312 use self::TerminatorKind::*;
1323 } => None.into_iter().chain(&mut []),
1324 Goto { target: ref mut t }
1327 cleanup: Some(ref mut t),
1331 destination: Some((_, ref mut t)),
1356 real_target: ref mut t,
1358 } => Some(t).into_iter().chain(&mut []),
1360 destination: Some((_, ref mut t)),
1361 cleanup: Some(ref mut u),
1366 drop: Some(ref mut u),
1371 unwind: Some(ref mut u),
1376 unwind: Some(ref mut u),
1381 cleanup: Some(ref mut u),
1385 real_target: ref mut t,
1386 unwind: Some(ref mut u),
1387 } => Some(t).into_iter().chain(slice::from_mut(u)),
1390 } => None.into_iter().chain(&mut targets[..]),
1392 ref mut real_target,
1393 ref mut imaginary_targets,
1394 } => Some(real_target)
1396 .chain(&mut imaginary_targets[..]),
1400 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1402 TerminatorKind::Goto { .. }
1403 | TerminatorKind::Resume
1404 | TerminatorKind::Abort
1405 | TerminatorKind::Return
1406 | TerminatorKind::Unreachable
1407 | TerminatorKind::GeneratorDrop
1408 | TerminatorKind::Yield { .. }
1409 | TerminatorKind::SwitchInt { .. }
1410 | TerminatorKind::FalseEdges { .. } => None,
1411 TerminatorKind::Call {
1412 cleanup: ref unwind,
1415 | TerminatorKind::Assert {
1416 cleanup: ref unwind,
1419 | TerminatorKind::DropAndReplace { ref unwind, .. }
1420 | TerminatorKind::Drop { ref unwind, .. }
1421 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1425 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1427 TerminatorKind::Goto { .. }
1428 | TerminatorKind::Resume
1429 | TerminatorKind::Abort
1430 | TerminatorKind::Return
1431 | TerminatorKind::Unreachable
1432 | TerminatorKind::GeneratorDrop
1433 | TerminatorKind::Yield { .. }
1434 | TerminatorKind::SwitchInt { .. }
1435 | TerminatorKind::FalseEdges { .. } => None,
1436 TerminatorKind::Call {
1437 cleanup: ref mut unwind,
1440 | TerminatorKind::Assert {
1441 cleanup: ref mut unwind,
1444 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1445 | TerminatorKind::Drop { ref mut unwind, .. }
1446 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1451 impl<'tcx> BasicBlockData<'tcx> {
1452 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1460 /// Accessor for terminator.
1462 /// Terminator may not be None after construction of the basic block is complete. This accessor
1463 /// provides a convenience way to reach the terminator.
1464 pub fn terminator(&self) -> &Terminator<'tcx> {
1465 self.terminator.as_ref().expect("invalid terminator state")
1468 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1469 self.terminator.as_mut().expect("invalid terminator state")
1472 pub fn retain_statements<F>(&mut self, mut f: F)
1474 F: FnMut(&mut Statement<'_>) -> bool,
1476 for s in &mut self.statements {
1483 pub fn expand_statements<F, I>(&mut self, mut f: F)
1485 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1486 I: iter::TrustedLen<Item = Statement<'tcx>>,
1488 // Gather all the iterators we'll need to splice in, and their positions.
1489 let mut splices: Vec<(usize, I)> = vec![];
1490 let mut extra_stmts = 0;
1491 for (i, s) in self.statements.iter_mut().enumerate() {
1492 if let Some(mut new_stmts) = f(s) {
1493 if let Some(first) = new_stmts.next() {
1494 // We can already store the first new statement.
1497 // Save the other statements for optimized splicing.
1498 let remaining = new_stmts.size_hint().0;
1500 splices.push((i + 1 + extra_stmts, new_stmts));
1501 extra_stmts += remaining;
1509 // Splice in the new statements, from the end of the block.
1510 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1511 // where a range of elements ("gap") is left uninitialized, with
1512 // splicing adding new elements to the end of that gap and moving
1513 // existing elements from before the gap to the end of the gap.
1514 // For now, this is safe code, emulating a gap but initializing it.
1515 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1516 self.statements.resize(
1519 source_info: SourceInfo {
1521 scope: OUTERMOST_SOURCE_SCOPE,
1523 kind: StatementKind::Nop,
1526 for (splice_start, new_stmts) in splices.into_iter().rev() {
1527 let splice_end = splice_start + new_stmts.size_hint().0;
1528 while gap.end > splice_end {
1531 self.statements.swap(gap.start, gap.end);
1533 self.statements.splice(splice_start..splice_end, new_stmts);
1534 gap.end = splice_start;
1538 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1539 if index < self.statements.len() {
1540 &self.statements[index]
1547 impl<'tcx> Debug for TerminatorKind<'tcx> {
1548 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1549 self.fmt_head(fmt)?;
1550 let successor_count = self.successors().count();
1551 let labels = self.fmt_successor_labels();
1552 assert_eq!(successor_count, labels.len());
1554 match successor_count {
1557 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1560 write!(fmt, " -> [")?;
1561 for (i, target) in self.successors().enumerate() {
1565 write!(fmt, "{}: {:?}", labels[i], target)?;
1573 impl<'tcx> TerminatorKind<'tcx> {
1574 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1575 /// successor basic block, if any. The only information not included is the list of possible
1576 /// successors, which may be rendered differently between the text and the graphviz format.
1577 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1578 use self::TerminatorKind::*;
1580 Goto { .. } => write!(fmt, "goto"),
1582 discr: ref place, ..
1583 } => write!(fmt, "switchInt({:?})", place),
1584 Return => write!(fmt, "return"),
1585 GeneratorDrop => write!(fmt, "generator_drop"),
1586 Resume => write!(fmt, "resume"),
1587 Abort => write!(fmt, "abort"),
1588 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1589 Unreachable => write!(fmt, "unreachable"),
1590 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1595 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1602 if let Some((ref destination, _)) = *destination {
1603 write!(fmt, "{:?} = ", destination)?;
1605 write!(fmt, "{:?}(", func)?;
1606 for (index, arg) in args.iter().enumerate() {
1610 write!(fmt, "{:?}", arg)?;
1620 write!(fmt, "assert(")?;
1624 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1626 FalseEdges { .. } => write!(fmt, "falseEdges"),
1627 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1631 /// Return the list of labels for the edges to the successor basic blocks.
1632 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1633 use self::TerminatorKind::*;
1635 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1636 Goto { .. } => vec!["".into()],
1642 let size = ty::tls::with(|tcx| {
1643 let param_env = ty::ParamEnv::empty();
1644 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1645 tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1650 let mut s = String::new();
1652 val: ConstValue::Scalar(
1655 size: size.bytes() as u8,
1660 fmt_const_val(&mut s, &c).unwrap();
1662 }).chain(iter::once("otherwise".into()))
1666 destination: Some(_),
1669 } => vec!["return".into(), "unwind".into()],
1671 destination: Some(_),
1674 } => vec!["return".into()],
1679 } => vec!["unwind".into()],
1685 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1686 Yield { drop: None, .. } => vec!["resume".into()],
1687 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1688 vec!["return".into()]
1695 } => vec!["return".into(), "unwind".into()],
1696 Assert { cleanup: None, .. } => vec!["".into()],
1697 Assert { .. } => vec!["success".into(), "unwind".into()],
1699 ref imaginary_targets,
1702 let mut l = vec!["real".into()];
1703 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1708 } => vec!["real".into(), "cleanup".into()],
1709 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1714 ///////////////////////////////////////////////////////////////////////////
1717 #[derive(Clone, RustcEncodable, RustcDecodable)]
1718 pub struct Statement<'tcx> {
1719 pub source_info: SourceInfo,
1720 pub kind: StatementKind<'tcx>,
1723 // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger.
1724 #[cfg(target_arch = "x86_64")]
1725 static_assert!(MEM_SIZE_OF_STATEMENT: mem::size_of::<Statement<'_>>() == 56);
1727 impl<'tcx> Statement<'tcx> {
1728 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1729 /// invalidating statement indices in `Location`s.
1730 pub fn make_nop(&mut self) {
1731 self.kind = StatementKind::Nop
1734 /// Changes a statement to a nop and returns the original statement.
1735 pub fn replace_nop(&mut self) -> Self {
1737 source_info: self.source_info,
1738 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1743 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1744 pub enum StatementKind<'tcx> {
1745 /// Write the RHS Rvalue to the LHS Place.
1746 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1748 /// This represents all the reading that a pattern match may do
1749 /// (e.g. inspecting constants and discriminant values), and the
1750 /// kind of pattern it comes from. This is in order to adapt potential
1751 /// error messages to these specific patterns.
1752 FakeRead(FakeReadCause, Place<'tcx>),
1754 /// Write the discriminant for a variant to the enum Place.
1757 variant_index: VariantIdx,
1760 /// Start a live range for the storage of the local.
1763 /// End the current live range for the storage of the local.
1766 /// Execute a piece of inline Assembly.
1768 asm: Box<InlineAsm>,
1769 outputs: Box<[Place<'tcx>]>,
1770 inputs: Box<[(Span, Operand<'tcx>)]>,
1773 /// Retag references in the given place, ensuring they got fresh tags. This is
1774 /// part of the Stacked Borrows model. These statements are currently only interpreted
1775 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1776 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1777 /// for more details.
1779 /// `fn_entry` indicates whether this is the initial retag that happens in the
1780 /// function prolog.
1785 /// Escape the given reference to a raw pointer, so that it can be accessed
1786 /// without precise provenance tracking. These statements are currently only interpreted
1787 /// by miri and only generated when "-Z mir-emit-retag" is passed.
1788 /// See <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/>
1789 /// for more details.
1790 EscapeToRaw(Operand<'tcx>),
1792 /// Mark one terminating point of a region scope (i.e. static region).
1793 /// (The starting point(s) arise implicitly from borrows.)
1794 EndRegion(region::Scope),
1796 /// Encodes a user's type ascription. These need to be preserved
1797 /// intact so that NLL can respect them. For example:
1801 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1802 /// to the user-given type `T`. The effect depends on the specified variance:
1804 /// - `Covariant` -- requires that `T_y <: T`
1805 /// - `Contravariant` -- requires that `T_y :> T`
1806 /// - `Invariant` -- requires that `T_y == T`
1807 /// - `Bivariant` -- no effect
1808 AscribeUserType(Place<'tcx>, ty::Variance, Box<UserTypeProjection<'tcx>>),
1810 /// No-op. Useful for deleting instructions without affecting statement indices.
1814 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1815 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1816 pub enum FakeReadCause {
1817 /// Inject a fake read of the borrowed input at the start of each arm's
1818 /// pattern testing code.
1820 /// This should ensure that you cannot change the variant for an enum
1821 /// while you are in the midst of matching on it.
1824 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1825 /// generate a read of x to check that it is initialized and safe.
1828 /// Officially, the semantics of
1830 /// `let pattern = <expr>;`
1832 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1833 /// into the pattern.
1835 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1836 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1837 /// but in some cases it can affect the borrow checker, as in #53695.
1838 /// Therefore, we insert a "fake read" here to ensure that we get
1839 /// appropriate errors.
1843 impl<'tcx> Debug for Statement<'tcx> {
1844 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1845 use self::StatementKind::*;
1847 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1848 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1849 // (reuse lifetime rendering policy from ppaux.)
1850 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1851 Retag { fn_entry, ref place } =>
1852 write!(fmt, "Retag({}{:?})", if fn_entry { "[fn entry] " } else { "" }, place),
1853 EscapeToRaw(ref place) => write!(fmt, "EscapeToRaw({:?})", place),
1854 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1855 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1859 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1864 } => write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs),
1865 AscribeUserType(ref place, ref variance, ref c_ty) => {
1866 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1868 Nop => write!(fmt, "nop"),
1873 ///////////////////////////////////////////////////////////////////////////
1876 /// A path to a value; something that can be evaluated without
1877 /// changing or disturbing program state.
1878 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1879 pub enum Place<'tcx> {
1883 /// static or static mut variable
1884 Static(Box<Static<'tcx>>),
1886 /// Constant code promoted to an injected static
1887 Promoted(Box<(Promoted, Ty<'tcx>)>),
1889 /// projection out of a place (access a field, deref a pointer, etc)
1890 Projection(Box<PlaceProjection<'tcx>>),
1893 /// The def-id of a static, along with its normalized type (which is
1894 /// stored to avoid requiring normalization when reading MIR).
1895 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1896 pub struct Static<'tcx> {
1901 impl_stable_hash_for!(struct Static<'tcx> {
1906 /// The `Projection` data structure defines things of the form `B.x`
1907 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1908 /// shared between `Constant` and `Place`. See the aliases
1909 /// `PlaceProjection` etc below.
1910 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1911 pub struct Projection<'tcx, B, V, T> {
1913 pub elem: ProjectionElem<'tcx, V, T>,
1916 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1917 pub enum ProjectionElem<'tcx, V, T> {
1922 /// These indices are generated by slice patterns. Easiest to explain
1926 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1927 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1928 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1929 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1932 /// index or -index (in Python terms), depending on from_end
1934 /// thing being indexed must be at least this long
1936 /// counting backwards from end?
1940 /// These indices are generated by slice patterns.
1942 /// slice[from:-to] in Python terms.
1948 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1949 /// this for ADTs with more than one variant. It may be better to
1950 /// just introduce it always, or always for enums.
1951 Downcast(&'tcx AdtDef, VariantIdx),
1954 /// Alias for projections as they appear in places, where the base is a place
1955 /// and the index is a local.
1956 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1958 /// Alias for projections as they appear in places, where the base is a place
1959 /// and the index is a local.
1960 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1962 // at least on 64 bit systems, `PlaceElem` should not be larger than two pointers
1963 static_assert!(PROJECTION_ELEM_IS_2_PTRS_LARGE:
1964 mem::size_of::<PlaceElem<'_>>() <= 16
1967 /// Alias for projections as they appear in `UserTypeProjection`, where we
1968 /// need neither the `V` parameter for `Index` nor the `T` for `Field`.
1969 pub type ProjectionKind<'tcx> = ProjectionElem<'tcx, (), ()>;
1973 DEBUG_FORMAT = "field[{}]"
1977 impl<'tcx> Place<'tcx> {
1978 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1979 self.elem(ProjectionElem::Field(f, ty))
1982 pub fn deref(self) -> Place<'tcx> {
1983 self.elem(ProjectionElem::Deref)
1986 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Place<'tcx> {
1987 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1990 pub fn index(self, index: Local) -> Place<'tcx> {
1991 self.elem(ProjectionElem::Index(index))
1994 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1995 Place::Projection(Box::new(PlaceProjection { base: self, elem }))
1998 /// Find the innermost `Local` from this `Place`, *if* it is either a local itself or
1999 /// a single deref of a local.
2001 /// FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2002 pub fn local(&self) -> Option<Local> {
2004 Place::Local(local) |
2005 Place::Projection(box Projection {
2006 base: Place::Local(local),
2007 elem: ProjectionElem::Deref,
2013 /// Find the innermost `Local` from this `Place`.
2014 pub fn base_local(&self) -> Option<Local> {
2016 Place::Local(local) => Some(*local),
2017 Place::Projection(box Projection { base, elem: _ }) => base.base_local(),
2018 Place::Promoted(..) | Place::Static(..) => None,
2023 impl<'tcx> Debug for Place<'tcx> {
2024 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2028 Local(id) => write!(fmt, "{:?}", id),
2029 Static(box self::Static { def_id, ty }) => write!(
2032 ty::tls::with(|tcx| tcx.item_path_str(def_id)),
2035 Promoted(ref promoted) => write!(fmt, "({:?}: {:?})", promoted.0, promoted.1),
2036 Projection(ref data) => match data.elem {
2037 ProjectionElem::Downcast(ref adt_def, index) => {
2038 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name)
2040 ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
2041 ProjectionElem::Field(field, ty) => {
2042 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
2044 ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
2045 ProjectionElem::ConstantIndex {
2049 } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
2050 ProjectionElem::ConstantIndex {
2054 } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
2055 ProjectionElem::Subslice { from, to } if to == 0 => {
2056 write!(fmt, "{:?}[{:?}:]", data.base, from)
2058 ProjectionElem::Subslice { from, to } if from == 0 => {
2059 write!(fmt, "{:?}[:-{:?}]", data.base, to)
2061 ProjectionElem::Subslice { from, to } => {
2062 write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
2069 ///////////////////////////////////////////////////////////////////////////
2073 pub struct SourceScope {
2074 DEBUG_FORMAT = "scope[{}]",
2075 const OUTERMOST_SOURCE_SCOPE = 0,
2079 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2080 pub struct SourceScopeData {
2082 pub parent_scope: Option<SourceScope>,
2085 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2086 pub struct SourceScopeLocalData {
2087 /// A NodeId with lint levels equivalent to this scope's lint levels.
2088 pub lint_root: ast::NodeId,
2089 /// The unsafe block that contains this node.
2093 ///////////////////////////////////////////////////////////////////////////
2096 /// These are values that can appear inside an rvalue. They are intentionally
2097 /// limited to prevent rvalues from being nested in one another.
2098 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
2099 pub enum Operand<'tcx> {
2100 /// Copy: The value must be available for use afterwards.
2102 /// This implies that the type of the place must be `Copy`; this is true
2103 /// by construction during build, but also checked by the MIR type checker.
2106 /// Move: The value (including old borrows of it) will not be used again.
2108 /// Safe for values of all types (modulo future developments towards `?Move`).
2109 /// Correct usage patterns are enforced by the borrow checker for safe code.
2110 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
2113 /// Synthesizes a constant value.
2114 Constant(Box<Constant<'tcx>>),
2117 impl<'tcx> Debug for Operand<'tcx> {
2118 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2119 use self::Operand::*;
2121 Constant(ref a) => write!(fmt, "{:?}", a),
2122 Copy(ref place) => write!(fmt, "{:?}", place),
2123 Move(ref place) => write!(fmt, "move {:?}", place),
2128 impl<'tcx> Operand<'tcx> {
2129 /// Convenience helper to make a constant that refers to the fn
2130 /// with given def-id and substs. Since this is used to synthesize
2131 /// MIR, assumes `user_ty` is None.
2132 pub fn function_handle<'a>(
2133 tcx: TyCtxt<'a, 'tcx, 'tcx>,
2135 substs: &'tcx Substs<'tcx>,
2138 let ty = tcx.type_of(def_id).subst(tcx, substs);
2139 Operand::Constant(box Constant {
2143 literal: ty::Const::zero_sized(tcx, ty),
2147 pub fn to_copy(&self) -> Self {
2149 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
2150 Operand::Move(ref place) => Operand::Copy(place.clone()),
2155 ///////////////////////////////////////////////////////////////////////////
2158 #[derive(Clone, RustcEncodable, RustcDecodable)]
2159 pub enum Rvalue<'tcx> {
2160 /// x (either a move or copy, depending on type of x)
2164 Repeat(Operand<'tcx>, u64),
2167 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
2169 /// length of a [X] or [X;n] value
2172 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
2174 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2175 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
2177 NullaryOp(NullOp, Ty<'tcx>),
2178 UnaryOp(UnOp, Operand<'tcx>),
2180 /// Read the discriminant of an ADT.
2182 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
2183 /// be defined to return, say, a 0) if ADT is not an enum.
2184 Discriminant(Place<'tcx>),
2186 /// Create an aggregate value, like a tuple or struct. This is
2187 /// only needed because we want to distinguish `dest = Foo { x:
2188 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
2189 /// that `Foo` has a destructor. These rvalues can be optimized
2190 /// away after type-checking and before lowering.
2191 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
2194 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2198 /// Convert unique, zero-sized type for a fn to fn()
2201 /// Convert non capturing closure to fn()
2204 /// Convert safe fn() to unsafe fn()
2207 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
2208 /// codegen must figure out the details once full monomorphization
2209 /// is known. For example, this could be used to cast from a
2210 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
2211 /// (presuming `T: Trait`).
2215 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2216 pub enum AggregateKind<'tcx> {
2217 /// The type is of the element
2221 /// The second field is the variant index. It's equal to 0 for struct
2222 /// and union expressions. The fourth field is
2223 /// active field number and is present only for union expressions
2224 /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
2225 /// active field index would identity the field `c`
2230 Option<UserTypeAnnotation<'tcx>>,
2234 Closure(DefId, ClosureSubsts<'tcx>),
2235 Generator(DefId, GeneratorSubsts<'tcx>, hir::GeneratorMovability),
2238 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2240 /// The `+` operator (addition)
2242 /// The `-` operator (subtraction)
2244 /// The `*` operator (multiplication)
2246 /// The `/` operator (division)
2248 /// The `%` operator (modulus)
2250 /// The `^` operator (bitwise xor)
2252 /// The `&` operator (bitwise and)
2254 /// The `|` operator (bitwise or)
2256 /// The `<<` operator (shift left)
2258 /// The `>>` operator (shift right)
2260 /// The `==` operator (equality)
2262 /// The `<` operator (less than)
2264 /// The `<=` operator (less than or equal to)
2266 /// The `!=` operator (not equal to)
2268 /// The `>=` operator (greater than or equal to)
2270 /// The `>` operator (greater than)
2272 /// The `ptr.offset` operator
2277 pub fn is_checkable(self) -> bool {
2280 Add | Sub | Mul | Shl | Shr => true,
2286 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2288 /// Return the size of a value of that type
2290 /// Create a new uninitialized box for a value of that type
2294 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
2296 /// The `!` operator for logical inversion
2298 /// The `-` operator for negation
2302 impl<'tcx> Debug for Rvalue<'tcx> {
2303 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2304 use self::Rvalue::*;
2307 Use(ref place) => write!(fmt, "{:?}", place),
2308 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
2309 Len(ref a) => write!(fmt, "Len({:?})", a),
2310 Cast(ref kind, ref place, ref ty) => {
2311 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
2313 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
2314 CheckedBinaryOp(ref op, ref a, ref b) => {
2315 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
2317 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
2318 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
2319 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
2320 Ref(region, borrow_kind, ref place) => {
2321 let kind_str = match borrow_kind {
2322 BorrowKind::Shared => "",
2323 BorrowKind::Shallow => "shallow ",
2324 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
2327 // When printing regions, add trailing space if necessary.
2328 let region = if ppaux::verbose() || ppaux::identify_regions() {
2329 let mut region = region.to_string();
2330 if region.len() > 0 {
2335 // Do not even print 'static
2338 write!(fmt, "&{}{}{:?}", region, kind_str, place)
2341 Aggregate(ref kind, ref places) => {
2342 fn fmt_tuple(fmt: &mut Formatter<'_>, places: &[Operand<'_>]) -> fmt::Result {
2343 let mut tuple_fmt = fmt.debug_tuple("");
2344 for place in places {
2345 tuple_fmt.field(place);
2351 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
2353 AggregateKind::Tuple => match places.len() {
2354 0 => write!(fmt, "()"),
2355 1 => write!(fmt, "({:?},)", places[0]),
2356 _ => fmt_tuple(fmt, places),
2359 AggregateKind::Adt(adt_def, variant, substs, _user_ty, _) => {
2360 let variant_def = &adt_def.variants[variant];
2362 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
2364 match variant_def.ctor_kind {
2365 CtorKind::Const => Ok(()),
2366 CtorKind::Fn => fmt_tuple(fmt, places),
2367 CtorKind::Fictive => {
2368 let mut struct_fmt = fmt.debug_struct("");
2369 for (field, place) in variant_def.fields.iter().zip(places) {
2370 struct_fmt.field(&field.ident.as_str(), place);
2377 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
2378 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2379 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
2380 format!("[closure@{:?}]", node_id)
2382 format!("[closure@{:?}]", tcx.hir.span(node_id))
2384 let mut struct_fmt = fmt.debug_struct(&name);
2386 tcx.with_freevars(node_id, |freevars| {
2387 for (freevar, place) in freevars.iter().zip(places) {
2388 let var_name = tcx.hir.name(freevar.var_id());
2389 struct_fmt.field(&var_name.as_str(), place);
2395 write!(fmt, "[closure]")
2399 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
2400 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
2401 let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
2402 let mut struct_fmt = fmt.debug_struct(&name);
2404 tcx.with_freevars(node_id, |freevars| {
2405 for (freevar, place) in freevars.iter().zip(places) {
2406 let var_name = tcx.hir.name(freevar.var_id());
2407 struct_fmt.field(&var_name.as_str(), place);
2409 struct_fmt.field("$state", &places[freevars.len()]);
2410 for i in (freevars.len() + 1)..places.len() {
2412 .field(&format!("${}", i - freevars.len() - 1), &places[i]);
2418 write!(fmt, "[generator]")
2427 ///////////////////////////////////////////////////////////////////////////
2430 /// Two constants are equal if they are the same constant. Note that
2431 /// this does not necessarily mean that they are "==" in Rust -- in
2432 /// particular one must be wary of `NaN`!
2434 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2435 pub struct Constant<'tcx> {
2439 /// Optional user-given type: for something like
2440 /// `collect::<Vec<_>>`, this would be present and would
2441 /// indicate that `Vec<_>` was explicitly specified.
2443 /// Needed for NLL to impose user-given type constraints.
2444 pub user_ty: Option<UserTypeAnnotation<'tcx>>,
2446 pub literal: &'tcx ty::Const<'tcx>,
2449 /// A user-given type annotation attached to a constant. These arise
2450 /// from constants that are named via paths, like `Foo::<A>::new` and
2452 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2453 pub enum UserTypeAnnotation<'tcx> {
2454 Ty(CanonicalTy<'tcx>),
2456 /// The canonical type is the result of `type_of(def_id)` with the
2457 /// given substitutions applied.
2458 TypeOf(DefId, CanonicalUserSubsts<'tcx>),
2461 EnumTypeFoldableImpl! {
2462 impl<'tcx> TypeFoldable<'tcx> for UserTypeAnnotation<'tcx> {
2463 (UserTypeAnnotation::Ty)(ty),
2464 (UserTypeAnnotation::TypeOf)(def, substs),
2469 impl<'a, 'tcx> Lift<'tcx> for UserTypeAnnotation<'a> {
2470 type Lifted = UserTypeAnnotation<'tcx>;
2471 (UserTypeAnnotation::Ty)(ty),
2472 (UserTypeAnnotation::TypeOf)(def, substs),
2476 /// A collection of projections into user types.
2478 /// They are projections because a binding can occur a part of a
2479 /// parent pattern that has been ascribed a type.
2481 /// Its a collection because there can be multiple type ascriptions on
2482 /// the path from the root of the pattern down to the binding itself.
2487 /// struct S<'a>((i32, &'a str), String);
2488 /// let S((_, w): (i32, &'static str), _): S = ...;
2489 /// // ------ ^^^^^^^^^^^^^^^^^^^ (1)
2490 /// // --------------------------------- ^ (2)
2493 /// The highlights labelled `(1)` show the subpattern `(_, w)` being
2494 /// ascribed the type `(i32, &'static str)`.
2496 /// The highlights labelled `(2)` show the whole pattern being
2497 /// ascribed the type `S`.
2499 /// In this example, when we descend to `w`, we will have built up the
2500 /// following two projected types:
2502 /// * base: `S`, projection: `(base.0).1`
2503 /// * base: `(i32, &'static str)`, projection: `base.1`
2505 /// The first will lead to the constraint `w: &'1 str` (for some
2506 /// inferred region `'1`). The second will lead to the constraint `w:
2508 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2509 pub struct UserTypeProjections<'tcx> {
2510 pub(crate) contents: Vec<(UserTypeProjection<'tcx>, Span)>,
2513 BraceStructTypeFoldableImpl! {
2514 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjections<'tcx> {
2519 impl<'tcx> UserTypeProjections<'tcx> {
2520 pub fn none() -> Self {
2521 UserTypeProjections { contents: vec![] }
2524 pub fn from_projections(projs: impl Iterator<Item=(UserTypeProjection<'tcx>, Span)>) -> Self {
2525 UserTypeProjections { contents: projs.collect() }
2528 pub fn projections_and_spans(&self) -> impl Iterator<Item=&(UserTypeProjection<'tcx>, Span)> {
2529 self.contents.iter()
2532 pub fn projections(&self) -> impl Iterator<Item=&UserTypeProjection<'tcx>> {
2533 self.contents.iter().map(|&(ref user_type, _span)| user_type)
2537 /// Encodes the effect of a user-supplied type annotation on the
2538 /// subcomponents of a pattern. The effect is determined by applying the
2539 /// given list of proejctions to some underlying base type. Often,
2540 /// the projection element list `projs` is empty, in which case this
2541 /// directly encodes a type in `base`. But in the case of complex patterns with
2542 /// subpatterns and bindings, we want to apply only a *part* of the type to a variable,
2543 /// in which case the `projs` vector is used.
2547 /// * `let x: T = ...` -- here, the `projs` vector is empty.
2549 /// * `let (x, _): T = ...` -- here, the `projs` vector would contain
2550 /// `field[0]` (aka `.0`), indicating that the type of `s` is
2551 /// determined by finding the type of the `.0` field from `T`.
2552 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2553 pub struct UserTypeProjection<'tcx> {
2554 pub base: UserTypeAnnotation<'tcx>,
2555 pub projs: Vec<ProjectionElem<'tcx, (), ()>>,
2558 impl<'tcx> Copy for ProjectionKind<'tcx> { }
2560 CloneTypeFoldableAndLiftImpls! { ProjectionKind<'tcx>, }
2562 impl<'tcx> TypeFoldable<'tcx> for UserTypeProjection<'tcx> {
2563 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2564 use mir::ProjectionElem::*;
2566 let base = self.base.fold_with(folder);
2567 let projs: Vec<_> = self.projs
2572 Field(f, ()) => Field(f.clone(), ()),
2573 Index(()) => Index(()),
2574 elem => elem.clone(),
2578 UserTypeProjection { base, projs }
2581 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2582 self.base.visit_with(visitor)
2583 // Note: there's nothing in `self.proj` to visit.
2588 pub struct Promoted {
2589 DEBUG_FORMAT = "promoted[{}]"
2593 impl<'tcx> Debug for Constant<'tcx> {
2594 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2595 write!(fmt, "const ")?;
2596 fmt_const_val(fmt, self.literal)
2600 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2601 pub fn fmt_const_val(f: &mut impl Write, const_val: &ty::Const<'_>) -> fmt::Result {
2603 let value = const_val.val;
2604 let ty = const_val.ty;
2605 // print some primitives
2606 if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2608 Bool if bits == 0 => return write!(f, "false"),
2609 Bool if bits == 1 => return write!(f, "true"),
2610 Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2611 Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2612 Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2614 let bit_width = ty::tls::with(|tcx| {
2615 let ty = tcx.lift_to_global(&ty).unwrap();
2616 tcx.layout_of(ty::ParamEnv::empty().and(ty))
2621 let shift = 128 - bit_width;
2622 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2624 Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2628 // print function definitions
2629 if let FnDef(did, _) = ty.sty {
2630 return write!(f, "{}", item_path_str(did));
2632 // print string literals
2633 if let ConstValue::ScalarPair(ptr, len) = value {
2634 if let Scalar::Ptr(ptr) = ptr {
2635 if let Scalar::Bits { bits: len, .. } = len {
2636 if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2637 return ty::tls::with(|tcx| {
2638 let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2639 if let Some(interpret::AllocType::Memory(alloc)) = alloc {
2640 assert_eq!(len as usize as u128, len);
2642 &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2643 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2644 write!(f, "{:?}", s)
2646 write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2653 // just raw dump everything else
2654 write!(f, "{:?}:{}", value, ty)
2657 fn item_path_str(def_id: DefId) -> String {
2658 ty::tls::with(|tcx| tcx.item_path_str(def_id))
2661 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2662 type Node = BasicBlock;
2665 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2666 fn num_nodes(&self) -> usize {
2667 self.basic_blocks.len()
2671 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2672 fn start_node(&self) -> Self::Node {
2677 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2678 fn predecessors<'graph>(
2681 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2682 self.predecessors_for(node).clone().into_iter()
2686 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2687 fn successors<'graph>(
2690 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2691 self.basic_blocks[node].terminator().successors().cloned()
2695 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2696 type Item = BasicBlock;
2697 type Iter = IntoIter<BasicBlock>;
2700 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2701 type Item = BasicBlock;
2702 type Iter = iter::Cloned<Successors<'b>>;
2705 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
2706 pub struct Location {
2707 /// the location is within this block
2708 pub block: BasicBlock,
2710 /// the location is the start of the statement; or, if `statement_index`
2711 /// == num-statements, then the start of the terminator.
2712 pub statement_index: usize,
2715 impl fmt::Debug for Location {
2716 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2717 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2722 pub const START: Location = Location {
2727 /// Returns the location immediately after this one within the enclosing block.
2729 /// Note that if this location represents a terminator, then the
2730 /// resulting location would be out of bounds and invalid.
2731 pub fn successor_within_block(&self) -> Location {
2734 statement_index: self.statement_index + 1,
2738 /// Returns `true` if `other` is earlier in the control flow graph than `self`.
2739 pub fn is_predecessor_of<'tcx>(&self, other: Location, mir: &Mir<'tcx>) -> bool {
2740 // If we are in the same block as the other location and are an earlier statement
2741 // then we are a predecessor of `other`.
2742 if self.block == other.block && self.statement_index < other.statement_index {
2746 // If we're in another block, then we want to check that block is a predecessor of `other`.
2747 let mut queue: Vec<BasicBlock> = mir.predecessors_for(other.block).clone();
2748 let mut visited = FxHashSet::default();
2750 while let Some(block) = queue.pop() {
2751 // If we haven't visited this block before, then make sure we visit it's predecessors.
2752 if visited.insert(block) {
2753 queue.append(&mut mir.predecessors_for(block).clone());
2758 // If we found the block that `self` is in, then we are a predecessor of `other` (since
2759 // we found that block by looking at the predecessors of `other`).
2760 if self.block == block {
2768 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2769 if self.block == other.block {
2770 self.statement_index <= other.statement_index
2772 dominators.is_dominated_by(other.block, self.block)
2777 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2778 pub enum UnsafetyViolationKind {
2780 /// unsafety is not allowed at all in min const fn
2782 ExternStatic(ast::NodeId),
2783 BorrowPacked(ast::NodeId),
2786 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2787 pub struct UnsafetyViolation {
2788 pub source_info: SourceInfo,
2789 pub description: InternedString,
2790 pub details: InternedString,
2791 pub kind: UnsafetyViolationKind,
2794 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2795 pub struct UnsafetyCheckResult {
2796 /// Violations that are propagated *upwards* from this function
2797 pub violations: Lrc<[UnsafetyViolation]>,
2798 /// unsafe blocks in this function, along with whether they are used. This is
2799 /// used for the "unused_unsafe" lint.
2800 pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>,
2803 /// The layout of generator state
2804 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2805 pub struct GeneratorLayout<'tcx> {
2806 pub fields: Vec<LocalDecl<'tcx>>,
2809 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2810 pub struct BorrowCheckResult<'gcx> {
2811 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
2812 pub used_mut_upvars: SmallVec<[Field; 8]>,
2815 /// After we borrow check a closure, we are left with various
2816 /// requirements that we have inferred between the free regions that
2817 /// appear in the closure's signature or on its field types. These
2818 /// requirements are then verified and proved by the closure's
2819 /// creating function. This struct encodes those requirements.
2821 /// The requirements are listed as being between various
2822 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2823 /// vids refer to the free regions that appear in the closure (or
2824 /// generator's) type, in order of appearance. (This numbering is
2825 /// actually defined by the `UniversalRegions` struct in the NLL
2826 /// region checker. See for example
2827 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2828 /// regions in the closure's type "as if" they were erased, so their
2829 /// precise identity is not important, only their position.
2831 /// Example: If type check produces a closure with the closure substs:
2834 /// ClosureSubsts = [
2835 /// i8, // the "closure kind"
2836 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2837 /// &'a String, // some upvar
2841 /// here, there is one unique free region (`'a`) but it appears
2842 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2845 /// ClosureSubsts = [
2846 /// i8, // the "closure kind"
2847 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2848 /// &'2 String, // some upvar
2852 /// Now the code might impose a requirement like `'1: '2`. When an
2853 /// instance of the closure is created, the corresponding free regions
2854 /// can be extracted from its type and constrained to have the given
2855 /// outlives relationship.
2857 /// In some cases, we have to record outlives requirements between
2858 /// types and regions as well. In that case, if those types include
2859 /// any regions, those regions are recorded as `ReClosureBound`
2860 /// instances assigned one of these same indices. Those regions will
2861 /// be substituted away by the creator. We use `ReClosureBound` in
2862 /// that case because the regions must be allocated in the global
2863 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2864 /// internally within the rest of the NLL code).
2865 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2866 pub struct ClosureRegionRequirements<'gcx> {
2867 /// The number of external regions defined on the closure. In our
2868 /// example above, it would be 3 -- one for `'static`, then `'1`
2869 /// and `'2`. This is just used for a sanity check later on, to
2870 /// make sure that the number of regions we see at the callsite
2872 pub num_external_vids: usize,
2874 /// Requirements between the various free regions defined in
2876 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
2879 /// Indicates an outlives constraint between a type or between two
2880 /// free-regions declared on the closure.
2881 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2882 pub struct ClosureOutlivesRequirement<'tcx> {
2883 // This region or type ...
2884 pub subject: ClosureOutlivesSubject<'tcx>,
2886 // ... must outlive this one.
2887 pub outlived_free_region: ty::RegionVid,
2889 // If not, report an error here ...
2890 pub blame_span: Span,
2892 // ... due to this reason.
2893 pub category: ConstraintCategory,
2896 /// Outlives constraints can be categorized to determine whether and why they
2897 /// are interesting (for error reporting). Order of variants indicates sort
2898 /// order of the category, thereby influencing diagnostic output.
2900 /// See also [rustc_mir::borrow_check::nll::constraints]
2901 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
2902 pub enum ConstraintCategory {
2909 /// A constraint that came from checking the body of a closure.
2911 /// We try to get the category that the closure used when reporting this.
2919 /// A "boring" constraint (caused by the given location) is one that
2920 /// the user probably doesn't want to see described in diagnostics,
2921 /// because it is kind of an artifact of the type system setup.
2922 /// Example: `x = Foo { field: y }` technically creates
2923 /// intermediate regions representing the "type of `Foo { field: y
2924 /// }`", and data flows from `y` into those variables, but they
2925 /// are not very interesting. The assignment into `x` on the other
2928 // Boring and applicable everywhere.
2931 /// A constraint that doesn't correspond to anything the user sees.
2935 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2936 /// that must outlive some region.
2937 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2938 pub enum ClosureOutlivesSubject<'tcx> {
2939 /// Subject is a type, typically a type parameter, but could also
2940 /// be a projection. Indicates a requirement like `T: 'a` being
2941 /// passed to the caller, where the type here is `T`.
2943 /// The type here is guaranteed not to contain any free regions at
2947 /// Subject is a free region from the closure. Indicates a requirement
2948 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2949 Region(ty::RegionVid),
2953 * TypeFoldable implementations for MIR types
2956 CloneTypeFoldableAndLiftImpls! {
2965 SourceScopeLocalData,
2968 BraceStructTypeFoldableImpl! {
2969 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2973 source_scope_local_data,
2987 BraceStructTypeFoldableImpl! {
2988 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2993 BraceStructTypeFoldableImpl! {
2994 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
3007 BraceStructTypeFoldableImpl! {
3008 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
3015 BraceStructTypeFoldableImpl! {
3016 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
3021 EnumTypeFoldableImpl! {
3022 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
3023 (StatementKind::Assign)(a, b),
3024 (StatementKind::FakeRead)(cause, place),
3025 (StatementKind::SetDiscriminant) { place, variant_index },
3026 (StatementKind::StorageLive)(a),
3027 (StatementKind::StorageDead)(a),
3028 (StatementKind::InlineAsm) { asm, outputs, inputs },
3029 (StatementKind::Retag) { fn_entry, place },
3030 (StatementKind::EscapeToRaw)(place),
3031 (StatementKind::EndRegion)(a),
3032 (StatementKind::AscribeUserType)(a, v, b),
3033 (StatementKind::Nop),
3037 EnumTypeFoldableImpl! {
3038 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
3039 (ClearCrossCrate::Clear),
3040 (ClearCrossCrate::Set)(a),
3041 } where T: TypeFoldable<'tcx>
3044 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
3045 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3046 use mir::TerminatorKind::*;
3048 let kind = match self.kind {
3049 Goto { target } => Goto { target },
3056 discr: discr.fold_with(folder),
3057 switch_ty: switch_ty.fold_with(folder),
3058 values: values.clone(),
3059 targets: targets.clone(),
3066 location: location.fold_with(folder),
3075 } => DropAndReplace {
3076 location: location.fold_with(folder),
3077 value: value.fold_with(folder),
3086 value: value.fold_with(folder),
3097 let dest = destination
3099 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
3102 func: func.fold_with(folder),
3103 args: args.fold_with(folder),
3116 let msg = if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3117 EvalErrorKind::BoundsCheck {
3118 len: len.fold_with(folder),
3119 index: index.fold_with(folder),
3125 cond: cond.fold_with(folder),
3132 GeneratorDrop => GeneratorDrop,
3136 Unreachable => Unreachable,
3139 ref imaginary_targets,
3142 imaginary_targets: imaginary_targets.clone(),
3153 source_info: self.source_info,
3158 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3159 use mir::TerminatorKind::*;
3166 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3167 Drop { ref location, .. } => location.visit_with(visitor),
3172 } => location.visit_with(visitor) || value.visit_with(visitor),
3173 Yield { ref value, .. } => value.visit_with(visitor),
3180 let dest = if let Some((ref loc, _)) = *destination {
3181 loc.visit_with(visitor)
3185 dest || func.visit_with(visitor) || args.visit_with(visitor)
3188 ref cond, ref msg, ..
3190 if cond.visit_with(visitor) {
3191 if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3192 len.visit_with(visitor) || index.visit_with(visitor)
3207 | FalseUnwind { .. } => false,
3212 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3213 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3215 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3220 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3221 if let &Place::Projection(ref p) = self {
3222 p.visit_with(visitor)
3229 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3230 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3233 Use(ref op) => Use(op.fold_with(folder)),
3234 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3235 Ref(region, bk, ref place) => {
3236 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3238 Len(ref place) => Len(place.fold_with(folder)),
3239 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3240 BinaryOp(op, ref rhs, ref lhs) => {
3241 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3243 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3244 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3246 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3247 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3248 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3249 Aggregate(ref kind, ref fields) => {
3250 let kind = box match **kind {
3251 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3252 AggregateKind::Tuple => AggregateKind::Tuple,
3253 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3256 substs.fold_with(folder),
3257 user_ty.fold_with(folder),
3260 AggregateKind::Closure(id, substs) => {
3261 AggregateKind::Closure(id, substs.fold_with(folder))
3263 AggregateKind::Generator(id, substs, movablity) => {
3264 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3267 Aggregate(kind, fields.fold_with(folder))
3272 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3275 Use(ref op) => op.visit_with(visitor),
3276 Repeat(ref op, _) => op.visit_with(visitor),
3277 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3278 Len(ref place) => place.visit_with(visitor),
3279 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3280 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3281 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3283 UnaryOp(_, ref val) => val.visit_with(visitor),
3284 Discriminant(ref place) => place.visit_with(visitor),
3285 NullaryOp(_, ty) => ty.visit_with(visitor),
3286 Aggregate(ref kind, ref fields) => {
3288 AggregateKind::Array(ty) => ty.visit_with(visitor),
3289 AggregateKind::Tuple => false,
3290 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3291 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3293 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3294 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3295 }) || fields.visit_with(visitor)
3301 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3302 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3304 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3305 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3306 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3310 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3312 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3313 Operand::Constant(ref c) => c.visit_with(visitor),
3318 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
3320 B: TypeFoldable<'tcx>,
3321 V: TypeFoldable<'tcx>,
3322 T: TypeFoldable<'tcx>,
3324 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3325 use mir::ProjectionElem::*;
3327 let base = self.base.fold_with(folder);
3328 let elem = match self.elem {
3330 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3331 Index(ref v) => Index(v.fold_with(folder)),
3332 ref elem => elem.clone(),
3335 Projection { base, elem }
3338 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3339 use mir::ProjectionElem::*;
3341 self.base.visit_with(visitor) || match self.elem {
3342 Field(_, ref ty) => ty.visit_with(visitor),
3343 Index(ref v) => v.visit_with(visitor),
3349 impl<'tcx> TypeFoldable<'tcx> for Field {
3350 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3353 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3358 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3359 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3361 span: self.span.clone(),
3362 ty: self.ty.fold_with(folder),
3363 user_ty: self.user_ty.fold_with(folder),
3364 literal: self.literal.fold_with(folder),
3367 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3368 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)