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::graph::dominators::{dominators, Dominators};
24 use rustc_data_structures::graph::{self, GraphPredecessors, GraphSuccessors};
25 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
26 use rustc_data_structures::sync::Lrc;
27 use rustc_data_structures::sync::MappedReadGuard;
28 use rustc_serialize as serialize;
29 use smallvec::SmallVec;
31 use std::fmt::{self, Debug, Formatter, Write};
32 use std::ops::{Index, IndexMut};
34 use std::vec::IntoIter;
35 use std::{iter, mem, option, u32};
36 use syntax::ast::{self, Name};
37 use syntax::symbol::InternedString;
38 use syntax_pos::{Span, DUMMY_SP};
39 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
40 use ty::subst::{CanonicalUserSubsts, Subst, Substs};
41 use ty::{self, AdtDef, CanonicalTy, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt};
44 pub use mir::interpret::AssertMessage;
54 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
56 pub trait HasLocalDecls<'tcx> {
57 fn local_decls(&self) -> &LocalDecls<'tcx>;
60 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
61 fn local_decls(&self) -> &LocalDecls<'tcx> {
66 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
67 fn local_decls(&self) -> &LocalDecls<'tcx> {
72 /// The various "big phases" that MIR goes through.
74 /// Warning: ordering of variants is significant
75 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
83 /// Lowered representation of a single function.
84 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
85 pub struct Mir<'tcx> {
86 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
87 /// that indexes into this vector.
88 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
90 /// Records how far through the "desugaring and optimization" process this particular
91 /// MIR has traversed. This is particularly useful when inlining, since in that context
92 /// we instantiate the promoted constants and add them to our promoted vector -- but those
93 /// promoted items have already been optimized, whereas ours have not. This field allows
94 /// us to see the difference and forego optimization on the inlined promoted items.
97 /// List of source scopes; these are referenced by statements
98 /// and used for debuginfo. Indexed by a `SourceScope`.
99 pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
101 /// Crate-local information for each source scope, that can't (and
102 /// needn't) be tracked across crates.
103 pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
105 /// Rvalues promoted from this function, such as borrows of constants.
106 /// Each of them is the Mir of a constant with the fn's type parameters
107 /// in scope, but a separate set of locals.
108 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
110 /// Yield type of the function, if it is a generator.
111 pub yield_ty: Option<Ty<'tcx>>,
113 /// Generator drop glue
114 pub generator_drop: Option<Box<Mir<'tcx>>>,
116 /// The layout of a generator. Produced by the state transformation.
117 pub generator_layout: Option<GeneratorLayout<'tcx>>,
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 /// Number of arguments this function takes.
128 /// Starting at local 1, `arg_count` locals will be provided by the caller
129 /// and can be assumed to be initialized.
131 /// If this MIR was built for a constant, this will be 0.
132 pub arg_count: usize,
134 /// Names and capture modes of all the closure upvars, assuming
135 /// the first argument is either the closure or a reference to it.
136 pub upvar_decls: Vec<UpvarDecl>,
138 /// Mark an argument local (which must be a tuple) as getting passed as
139 /// its individual components at the LLVM level.
141 /// This is used for the "rust-call" ABI.
142 pub spread_arg: Option<Local>,
144 /// A span representing this MIR, for error reporting
147 /// A cache for various calculations
151 impl<'tcx> Mir<'tcx> {
153 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
154 source_scopes: IndexVec<SourceScope, SourceScopeData>,
155 source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
156 promoted: IndexVec<Promoted, Mir<'tcx>>,
157 yield_ty: Option<Ty<'tcx>>,
158 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
160 upvar_decls: Vec<UpvarDecl>,
163 // We need `arg_count` locals, and one for the return place
165 local_decls.len() >= arg_count + 1,
166 "expected at least {} locals, got {}",
172 phase: MirPhase::Build,
175 source_scope_local_data,
178 generator_drop: None,
179 generator_layout: None,
185 cache: cache::Cache::new(),
190 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
195 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
196 self.cache.invalidate();
197 &mut self.basic_blocks
201 pub fn basic_blocks_and_local_decls_mut(
204 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
205 &mut LocalDecls<'tcx>,
207 self.cache.invalidate();
208 (&mut self.basic_blocks, &mut self.local_decls)
212 pub fn predecessors(&self) -> MappedReadGuard<'_, IndexVec<BasicBlock, Vec<BasicBlock>>> {
213 self.cache.predecessors(self)
217 pub fn predecessors_for(&self, bb: BasicBlock) -> MappedReadGuard<'_, Vec<BasicBlock>> {
218 MappedReadGuard::map(self.predecessors(), |p| &p[bb])
222 pub fn predecessor_locations(&self, loc: Location) -> impl Iterator<Item = Location> + '_ {
223 let if_zero_locations = if loc.statement_index == 0 {
224 let predecessor_blocks = self.predecessors_for(loc.block);
225 let num_predecessor_blocks = predecessor_blocks.len();
227 (0..num_predecessor_blocks)
228 .map(move |i| predecessor_blocks[i])
229 .map(move |bb| self.terminator_loc(bb)),
235 let if_not_zero_locations = if loc.statement_index == 0 {
240 statement_index: loc.statement_index - 1,
247 .chain(if_not_zero_locations)
251 pub fn dominators(&self) -> Dominators<BasicBlock> {
256 pub fn local_kind(&self, local: Local) -> LocalKind {
257 let index = local.as_usize();
260 self.local_decls[local].mutability == Mutability::Mut,
261 "return place should be mutable"
264 LocalKind::ReturnPointer
265 } else if index < self.arg_count + 1 {
267 } else if self.local_decls[local].name.is_some() {
274 /// Returns an iterator over all temporaries.
276 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
277 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
278 let local = Local::new(index);
279 if self.local_decls[local].is_user_variable.is_some() {
287 /// Returns an iterator over all user-declared locals.
289 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
290 (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
291 let local = Local::new(index);
292 if self.local_decls[local].is_user_variable.is_some() {
300 /// Returns an iterator over all user-declared mutable arguments and locals.
302 pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
303 (1..self.local_decls.len()).filter_map(move |index| {
304 let local = Local::new(index);
305 let decl = &self.local_decls[local];
306 if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
307 && decl.mutability == Mutability::Mut
316 /// Returns an iterator over all function arguments.
318 pub fn args_iter(&self) -> impl Iterator<Item = Local> {
319 let arg_count = self.arg_count;
320 (1..arg_count + 1).map(Local::new)
323 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
324 /// locals that are neither arguments nor the return place).
326 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
327 let arg_count = self.arg_count;
328 let local_count = self.local_decls.len();
329 (arg_count + 1..local_count).map(Local::new)
332 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
333 /// invalidating statement indices in `Location`s.
334 pub fn make_statement_nop(&mut self, location: Location) {
335 let block = &mut self[location.block];
336 debug_assert!(location.statement_index < block.statements.len());
337 block.statements[location.statement_index].make_nop()
340 /// Returns the source info associated with `location`.
341 pub fn source_info(&self, location: Location) -> &SourceInfo {
342 let block = &self[location.block];
343 let stmts = &block.statements;
344 let idx = location.statement_index;
345 if idx < stmts.len() {
346 &stmts[idx].source_info
348 assert_eq!(idx, stmts.len());
349 &block.terminator().source_info
353 /// Check if `sub` is a sub scope of `sup`
354 pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
356 match self.source_scopes[sub].parent_scope {
357 None => return false,
364 /// Return the return type, it always return first element from `local_decls` array
365 pub fn return_ty(&self) -> Ty<'tcx> {
366 self.local_decls[RETURN_PLACE].ty
369 /// Get the location of the terminator for the given block
370 pub fn terminator_loc(&self, bb: BasicBlock) -> Location {
373 statement_index: self[bb].statements.len(),
378 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
381 /// Unsafe because of a PushUnsafeBlock
383 /// Unsafe because of an unsafe fn
385 /// Unsafe because of an `unsafe` block
386 ExplicitUnsafe(ast::NodeId),
389 impl_stable_hash_for!(struct Mir<'tcx> {
393 source_scope_local_data,
406 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
407 type Output = BasicBlockData<'tcx>;
410 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
411 &self.basic_blocks()[index]
415 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
417 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
418 &mut self.basic_blocks_mut()[index]
422 #[derive(Copy, Clone, Debug)]
423 pub enum ClearCrossCrate<T> {
428 impl<T> ClearCrossCrate<T> {
429 pub fn assert_crate_local(self) -> T {
431 ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
432 ClearCrossCrate::Set(v) => v,
437 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
438 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
440 /// Grouped information about the source code origin of a MIR entity.
441 /// Intended to be inspected by diagnostics and debuginfo.
442 /// Most passes can work with it as a whole, within a single function.
443 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
444 pub struct SourceInfo {
445 /// Source span for the AST pertaining to this MIR entity.
448 /// The source scope, keeping track of which bindings can be
449 /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
450 pub scope: SourceScope,
453 ///////////////////////////////////////////////////////////////////////////
454 // Mutability and borrow kinds
456 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
457 pub enum Mutability {
462 impl From<Mutability> for hir::Mutability {
463 fn from(m: Mutability) -> Self {
465 Mutability::Mut => hir::MutMutable,
466 Mutability::Not => hir::MutImmutable,
471 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
472 pub enum BorrowKind {
473 /// Data must be immutable and is aliasable.
476 /// The immediately borrowed place must be immutable, but projections from
477 /// it don't need to be. For example, a shallow borrow of `a.b` doesn't
478 /// conflict with a mutable borrow of `a.b.c`.
480 /// This is used when lowering matches: when matching on a place we want to
481 /// ensure that place have the same value from the start of the match until
482 /// an arm is selected. This prevents this code from compiling:
484 /// let mut x = &Some(0);
487 /// Some(_) if { x = &None; false } => (),
491 /// This can't be a shared borrow because mutably borrowing (*x as Some).0
492 /// should not prevent `if let None = x { ... }`, for example, becase the
493 /// mutating `(*x as Some).0` can't affect the discriminant of `x`.
494 /// We can also report errors with this kind of borrow differently.
497 /// Data must be immutable but not aliasable. This kind of borrow
498 /// cannot currently be expressed by the user and is used only in
499 /// implicit closure bindings. It is needed when the closure is
500 /// borrowing or mutating a mutable referent, e.g.:
502 /// let x: &mut isize = ...;
503 /// let y = || *x += 5;
505 /// If we were to try to translate this closure into a more explicit
506 /// form, we'd encounter an error with the code as written:
508 /// struct Env { x: & &mut isize }
509 /// let x: &mut isize = ...;
510 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
511 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
513 /// This is then illegal because you cannot mutate an `&mut` found
514 /// in an aliasable location. To solve, you'd have to translate with
515 /// an `&mut` borrow:
517 /// struct Env { x: & &mut isize }
518 /// let x: &mut isize = ...;
519 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
520 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
522 /// Now the assignment to `**env.x` is legal, but creating a
523 /// mutable pointer to `x` is not because `x` is not mutable. We
524 /// could fix this by declaring `x` as `let mut x`. This is ok in
525 /// user code, if awkward, but extra weird for closures, since the
526 /// borrow is hidden.
528 /// So we introduce a "unique imm" borrow -- the referent is
529 /// immutable, but not aliasable. This solves the problem. For
530 /// simplicity, we don't give users the way to express this
531 /// borrow, it's just used when translating closures.
534 /// Data is mutable and not aliasable.
536 /// True if this borrow arose from method-call auto-ref
537 /// (i.e. `adjustment::Adjust::Borrow`)
538 allow_two_phase_borrow: bool,
543 pub fn allows_two_phase_borrow(&self) -> bool {
545 BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
546 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
551 ///////////////////////////////////////////////////////////////////////////
552 // Variables and temps
556 DEBUG_FORMAT = "_{}",
557 const RETURN_PLACE = 0,
561 /// Classifies locals into categories. See `Mir::local_kind`.
562 #[derive(PartialEq, Eq, Debug)]
564 /// User-declared variable binding
566 /// Compiler-introduced temporary
568 /// Function argument
570 /// Location of function's return value
574 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
575 pub struct VarBindingForm<'tcx> {
576 /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
577 pub binding_mode: ty::BindingMode,
578 /// If an explicit type was provided for this variable binding,
579 /// this holds the source Span of that type.
581 /// NOTE: If you want to change this to a `HirId`, be wary that
582 /// doing so breaks incremental compilation (as of this writing),
583 /// while a `Span` does not cause our tests to fail.
584 pub opt_ty_info: Option<Span>,
585 /// Place of the RHS of the =, or the subject of the `match` where this
586 /// variable is initialized. None in the case of `let PATTERN;`.
587 /// Some((None, ..)) in the case of and `let [mut] x = ...` because
588 /// (a) the right-hand side isn't evaluated as a place expression.
589 /// (b) it gives a way to separate this case from the remaining cases
591 pub opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
592 /// Span of the pattern in which this variable was bound.
596 #[derive(Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
597 pub enum BindingForm<'tcx> {
598 /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
599 Var(VarBindingForm<'tcx>),
600 /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
601 ImplicitSelf(ImplicitSelfKind),
602 /// Reference used in a guard expression to ensure immutability.
606 /// Represents what type of implicit self a function has, if any.
607 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
608 pub enum ImplicitSelfKind {
609 /// Represents a `fn x(self);`.
611 /// Represents a `fn x(mut self);`.
613 /// Represents a `fn x(&self);`.
615 /// Represents a `fn x(&mut self);`.
617 /// Represents when a function does not have a self argument or
618 /// when a function has a `self: X` argument.
622 CloneTypeFoldableAndLiftImpls! { BindingForm<'tcx>, }
624 impl_stable_hash_for!(struct self::VarBindingForm<'tcx> {
631 impl_stable_hash_for!(enum self::ImplicitSelfKind {
639 impl_stable_hash_for!(enum self::MirPhase {
646 mod binding_form_impl {
647 use ich::StableHashingContext;
648 use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
650 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for super::BindingForm<'tcx> {
651 fn hash_stable<W: StableHasherResult>(
653 hcx: &mut StableHashingContext<'a>,
654 hasher: &mut StableHasher<W>,
656 use super::BindingForm::*;
657 ::std::mem::discriminant(self).hash_stable(hcx, hasher);
660 Var(binding) => binding.hash_stable(hcx, hasher),
661 ImplicitSelf(kind) => kind.hash_stable(hcx, hasher),
668 /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
669 /// created during evaluation of expressions in a block tail
670 /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
672 /// It is used to improve diagnostics when such temporaries are
673 /// involved in borrow_check errors, e.g. explanations of where the
674 /// temporaries come from, when their destructors are run, and/or how
675 /// one might revise the code to satisfy the borrow checker's rules.
676 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
677 pub struct BlockTailInfo {
678 /// If `true`, then the value resulting from evaluating this tail
679 /// expression is ignored by the block's expression context.
681 /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
682 /// but not e.g. `let _x = { ...; tail };`
683 pub tail_result_is_ignored: bool,
686 impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
690 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
691 /// argument, or the return place.
692 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
693 pub struct LocalDecl<'tcx> {
694 /// `let mut x` vs `let x`.
696 /// Temporaries and the return place are always mutable.
697 pub mutability: Mutability,
699 /// Some(binding_mode) if this corresponds to a user-declared local variable.
701 /// This is solely used for local diagnostics when generating
702 /// warnings/errors when compiling the current crate, and
703 /// therefore it need not be visible across crates. pnkfelix
704 /// currently hypothesized we *need* to wrap this in a
705 /// `ClearCrossCrate` as long as it carries as `HirId`.
706 pub is_user_variable: Option<ClearCrossCrate<BindingForm<'tcx>>>,
708 /// True if this is an internal local
710 /// These locals are not based on types in the source code and are only used
711 /// for a few desugarings at the moment.
713 /// The generator transformation will sanity check the locals which are live
714 /// across a suspension point against the type components of the generator
715 /// which type checking knows are live across a suspension point. We need to
716 /// flag drop flags to avoid triggering this check as they are introduced
719 /// Unsafety checking will also ignore dereferences of these locals,
720 /// so they can be used for raw pointers only used in a desugaring.
722 /// This should be sound because the drop flags are fully algebraic, and
723 /// therefore don't affect the OIBIT or outlives properties of the
727 /// If this local is a temporary and `is_block_tail` is `Some`,
728 /// then it is a temporary created for evaluation of some
729 /// subexpression of some block's tail expression (with no
730 /// intervening statement context).
731 pub is_block_tail: Option<BlockTailInfo>,
733 /// Type of this local.
736 /// If the user manually ascribed a type to this variable,
737 /// e.g. via `let x: T`, then we carry that type here. The MIR
738 /// borrow checker needs this information since it can affect
739 /// region inference.
740 pub user_ty: Option<(UserTypeAnnotation<'tcx>, Span)>,
742 /// Name of the local, used in debuginfo and pretty-printing.
744 /// Note that function arguments can also have this set to `Some(_)`
745 /// to generate better debuginfo.
746 pub name: Option<Name>,
748 /// The *syntactic* (i.e. not visibility) source scope the local is defined
749 /// in. If the local was defined in a let-statement, this
750 /// is *within* the let-statement, rather than outside
753 /// This is needed because the visibility source scope of locals within
754 /// a let-statement is weird.
756 /// The reason is that we want the local to be *within* the let-statement
757 /// for lint purposes, but we want the local to be *after* the let-statement
758 /// for names-in-scope purposes.
760 /// That's it, if we have a let-statement like the one in this
764 /// fn foo(x: &str) {
765 /// #[allow(unused_mut)]
766 /// let mut x: u32 = { // <- one unused mut
767 /// let mut y: u32 = x.parse().unwrap();
774 /// Then, from a lint point of view, the declaration of `x: u32`
775 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
776 /// lint scopes are the same as the AST/HIR nesting.
778 /// However, from a name lookup point of view, the scopes look more like
779 /// as if the let-statements were `match` expressions:
782 /// fn foo(x: &str) {
784 /// match x.parse().unwrap() {
793 /// We care about the name-lookup scopes for debuginfo - if the
794 /// debuginfo instruction pointer is at the call to `x.parse()`, we
795 /// want `x` to refer to `x: &str`, but if it is at the call to
796 /// `drop(x)`, we want it to refer to `x: u32`.
798 /// To allow both uses to work, we need to have more than a single scope
799 /// for a local. We have the `source_info.scope` represent the
800 /// "syntactic" lint scope (with a variable being under its let
801 /// block) while the `visibility_scope` represents the "local variable"
802 /// scope (where the "rest" of a block is under all prior let-statements).
804 /// The end result looks like this:
808 /// │{ argument x: &str }
810 /// │ │{ #[allow(unused_mut)] } // this is actually split into 2 scopes
811 /// │ │ // in practice because I'm lazy.
813 /// │ │← x.source_info.scope
814 /// │ │← `x.parse().unwrap()`
816 /// │ │ │← y.source_info.scope
818 /// │ │ │{ let y: u32 }
820 /// │ │ │← y.visibility_scope
823 /// │ │{ let x: u32 }
824 /// │ │← x.visibility_scope
825 /// │ │← `drop(x)` // this accesses `x: u32`
827 pub source_info: SourceInfo,
829 /// Source scope within which the local is visible (for debuginfo)
830 /// (see `source_info` for more details).
831 pub visibility_scope: SourceScope,
834 impl<'tcx> LocalDecl<'tcx> {
835 /// Returns true only if local is a binding that can itself be
836 /// made mutable via the addition of the `mut` keyword, namely
837 /// something like the occurrences of `x` in:
838 /// - `fn foo(x: Type) { ... }`,
840 /// - or `match ... { C(x) => ... }`
841 pub fn can_be_made_mutable(&self) -> bool {
842 match self.is_user_variable {
843 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
844 binding_mode: ty::BindingMode::BindByValue(_),
850 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(ImplicitSelfKind::Imm)))
857 /// Returns true if local is definitely not a `ref ident` or
858 /// `ref mut ident` binding. (Such bindings cannot be made into
859 /// mutable bindings, but the inverse does not necessarily hold).
860 pub fn is_nonref_binding(&self) -> bool {
861 match self.is_user_variable {
862 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
863 binding_mode: ty::BindingMode::BindByValue(_),
869 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(_))) => true,
875 /// Create a new `LocalDecl` for a temporary.
877 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
878 Self::new_local(ty, Mutability::Mut, false, span)
881 /// Converts `self` into same `LocalDecl` except tagged as immutable.
883 pub fn immutable(mut self) -> Self {
884 self.mutability = Mutability::Not;
888 /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
890 pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
891 assert!(self.is_block_tail.is_none());
892 self.is_block_tail = Some(info);
896 /// Create a new `LocalDecl` for a internal temporary.
898 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
899 Self::new_local(ty, Mutability::Mut, true, span)
905 mutability: Mutability,
914 source_info: SourceInfo {
916 scope: OUTERMOST_SOURCE_SCOPE,
918 visibility_scope: OUTERMOST_SOURCE_SCOPE,
920 is_user_variable: None,
925 /// Builds a `LocalDecl` for the return place.
927 /// This must be inserted into the `local_decls` list as the first local.
929 pub fn new_return_place(return_ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
931 mutability: Mutability::Mut,
934 source_info: SourceInfo {
936 scope: OUTERMOST_SOURCE_SCOPE,
938 visibility_scope: OUTERMOST_SOURCE_SCOPE,
941 name: None, // FIXME maybe we do want some name here?
942 is_user_variable: None,
947 /// A closure capture, with its name and mode.
948 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
949 pub struct UpvarDecl {
950 pub debug_name: Name,
952 /// `HirId` of the captured variable
953 pub var_hir_id: ClearCrossCrate<HirId>,
955 /// If true, the capture is behind a reference.
958 pub mutability: Mutability,
961 ///////////////////////////////////////////////////////////////////////////
965 pub struct BasicBlock {
966 DEBUG_FORMAT = "bb{}",
967 const START_BLOCK = 0,
972 pub fn start_location(self) -> Location {
980 ///////////////////////////////////////////////////////////////////////////
981 // BasicBlockData and Terminator
983 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
984 pub struct BasicBlockData<'tcx> {
985 /// List of statements in this block.
986 pub statements: Vec<Statement<'tcx>>,
988 /// Terminator for this block.
990 /// NB. This should generally ONLY be `None` during construction.
991 /// Therefore, you should generally access it via the
992 /// `terminator()` or `terminator_mut()` methods. The only
993 /// exception is that certain passes, such as `simplify_cfg`, swap
994 /// out the terminator temporarily with `None` while they continue
995 /// to recurse over the set of basic blocks.
996 pub terminator: Option<Terminator<'tcx>>,
998 /// If true, this block lies on an unwind path. This is used
999 /// during codegen where distinct kinds of basic blocks may be
1000 /// generated (particularly for MSVC cleanup). Unwind blocks must
1001 /// only branch to other unwind blocks.
1002 pub is_cleanup: bool,
1005 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1006 pub struct Terminator<'tcx> {
1007 pub source_info: SourceInfo,
1008 pub kind: TerminatorKind<'tcx>,
1011 #[derive(Clone, RustcEncodable, RustcDecodable)]
1012 pub enum TerminatorKind<'tcx> {
1013 /// block should have one successor in the graph; we jump there
1014 Goto { target: BasicBlock },
1016 /// operand evaluates to an integer; jump depending on its value
1017 /// to one of the targets, and otherwise fallback to `otherwise`
1019 /// discriminant value being tested
1020 discr: Operand<'tcx>,
1022 /// type of value being tested
1023 switch_ty: Ty<'tcx>,
1025 /// Possible values. The locations to branch to in each case
1026 /// are found in the corresponding indices from the `targets` vector.
1027 values: Cow<'tcx, [u128]>,
1029 /// Possible branch sites. The last element of this vector is used
1030 /// for the otherwise branch, so targets.len() == values.len() + 1
1032 // This invariant is quite non-obvious and also could be improved.
1033 // One way to make this invariant is to have something like this instead:
1035 // branches: Vec<(ConstInt, BasicBlock)>,
1036 // otherwise: Option<BasicBlock> // exhaustive if None
1038 // However we’ve decided to keep this as-is until we figure a case
1039 // where some other approach seems to be strictly better than other.
1040 targets: Vec<BasicBlock>,
1043 /// Indicates that the landing pad is finished and unwinding should
1044 /// continue. Emitted by build::scope::diverge_cleanup.
1047 /// Indicates that the landing pad is finished and that the process
1048 /// should abort. Used to prevent unwinding for foreign items.
1051 /// Indicates a normal return. The return place should have
1052 /// been filled in by now. This should occur at most once.
1055 /// Indicates a terminator that can never be reached.
1060 location: Place<'tcx>,
1062 unwind: Option<BasicBlock>,
1065 /// Drop the Place and assign the new value over it. This ensures
1066 /// that the assignment to `P` occurs *even if* the destructor for
1067 /// place unwinds. Its semantics are best explained by the
1072 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
1080 /// Drop(P, goto BB1, unwind BB2)
1083 /// // P is now uninitialized
1087 /// // P is now uninitialized -- its dtor panicked
1092 location: Place<'tcx>,
1093 value: Operand<'tcx>,
1095 unwind: Option<BasicBlock>,
1098 /// Block ends with a call of a converging function
1100 /// The function that’s being called
1101 func: Operand<'tcx>,
1102 /// Arguments the function is called with.
1103 /// These are owned by the callee, which is free to modify them.
1104 /// This allows the memory occupied by "by-value" arguments to be
1105 /// reused across function calls without duplicating the contents.
1106 args: Vec<Operand<'tcx>>,
1107 /// Destination for the return value. If some, the call is converging.
1108 destination: Option<(Place<'tcx>, BasicBlock)>,
1109 /// Cleanups to be done if the call unwinds.
1110 cleanup: Option<BasicBlock>,
1111 /// Whether this is from a call in HIR, rather than from an overloaded
1112 /// operator. True for overloaded function call.
1113 from_hir_call: bool,
1116 /// Jump to the target if the condition has the expected value,
1117 /// otherwise panic with a message and a cleanup target.
1119 cond: Operand<'tcx>,
1121 msg: AssertMessage<'tcx>,
1123 cleanup: Option<BasicBlock>,
1128 /// The value to return
1129 value: Operand<'tcx>,
1130 /// Where to resume to
1132 /// Cleanup to be done if the generator is dropped at this suspend point
1133 drop: Option<BasicBlock>,
1136 /// Indicates the end of the dropping of a generator
1139 /// A block where control flow only ever takes one real path, but borrowck
1140 /// needs to be more conservative.
1142 /// The target normal control flow will take
1143 real_target: BasicBlock,
1144 /// The list of blocks control flow could conceptually take, but won't
1146 imaginary_targets: Vec<BasicBlock>,
1148 /// A terminator for blocks that only take one path in reality, but where we
1149 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
1150 /// This can arise in infinite loops with no function calls for example.
1152 /// The target normal control flow will take
1153 real_target: BasicBlock,
1154 /// The imaginary cleanup block link. This particular path will never be taken
1155 /// in practice, but in order to avoid fragility we want to always
1156 /// consider it in borrowck. We don't want to accept programs which
1157 /// pass borrowck only when panic=abort or some assertions are disabled
1158 /// due to release vs. debug mode builds. This needs to be an Option because
1159 /// of the remove_noop_landing_pads and no_landing_pads passes
1160 unwind: Option<BasicBlock>,
1164 pub type Successors<'a> =
1165 iter::Chain<option::IntoIter<&'a BasicBlock>, slice::Iter<'a, BasicBlock>>;
1166 pub type SuccessorsMut<'a> =
1167 iter::Chain<option::IntoIter<&'a mut BasicBlock>, slice::IterMut<'a, BasicBlock>>;
1169 impl<'tcx> Terminator<'tcx> {
1170 pub fn successors(&self) -> Successors<'_> {
1171 self.kind.successors()
1174 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1175 self.kind.successors_mut()
1178 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1182 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1183 self.kind.unwind_mut()
1187 impl<'tcx> TerminatorKind<'tcx> {
1188 pub fn if_<'a, 'gcx>(
1189 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1190 cond: Operand<'tcx>,
1193 ) -> TerminatorKind<'tcx> {
1194 static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
1195 TerminatorKind::SwitchInt {
1197 switch_ty: tcx.types.bool,
1198 values: From::from(BOOL_SWITCH_FALSE),
1199 targets: vec![f, t],
1203 pub fn successors(&self) -> Successors<'_> {
1204 use self::TerminatorKind::*;
1215 } => None.into_iter().chain(&[]),
1216 Goto { target: ref t }
1219 cleanup: Some(ref t),
1223 destination: Some((_, ref t)),
1250 } => Some(t).into_iter().chain(&[]),
1252 destination: Some((_, ref t)),
1253 cleanup: Some(ref u),
1263 unwind: Some(ref u),
1268 unwind: Some(ref u),
1273 cleanup: Some(ref u),
1278 unwind: Some(ref u),
1279 } => Some(t).into_iter().chain(slice::from_ref(u)),
1280 SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
1283 ref imaginary_targets,
1284 } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
1288 pub fn successors_mut(&mut self) -> SuccessorsMut<'_> {
1289 use self::TerminatorKind::*;
1300 } => None.into_iter().chain(&mut []),
1301 Goto { target: ref mut t }
1304 cleanup: Some(ref mut t),
1308 destination: Some((_, ref mut t)),
1333 real_target: ref mut t,
1335 } => Some(t).into_iter().chain(&mut []),
1337 destination: Some((_, ref mut t)),
1338 cleanup: Some(ref mut u),
1343 drop: Some(ref mut u),
1348 unwind: Some(ref mut u),
1353 unwind: Some(ref mut u),
1358 cleanup: Some(ref mut u),
1362 real_target: ref mut t,
1363 unwind: Some(ref mut u),
1364 } => Some(t).into_iter().chain(slice::from_mut(u)),
1367 } => None.into_iter().chain(&mut targets[..]),
1369 ref mut real_target,
1370 ref mut imaginary_targets,
1371 } => Some(real_target)
1373 .chain(&mut imaginary_targets[..]),
1377 pub fn unwind(&self) -> Option<&Option<BasicBlock>> {
1379 TerminatorKind::Goto { .. }
1380 | TerminatorKind::Resume
1381 | TerminatorKind::Abort
1382 | TerminatorKind::Return
1383 | TerminatorKind::Unreachable
1384 | TerminatorKind::GeneratorDrop
1385 | TerminatorKind::Yield { .. }
1386 | TerminatorKind::SwitchInt { .. }
1387 | TerminatorKind::FalseEdges { .. } => None,
1388 TerminatorKind::Call {
1389 cleanup: ref unwind,
1392 | TerminatorKind::Assert {
1393 cleanup: ref unwind,
1396 | TerminatorKind::DropAndReplace { ref unwind, .. }
1397 | TerminatorKind::Drop { ref unwind, .. }
1398 | TerminatorKind::FalseUnwind { ref unwind, .. } => Some(unwind),
1402 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
1404 TerminatorKind::Goto { .. }
1405 | TerminatorKind::Resume
1406 | TerminatorKind::Abort
1407 | TerminatorKind::Return
1408 | TerminatorKind::Unreachable
1409 | TerminatorKind::GeneratorDrop
1410 | TerminatorKind::Yield { .. }
1411 | TerminatorKind::SwitchInt { .. }
1412 | TerminatorKind::FalseEdges { .. } => None,
1413 TerminatorKind::Call {
1414 cleanup: ref mut unwind,
1417 | TerminatorKind::Assert {
1418 cleanup: ref mut unwind,
1421 | TerminatorKind::DropAndReplace { ref mut unwind, .. }
1422 | TerminatorKind::Drop { ref mut unwind, .. }
1423 | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
1428 impl<'tcx> BasicBlockData<'tcx> {
1429 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
1437 /// Accessor for terminator.
1439 /// Terminator may not be None after construction of the basic block is complete. This accessor
1440 /// provides a convenience way to reach the terminator.
1441 pub fn terminator(&self) -> &Terminator<'tcx> {
1442 self.terminator.as_ref().expect("invalid terminator state")
1445 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
1446 self.terminator.as_mut().expect("invalid terminator state")
1449 pub fn retain_statements<F>(&mut self, mut f: F)
1451 F: FnMut(&mut Statement<'_>) -> bool,
1453 for s in &mut self.statements {
1460 pub fn expand_statements<F, I>(&mut self, mut f: F)
1462 F: FnMut(&mut Statement<'tcx>) -> Option<I>,
1463 I: iter::TrustedLen<Item = Statement<'tcx>>,
1465 // Gather all the iterators we'll need to splice in, and their positions.
1466 let mut splices: Vec<(usize, I)> = vec![];
1467 let mut extra_stmts = 0;
1468 for (i, s) in self.statements.iter_mut().enumerate() {
1469 if let Some(mut new_stmts) = f(s) {
1470 if let Some(first) = new_stmts.next() {
1471 // We can already store the first new statement.
1474 // Save the other statements for optimized splicing.
1475 let remaining = new_stmts.size_hint().0;
1477 splices.push((i + 1 + extra_stmts, new_stmts));
1478 extra_stmts += remaining;
1486 // Splice in the new statements, from the end of the block.
1487 // FIXME(eddyb) This could be more efficient with a "gap buffer"
1488 // where a range of elements ("gap") is left uninitialized, with
1489 // splicing adding new elements to the end of that gap and moving
1490 // existing elements from before the gap to the end of the gap.
1491 // For now, this is safe code, emulating a gap but initializing it.
1492 let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
1493 self.statements.resize(
1496 source_info: SourceInfo {
1498 scope: OUTERMOST_SOURCE_SCOPE,
1500 kind: StatementKind::Nop,
1503 for (splice_start, new_stmts) in splices.into_iter().rev() {
1504 let splice_end = splice_start + new_stmts.size_hint().0;
1505 while gap.end > splice_end {
1508 self.statements.swap(gap.start, gap.end);
1510 self.statements.splice(splice_start..splice_end, new_stmts);
1511 gap.end = splice_start;
1515 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
1516 if index < self.statements.len() {
1517 &self.statements[index]
1524 impl<'tcx> Debug for TerminatorKind<'tcx> {
1525 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1526 self.fmt_head(fmt)?;
1527 let successor_count = self.successors().count();
1528 let labels = self.fmt_successor_labels();
1529 assert_eq!(successor_count, labels.len());
1531 match successor_count {
1534 1 => write!(fmt, " -> {:?}", self.successors().nth(0).unwrap()),
1537 write!(fmt, " -> [")?;
1538 for (i, target) in self.successors().enumerate() {
1542 write!(fmt, "{}: {:?}", labels[i], target)?;
1550 impl<'tcx> TerminatorKind<'tcx> {
1551 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1552 /// successor basic block, if any. The only information not included is the list of possible
1553 /// successors, which may be rendered differently between the text and the graphviz format.
1554 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1555 use self::TerminatorKind::*;
1557 Goto { .. } => write!(fmt, "goto"),
1559 discr: ref place, ..
1560 } => write!(fmt, "switchInt({:?})", place),
1561 Return => write!(fmt, "return"),
1562 GeneratorDrop => write!(fmt, "generator_drop"),
1563 Resume => write!(fmt, "resume"),
1564 Abort => write!(fmt, "abort"),
1565 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1566 Unreachable => write!(fmt, "unreachable"),
1567 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1572 } => write!(fmt, "replace({:?} <- {:?})", location, value),
1579 if let Some((ref destination, _)) = *destination {
1580 write!(fmt, "{:?} = ", destination)?;
1582 write!(fmt, "{:?}(", func)?;
1583 for (index, arg) in args.iter().enumerate() {
1587 write!(fmt, "{:?}", arg)?;
1597 write!(fmt, "assert(")?;
1601 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
1603 FalseEdges { .. } => write!(fmt, "falseEdges"),
1604 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1608 /// Return the list of labels for the edges to the successor basic blocks.
1609 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1610 use self::TerminatorKind::*;
1612 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1613 Goto { .. } => vec!["".into()],
1619 let size = ty::tls::with(|tcx| {
1620 let param_env = ty::ParamEnv::empty();
1621 let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
1622 tcx.layout_of(param_env.and(switch_ty)).unwrap().size
1627 let mut s = String::new();
1629 val: ConstValue::Scalar(
1632 size: size.bytes() as u8,
1637 fmt_const_val(&mut s, &c).unwrap();
1639 }).chain(iter::once("otherwise".into()))
1643 destination: Some(_),
1646 } => vec!["return".into(), "unwind".into()],
1648 destination: Some(_),
1651 } => vec!["return".into()],
1656 } => vec!["unwind".into()],
1662 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1663 Yield { drop: None, .. } => vec!["resume".into()],
1664 DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
1665 vec!["return".into()]
1672 } => vec!["return".into(), "unwind".into()],
1673 Assert { cleanup: None, .. } => vec!["".into()],
1674 Assert { .. } => vec!["success".into(), "unwind".into()],
1676 ref imaginary_targets,
1679 let mut l = vec!["real".into()];
1680 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1685 } => vec!["real".into(), "cleanup".into()],
1686 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1691 ///////////////////////////////////////////////////////////////////////////
1694 #[derive(Clone, RustcEncodable, RustcDecodable)]
1695 pub struct Statement<'tcx> {
1696 pub source_info: SourceInfo,
1697 pub kind: StatementKind<'tcx>,
1700 impl<'tcx> Statement<'tcx> {
1701 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1702 /// invalidating statement indices in `Location`s.
1703 pub fn make_nop(&mut self) {
1704 self.kind = StatementKind::Nop
1707 /// Changes a statement to a nop and returns the original statement.
1708 pub fn replace_nop(&mut self) -> Self {
1710 source_info: self.source_info,
1711 kind: mem::replace(&mut self.kind, StatementKind::Nop),
1716 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1717 pub enum StatementKind<'tcx> {
1718 /// Write the RHS Rvalue to the LHS Place.
1719 Assign(Place<'tcx>, Box<Rvalue<'tcx>>),
1721 /// This represents all the reading that a pattern match may do
1722 /// (e.g. inspecting constants and discriminant values), and the
1723 /// kind of pattern it comes from. This is in order to adapt potential
1724 /// error messages to these specific patterns.
1725 FakeRead(FakeReadCause, Place<'tcx>),
1727 /// Write the discriminant for a variant to the enum Place.
1730 variant_index: usize,
1733 /// Start a live range for the storage of the local.
1736 /// End the current live range for the storage of the local.
1739 /// Execute a piece of inline Assembly.
1741 asm: Box<InlineAsm>,
1742 outputs: Box<[Place<'tcx>]>,
1743 inputs: Box<[Operand<'tcx>]>,
1746 /// Assert the given places to be valid inhabitants of their type. These statements are
1747 /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1748 /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1749 Validate(ValidationOp, Vec<ValidationOperand<'tcx, Place<'tcx>>>),
1751 /// Mark one terminating point of a region scope (i.e. static region).
1752 /// (The starting point(s) arise implicitly from borrows.)
1753 EndRegion(region::Scope),
1755 /// Encodes a user's type ascription. These need to be preserved
1756 /// intact so that NLL can respect them. For example:
1760 /// The effect of this annotation is to relate the type `T_y` of the place `y`
1761 /// to the user-given type `T`. The effect depends on the specified variance:
1763 /// - `Covariant` -- requires that `T_y <: T`
1764 /// - `Contravariant` -- requires that `T_y :> T`
1765 /// - `Invariant` -- requires that `T_y == T`
1766 /// - `Bivariant` -- no effect
1767 AscribeUserType(Place<'tcx>, ty::Variance, UserTypeAnnotation<'tcx>),
1769 /// No-op. Useful for deleting instructions without affecting statement indices.
1773 /// The `FakeReadCause` describes the type of pattern why a `FakeRead` statement exists.
1774 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1775 pub enum FakeReadCause {
1776 /// Inject a fake read of the borrowed input at the start of each arm's
1777 /// pattern testing code.
1779 /// This should ensure that you cannot change the variant for an enum
1780 /// while you are in the midst of matching on it.
1783 /// `let x: !; match x {}` doesn't generate any read of x so we need to
1784 /// generate a read of x to check that it is initialized and safe.
1787 /// Officially, the semantics of
1789 /// `let pattern = <expr>;`
1791 /// is that `<expr>` is evaluated into a temporary and then this temporary is
1792 /// into the pattern.
1794 /// However, if we see the simple pattern `let var = <expr>`, we optimize this to
1795 /// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
1796 /// but in some cases it can affect the borrow checker, as in #53695.
1797 /// Therefore, we insert a "fake read" here to ensure that we get
1798 /// appropriate errors.
1802 /// The `ValidationOp` describes what happens with each of the operands of a
1803 /// `Validate` statement.
1804 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1805 pub enum ValidationOp {
1806 /// Recursively traverse the place following the type and validate that all type
1807 /// invariants are maintained. Furthermore, acquire exclusive/read-only access to the
1808 /// memory reachable from the place.
1810 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1813 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1814 /// access *until* the given region ends. Then, access will be recovered.
1815 Suspend(region::Scope),
1818 impl Debug for ValidationOp {
1819 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1820 use self::ValidationOp::*;
1822 Acquire => write!(fmt, "Acquire"),
1823 Release => write!(fmt, "Release"),
1824 // (reuse lifetime rendering policy from ppaux.)
1825 Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1830 // This is generic so that it can be reused by miri
1831 #[derive(Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1832 pub struct ValidationOperand<'tcx, T> {
1835 pub re: Option<region::Scope>,
1836 pub mutbl: hir::Mutability,
1839 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1840 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1841 write!(fmt, "{:?}: {:?}", self.place, self.ty)?;
1842 if let Some(ce) = self.re {
1843 // (reuse lifetime rendering policy from ppaux.)
1844 write!(fmt, "/{}", ty::ReScope(ce))?;
1846 if let hir::MutImmutable = self.mutbl {
1847 write!(fmt, " (imm)")?;
1853 impl<'tcx> Debug for Statement<'tcx> {
1854 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1855 use self::StatementKind::*;
1857 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1858 FakeRead(ref cause, ref place) => write!(fmt, "FakeRead({:?}, {:?})", cause, place),
1859 // (reuse lifetime rendering policy from ppaux.)
1860 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1861 Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
1862 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1863 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1867 } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
1872 } => write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs),
1873 AscribeUserType(ref place, ref variance, ref c_ty) => {
1874 write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
1876 Nop => write!(fmt, "nop"),
1881 ///////////////////////////////////////////////////////////////////////////
1884 /// A path to a value; something that can be evaluated without
1885 /// changing or disturbing program state.
1886 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1887 pub enum Place<'tcx> {
1891 /// static or static mut variable
1892 Static(Box<Static<'tcx>>),
1894 /// Constant code promoted to an injected static
1895 Promoted(Box<(Promoted, Ty<'tcx>)>),
1897 /// projection out of a place (access a field, deref a pointer, etc)
1898 Projection(Box<PlaceProjection<'tcx>>),
1901 /// The def-id of a static, along with its normalized type (which is
1902 /// stored to avoid requiring normalization when reading MIR).
1903 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1904 pub struct Static<'tcx> {
1909 impl_stable_hash_for!(struct Static<'tcx> {
1914 /// The `Projection` data structure defines things of the form `B.x`
1915 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1916 /// shared between `Constant` and `Place`. See the aliases
1917 /// `PlaceProjection` etc below.
1918 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1919 pub struct Projection<'tcx, B, V, T> {
1921 pub elem: ProjectionElem<'tcx, V, T>,
1924 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1925 pub enum ProjectionElem<'tcx, V, T> {
1930 /// These indices are generated by slice patterns. Easiest to explain
1934 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1935 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1936 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1937 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1940 /// index or -index (in Python terms), depending on from_end
1942 /// thing being indexed must be at least this long
1944 /// counting backwards from end?
1948 /// These indices are generated by slice patterns.
1950 /// slice[from:-to] in Python terms.
1956 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1957 /// this for ADTs with more than one variant. It may be better to
1958 /// just introduce it always, or always for enums.
1959 Downcast(&'tcx AdtDef, usize),
1962 /// Alias for projections as they appear in places, where the base is a place
1963 /// and the index is a local.
1964 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1966 /// Alias for projections as they appear in places, where the base is a place
1967 /// and the index is a local.
1968 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1972 DEBUG_FORMAT = "field[{}]"
1976 impl<'tcx> Place<'tcx> {
1977 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1978 self.elem(ProjectionElem::Field(f, ty))
1981 pub fn deref(self) -> Place<'tcx> {
1982 self.elem(ProjectionElem::Deref)
1985 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1986 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1989 pub fn index(self, index: Local) -> Place<'tcx> {
1990 self.elem(ProjectionElem::Index(index))
1993 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1994 Place::Projection(Box::new(PlaceProjection { base: self, elem }))
1997 /// Find the innermost `Local` from this `Place`, *if* it is either a local itself or
1998 /// a single deref of a local.
2000 /// FIXME: can we safely swap the semantics of `fn base_local` below in here instead?
2001 pub fn local(&self) -> Option<Local> {
2003 Place::Local(local) |
2004 Place::Projection(box Projection {
2005 base: Place::Local(local),
2006 elem: ProjectionElem::Deref,
2012 /// Find the innermost `Local` from this `Place`.
2013 pub fn base_local(&self) -> Option<Local> {
2015 Place::Local(local) => Some(*local),
2016 Place::Projection(box Projection { base, elem: _ }) => base.base_local(),
2017 Place::Promoted(..) | Place::Static(..) => None,
2022 impl<'tcx> Debug for Place<'tcx> {
2023 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2027 Local(id) => write!(fmt, "{:?}", id),
2028 Static(box self::Static { def_id, ty }) => write!(
2031 ty::tls::with(|tcx| tcx.item_path_str(def_id)),
2034 Promoted(ref promoted) => write!(fmt, "({:?}: {:?})", promoted.0, promoted.1),
2035 Projection(ref data) => match data.elem {
2036 ProjectionElem::Downcast(ref adt_def, index) => {
2037 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name)
2039 ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
2040 ProjectionElem::Field(field, ty) => {
2041 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
2043 ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
2044 ProjectionElem::ConstantIndex {
2048 } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
2049 ProjectionElem::ConstantIndex {
2053 } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
2054 ProjectionElem::Subslice { from, to } if to == 0 => {
2055 write!(fmt, "{:?}[{:?}:]", data.base, from)
2057 ProjectionElem::Subslice { from, to } if from == 0 => {
2058 write!(fmt, "{:?}[:-{:?}]", data.base, to)
2060 ProjectionElem::Subslice { from, to } => {
2061 write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
2068 ///////////////////////////////////////////////////////////////////////////
2072 pub struct SourceScope {
2073 DEBUG_FORMAT = "scope[{}]",
2074 const OUTERMOST_SOURCE_SCOPE = 0,
2078 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2079 pub struct SourceScopeData {
2081 pub parent_scope: Option<SourceScope>,
2084 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2085 pub struct SourceScopeLocalData {
2086 /// A NodeId with lint levels equivalent to this scope's lint levels.
2087 pub lint_root: ast::NodeId,
2088 /// The unsafe block that contains this node.
2092 ///////////////////////////////////////////////////////////////////////////
2095 /// These are values that can appear inside an rvalue (or an index
2096 /// place). They are intentionally limited to prevent rvalues from
2097 /// 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 pub struct Promoted {
2470 DEBUG_FORMAT = "promoted[{}]"
2474 impl<'tcx> Debug for Constant<'tcx> {
2475 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
2476 write!(fmt, "const ")?;
2477 fmt_const_val(fmt, self.literal)
2481 /// Write a `ConstValue` in a way closer to the original source code than the `Debug` output.
2482 pub fn fmt_const_val(f: &mut impl Write, const_val: &ty::Const<'_>) -> fmt::Result {
2484 let value = const_val.val;
2485 let ty = const_val.ty;
2486 // print some primitives
2487 if let ConstValue::Scalar(Scalar::Bits { bits, .. }) = value {
2489 Bool if bits == 0 => return write!(f, "false"),
2490 Bool if bits == 1 => return write!(f, "true"),
2491 Float(ast::FloatTy::F32) => return write!(f, "{}f32", Single::from_bits(bits)),
2492 Float(ast::FloatTy::F64) => return write!(f, "{}f64", Double::from_bits(bits)),
2493 Uint(ui) => return write!(f, "{:?}{}", bits, ui),
2495 let bit_width = ty::tls::with(|tcx| {
2496 let ty = tcx.lift_to_global(&ty).unwrap();
2497 tcx.layout_of(ty::ParamEnv::empty().and(ty))
2502 let shift = 128 - bit_width;
2503 return write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i);
2505 Char => return write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
2509 // print function definitons
2510 if let FnDef(did, _) = ty.sty {
2511 return write!(f, "{}", item_path_str(did));
2513 // print string literals
2514 if let ConstValue::ScalarPair(ptr, len) = value {
2515 if let Scalar::Ptr(ptr) = ptr {
2516 if let Scalar::Bits { bits: len, .. } = len {
2517 if let Ref(_, &ty::TyS { sty: Str, .. }, _) = ty.sty {
2518 return ty::tls::with(|tcx| {
2519 let alloc = tcx.alloc_map.lock().get(ptr.alloc_id);
2520 if let Some(interpret::AllocType::Memory(alloc)) = alloc {
2521 assert_eq!(len as usize as u128, len);
2523 &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
2524 let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
2525 write!(f, "{:?}", s)
2527 write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len)
2534 // just raw dump everything else
2535 write!(f, "{:?}:{}", value, ty)
2538 fn item_path_str(def_id: DefId) -> String {
2539 ty::tls::with(|tcx| tcx.item_path_str(def_id))
2542 impl<'tcx> graph::DirectedGraph for Mir<'tcx> {
2543 type Node = BasicBlock;
2546 impl<'tcx> graph::WithNumNodes for Mir<'tcx> {
2547 fn num_nodes(&self) -> usize {
2548 self.basic_blocks.len()
2552 impl<'tcx> graph::WithStartNode for Mir<'tcx> {
2553 fn start_node(&self) -> Self::Node {
2558 impl<'tcx> graph::WithPredecessors for Mir<'tcx> {
2559 fn predecessors<'graph>(
2562 ) -> <Self as GraphPredecessors<'graph>>::Iter {
2563 self.predecessors_for(node).clone().into_iter()
2567 impl<'tcx> graph::WithSuccessors for Mir<'tcx> {
2568 fn successors<'graph>(
2571 ) -> <Self as GraphSuccessors<'graph>>::Iter {
2572 self.basic_blocks[node].terminator().successors().cloned()
2576 impl<'a, 'b> graph::GraphPredecessors<'b> for Mir<'a> {
2577 type Item = BasicBlock;
2578 type Iter = IntoIter<BasicBlock>;
2581 impl<'a, 'b> graph::GraphSuccessors<'b> for Mir<'a> {
2582 type Item = BasicBlock;
2583 type Iter = iter::Cloned<Successors<'b>>;
2586 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
2587 pub struct Location {
2588 /// the location is within this block
2589 pub block: BasicBlock,
2591 /// the location is the start of the statement; or, if `statement_index`
2592 /// == num-statements, then the start of the terminator.
2593 pub statement_index: usize,
2596 impl fmt::Debug for Location {
2597 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2598 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
2603 pub const START: Location = Location {
2608 /// Returns the location immediately after this one within the enclosing block.
2610 /// Note that if this location represents a terminator, then the
2611 /// resulting location would be out of bounds and invalid.
2612 pub fn successor_within_block(&self) -> Location {
2615 statement_index: self.statement_index + 1,
2619 pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
2620 if self.block == other.block {
2621 self.statement_index <= other.statement_index
2623 dominators.is_dominated_by(other.block, self.block)
2628 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2629 pub enum UnsafetyViolationKind {
2631 /// unsafety is not allowed at all in min const fn
2633 ExternStatic(ast::NodeId),
2634 BorrowPacked(ast::NodeId),
2637 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2638 pub struct UnsafetyViolation {
2639 pub source_info: SourceInfo,
2640 pub description: InternedString,
2641 pub details: InternedString,
2642 pub kind: UnsafetyViolationKind,
2645 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
2646 pub struct UnsafetyCheckResult {
2647 /// Violations that are propagated *upwards* from this function
2648 pub violations: Lrc<[UnsafetyViolation]>,
2649 /// unsafe blocks in this function, along with whether they are used. This is
2650 /// used for the "unused_unsafe" lint.
2651 pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>,
2654 /// The layout of generator state
2655 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2656 pub struct GeneratorLayout<'tcx> {
2657 pub fields: Vec<LocalDecl<'tcx>>,
2660 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2661 pub struct BorrowCheckResult<'gcx> {
2662 pub closure_requirements: Option<ClosureRegionRequirements<'gcx>>,
2663 pub used_mut_upvars: SmallVec<[Field; 8]>,
2666 /// After we borrow check a closure, we are left with various
2667 /// requirements that we have inferred between the free regions that
2668 /// appear in the closure's signature or on its field types. These
2669 /// requirements are then verified and proved by the closure's
2670 /// creating function. This struct encodes those requirements.
2672 /// The requirements are listed as being between various
2673 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
2674 /// vids refer to the free regions that appear in the closure (or
2675 /// generator's) type, in order of appearance. (This numbering is
2676 /// actually defined by the `UniversalRegions` struct in the NLL
2677 /// region checker. See for example
2678 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
2679 /// regions in the closure's type "as if" they were erased, so their
2680 /// precise identity is not important, only their position.
2682 /// Example: If type check produces a closure with the closure substs:
2685 /// ClosureSubsts = [
2686 /// i8, // the "closure kind"
2687 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
2688 /// &'a String, // some upvar
2692 /// here, there is one unique free region (`'a`) but it appears
2693 /// twice. We would "renumber" each occurrence to a unique vid, as follows:
2696 /// ClosureSubsts = [
2697 /// i8, // the "closure kind"
2698 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
2699 /// &'2 String, // some upvar
2703 /// Now the code might impose a requirement like `'1: '2`. When an
2704 /// instance of the closure is created, the corresponding free regions
2705 /// can be extracted from its type and constrained to have the given
2706 /// outlives relationship.
2708 /// In some cases, we have to record outlives requirements between
2709 /// types and regions as well. In that case, if those types include
2710 /// any regions, those regions are recorded as `ReClosureBound`
2711 /// instances assigned one of these same indices. Those regions will
2712 /// be substituted away by the creator. We use `ReClosureBound` in
2713 /// that case because the regions must be allocated in the global
2714 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
2715 /// internally within the rest of the NLL code).
2716 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
2717 pub struct ClosureRegionRequirements<'gcx> {
2718 /// The number of external regions defined on the closure. In our
2719 /// example above, it would be 3 -- one for `'static`, then `'1`
2720 /// and `'2`. This is just used for a sanity check later on, to
2721 /// make sure that the number of regions we see at the callsite
2723 pub num_external_vids: usize,
2725 /// Requirements between the various free regions defined in
2727 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
2730 /// Indicates an outlives constraint between a type or between two
2731 /// free-regions declared on the closure.
2732 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2733 pub struct ClosureOutlivesRequirement<'tcx> {
2734 // This region or type ...
2735 pub subject: ClosureOutlivesSubject<'tcx>,
2737 // ... must outlive this one.
2738 pub outlived_free_region: ty::RegionVid,
2740 // If not, report an error here ...
2741 pub blame_span: Span,
2743 // ... due to this reason.
2744 pub category: ConstraintCategory,
2747 /// Outlives constraints can be categorized to determine whether and why they
2748 /// are interesting (for error reporting). Order of variants indicates sort
2749 /// order of the category, thereby influencing diagnostic output.
2751 /// See also [rustc_mir::borrow_check::nll::constraints]
2752 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
2753 pub enum ConstraintCategory {
2758 /// A constraint that came from checking the body of a closure.
2760 /// We try to get the category that the closure used when reporting this.
2768 /// A "boring" constraint (caused by the given location) is one that
2769 /// the user probably doesn't want to see described in diagnostics,
2770 /// because it is kind of an artifact of the type system setup.
2771 /// Example: `x = Foo { field: y }` technically creates
2772 /// intermediate regions representing the "type of `Foo { field: y
2773 /// }`", and data flows from `y` into those variables, but they
2774 /// are not very interesting. The assignment into `x` on the other
2777 // Boring and applicable everywhere.
2780 /// A constraint that doesn't correspond to anything the user sees.
2784 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2785 /// that must outlive some region.
2786 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2787 pub enum ClosureOutlivesSubject<'tcx> {
2788 /// Subject is a type, typically a type parameter, but could also
2789 /// be a projection. Indicates a requirement like `T: 'a` being
2790 /// passed to the caller, where the type here is `T`.
2792 /// The type here is guaranteed not to contain any free regions at
2796 /// Subject is a free region from the closure. Indicates a requirement
2797 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2798 Region(ty::RegionVid),
2802 * TypeFoldable implementations for MIR types
2805 CloneTypeFoldableAndLiftImpls! {
2815 SourceScopeLocalData,
2818 BraceStructTypeFoldableImpl! {
2819 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2823 source_scope_local_data,
2837 BraceStructTypeFoldableImpl! {
2838 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2843 BraceStructTypeFoldableImpl! {
2844 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
2857 BraceStructTypeFoldableImpl! {
2858 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
2865 BraceStructTypeFoldableImpl! {
2866 impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Place<'tcx>> {
2867 place, ty, re, mutbl
2871 BraceStructTypeFoldableImpl! {
2872 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
2877 EnumTypeFoldableImpl! {
2878 impl<'tcx> TypeFoldable<'tcx> for StatementKind<'tcx> {
2879 (StatementKind::Assign)(a, b),
2880 (StatementKind::FakeRead)(cause, place),
2881 (StatementKind::SetDiscriminant) { place, variant_index },
2882 (StatementKind::StorageLive)(a),
2883 (StatementKind::StorageDead)(a),
2884 (StatementKind::InlineAsm) { asm, outputs, inputs },
2885 (StatementKind::Validate)(a, b),
2886 (StatementKind::EndRegion)(a),
2887 (StatementKind::AscribeUserType)(a, v, b),
2888 (StatementKind::Nop),
2892 EnumTypeFoldableImpl! {
2893 impl<'tcx, T> TypeFoldable<'tcx> for ClearCrossCrate<T> {
2894 (ClearCrossCrate::Clear),
2895 (ClearCrossCrate::Set)(a),
2896 } where T: TypeFoldable<'tcx>
2899 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2900 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2901 use mir::TerminatorKind::*;
2903 let kind = match self.kind {
2904 Goto { target } => Goto { target: target },
2911 discr: discr.fold_with(folder),
2912 switch_ty: switch_ty.fold_with(folder),
2913 values: values.clone(),
2914 targets: targets.clone(),
2921 location: location.fold_with(folder),
2930 } => DropAndReplace {
2931 location: location.fold_with(folder),
2932 value: value.fold_with(folder),
2941 value: value.fold_with(folder),
2952 let dest = destination
2954 .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
2957 func: func.fold_with(folder),
2958 args: args.fold_with(folder),
2971 let msg = if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
2972 EvalErrorKind::BoundsCheck {
2973 len: len.fold_with(folder),
2974 index: index.fold_with(folder),
2980 cond: cond.fold_with(folder),
2987 GeneratorDrop => GeneratorDrop,
2991 Unreachable => Unreachable,
2994 ref imaginary_targets,
2997 imaginary_targets: imaginary_targets.clone(),
3008 source_info: self.source_info,
3013 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3014 use mir::TerminatorKind::*;
3021 } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
3022 Drop { ref location, .. } => location.visit_with(visitor),
3027 } => location.visit_with(visitor) || value.visit_with(visitor),
3028 Yield { ref value, .. } => value.visit_with(visitor),
3035 let dest = if let Some((ref loc, _)) = *destination {
3036 loc.visit_with(visitor)
3040 dest || func.visit_with(visitor) || args.visit_with(visitor)
3043 ref cond, ref msg, ..
3045 if cond.visit_with(visitor) {
3046 if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
3047 len.visit_with(visitor) || index.visit_with(visitor)
3062 | FalseUnwind { .. } => false,
3067 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
3068 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3070 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
3075 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3076 if let &Place::Projection(ref p) = self {
3077 p.visit_with(visitor)
3084 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
3085 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3088 Use(ref op) => Use(op.fold_with(folder)),
3089 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
3090 Ref(region, bk, ref place) => {
3091 Ref(region.fold_with(folder), bk, place.fold_with(folder))
3093 Len(ref place) => Len(place.fold_with(folder)),
3094 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
3095 BinaryOp(op, ref rhs, ref lhs) => {
3096 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3098 CheckedBinaryOp(op, ref rhs, ref lhs) => {
3099 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
3101 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
3102 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
3103 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
3104 Aggregate(ref kind, ref fields) => {
3105 let kind = box match **kind {
3106 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
3107 AggregateKind::Tuple => AggregateKind::Tuple,
3108 AggregateKind::Adt(def, v, substs, user_ty, n) => AggregateKind::Adt(
3111 substs.fold_with(folder),
3112 user_ty.fold_with(folder),
3115 AggregateKind::Closure(id, substs) => {
3116 AggregateKind::Closure(id, substs.fold_with(folder))
3118 AggregateKind::Generator(id, substs, movablity) => {
3119 AggregateKind::Generator(id, substs.fold_with(folder), movablity)
3122 Aggregate(kind, fields.fold_with(folder))
3127 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3130 Use(ref op) => op.visit_with(visitor),
3131 Repeat(ref op, _) => op.visit_with(visitor),
3132 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
3133 Len(ref place) => place.visit_with(visitor),
3134 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
3135 BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
3136 rhs.visit_with(visitor) || lhs.visit_with(visitor)
3138 UnaryOp(_, ref val) => val.visit_with(visitor),
3139 Discriminant(ref place) => place.visit_with(visitor),
3140 NullaryOp(_, ty) => ty.visit_with(visitor),
3141 Aggregate(ref kind, ref fields) => {
3143 AggregateKind::Array(ty) => ty.visit_with(visitor),
3144 AggregateKind::Tuple => false,
3145 AggregateKind::Adt(_, _, substs, user_ty, _) => {
3146 substs.visit_with(visitor) || user_ty.visit_with(visitor)
3148 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
3149 AggregateKind::Generator(_, substs, _) => substs.visit_with(visitor),
3150 }) || fields.visit_with(visitor)
3156 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
3157 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3159 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
3160 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
3161 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
3165 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3167 Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
3168 Operand::Constant(ref c) => c.visit_with(visitor),
3173 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
3175 B: TypeFoldable<'tcx>,
3176 V: TypeFoldable<'tcx>,
3177 T: TypeFoldable<'tcx>,
3179 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3180 use mir::ProjectionElem::*;
3182 let base = self.base.fold_with(folder);
3183 let elem = match self.elem {
3185 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
3186 Index(ref v) => Index(v.fold_with(folder)),
3187 ref elem => elem.clone(),
3190 Projection { base, elem }
3193 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
3194 use mir::ProjectionElem::*;
3196 self.base.visit_with(visitor) || match self.elem {
3197 Field(_, ref ty) => ty.visit_with(visitor),
3198 Index(ref v) => v.visit_with(visitor),
3204 impl<'tcx> TypeFoldable<'tcx> for Field {
3205 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, _: &mut F) -> Self {
3208 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
3213 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
3214 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
3216 span: self.span.clone(),
3217 ty: self.ty.fold_with(folder),
3218 user_ty: self.user_ty.fold_with(folder),
3219 literal: self.literal.fold_with(folder),
3222 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
3223 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)