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 module-level [README] for details.
13 //! [README]: https://github.com/rust-lang/rust/blob/master/src/librustc/mir/README.md
15 use graphviz::IntoCow;
16 use middle::const_val::ConstVal;
18 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
19 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
20 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
21 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
22 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
23 use rustc_serialize as serialize;
24 use hir::def::CtorKind;
25 use hir::def_id::DefId;
26 use mir::visit::MirVisitable;
27 use ty::subst::{Subst, Substs};
28 use ty::{self, AdtDef, ClosureSubsts, Region, Ty, TyCtxt, GeneratorInterior};
29 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
32 use hir::{self, InlineAsm};
34 use std::borrow::{Cow};
36 use std::fmt::{self, Debug, Formatter, Write};
38 use std::ops::{Index, IndexMut};
40 use std::vec::IntoIter;
41 use syntax::ast::{self, Name};
42 use syntax::symbol::InternedString;
53 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
55 pub trait HasLocalDecls<'tcx> {
56 fn local_decls(&self) -> &LocalDecls<'tcx>;
59 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
60 fn local_decls(&self) -> &LocalDecls<'tcx> {
65 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
66 fn local_decls(&self) -> &LocalDecls<'tcx> {
71 /// Lowered representation of a single function.
72 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
73 pub struct Mir<'tcx> {
74 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
75 /// that indexes into this vector.
76 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
78 /// List of visibility (lexical) scopes; these are referenced by statements
79 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
80 pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
82 /// Crate-local information for each visibility scope, that can't (and
83 /// needn't) be tracked across crates.
84 pub visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope, VisibilityScopeInfo>>,
86 /// Rvalues promoted from this function, such as borrows of constants.
87 /// Each of them is the Mir of a constant with the fn's type parameters
88 /// in scope, but a separate set of locals.
89 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
91 /// Yield type of the function, if it is a generator.
92 pub yield_ty: Option<Ty<'tcx>>,
94 /// Generator drop glue
95 pub generator_drop: Option<Box<Mir<'tcx>>>,
97 /// The layout of a generator. Produced by the state transformation.
98 pub generator_layout: Option<GeneratorLayout<'tcx>>,
100 /// Declarations of locals.
102 /// The first local is the return value pointer, followed by `arg_count`
103 /// locals for the function arguments, followed by any user-declared
104 /// variables and temporaries.
105 pub local_decls: LocalDecls<'tcx>,
107 /// Number of arguments this function takes.
109 /// Starting at local 1, `arg_count` locals will be provided by the caller
110 /// and can be assumed to be initialized.
112 /// If this MIR was built for a constant, this will be 0.
113 pub arg_count: usize,
115 /// Names and capture modes of all the closure upvars, assuming
116 /// the first argument is either the closure or a reference to it.
117 pub upvar_decls: Vec<UpvarDecl>,
119 /// Mark an argument local (which must be a tuple) as getting passed as
120 /// its individual components at the LLVM level.
122 /// This is used for the "rust-call" ABI.
123 pub spread_arg: Option<Local>,
125 /// A span representing this MIR, for error reporting
128 /// A cache for various calculations
132 /// where execution begins
133 pub const START_BLOCK: BasicBlock = BasicBlock(0);
135 impl<'tcx> Mir<'tcx> {
136 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
137 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
138 visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope,
139 VisibilityScopeInfo>>,
140 promoted: IndexVec<Promoted, Mir<'tcx>>,
141 yield_ty: Option<Ty<'tcx>>,
142 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
144 upvar_decls: Vec<UpvarDecl>,
147 // We need `arg_count` locals, and one for the return place
148 assert!(local_decls.len() >= arg_count + 1,
149 "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
154 visibility_scope_info,
157 generator_drop: None,
158 generator_layout: None,
164 cache: cache::Cache::new()
169 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
174 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
175 self.cache.invalidate();
176 &mut self.basic_blocks
180 pub fn basic_blocks_and_local_decls_mut(&mut self) -> (
181 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
182 &mut LocalDecls<'tcx>,
184 self.cache.invalidate();
185 (&mut self.basic_blocks, &mut self.local_decls)
189 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
190 self.cache.predecessors(self)
194 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
195 Ref::map(self.predecessors(), |p| &p[bb])
199 pub fn dominators(&self) -> Dominators<BasicBlock> {
204 pub fn local_kind(&self, local: Local) -> LocalKind {
205 let index = local.0 as usize;
207 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
208 "return place should be mutable");
210 LocalKind::ReturnPointer
211 } else if index < self.arg_count + 1 {
213 } else if self.local_decls[local].name.is_some() {
216 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
217 "temp should be mutable");
223 /// Returns an iterator over all temporaries.
225 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
226 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
227 let local = Local::new(index);
228 if self.local_decls[local].is_user_variable {
236 /// Returns an iterator over all user-declared locals.
238 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
239 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
240 let local = Local::new(index);
241 if self.local_decls[local].is_user_variable {
249 /// Returns an iterator over all function arguments.
251 pub fn args_iter(&self) -> impl Iterator<Item=Local> {
252 let arg_count = self.arg_count;
253 (1..arg_count+1).map(Local::new)
256 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
257 /// locals that are neither arguments nor the return place).
259 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
260 let arg_count = self.arg_count;
261 let local_count = self.local_decls.len();
262 (arg_count+1..local_count).map(Local::new)
265 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
266 /// invalidating statement indices in `Location`s.
267 pub fn make_statement_nop(&mut self, location: Location) {
268 let block = &mut self[location.block];
269 debug_assert!(location.statement_index < block.statements.len());
270 block.statements[location.statement_index].make_nop()
273 /// Returns the source info associated with `location`.
274 pub fn source_info(&self, location: Location) -> &SourceInfo {
275 let block = &self[location.block];
276 let stmts = &block.statements;
277 let idx = location.statement_index;
278 if idx < stmts.len() {
279 &stmts[idx].source_info
281 assert!(idx == stmts.len());
282 &block.terminator().source_info
286 /// Return the return type, it always return first element from `local_decls` array
287 pub fn return_ty(&self) -> Ty<'tcx> {
288 self.local_decls[RETURN_PLACE].ty
292 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
293 pub struct VisibilityScopeInfo {
294 /// A NodeId with lint levels equivalent to this scope's lint levels.
295 pub lint_root: ast::NodeId,
296 /// The unsafe block that contains this node.
300 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
303 /// Unsafe because of a PushUnsafeBlock
305 /// Unsafe because of an unsafe fn
307 /// Unsafe because of an `unsafe` block
308 ExplicitUnsafe(ast::NodeId)
311 impl_stable_hash_for!(struct Mir<'tcx> {
314 visibility_scope_info,
327 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
328 type Output = BasicBlockData<'tcx>;
331 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
332 &self.basic_blocks()[index]
336 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
338 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
339 &mut self.basic_blocks_mut()[index]
343 #[derive(Clone, Debug)]
344 pub enum ClearCrossCrate<T> {
349 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
350 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
352 /// Grouped information about the source code origin of a MIR entity.
353 /// Intended to be inspected by diagnostics and debuginfo.
354 /// Most passes can work with it as a whole, within a single function.
355 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
356 pub struct SourceInfo {
357 /// Source span for the AST pertaining to this MIR entity.
360 /// The lexical visibility scope, i.e. which bindings can be seen.
361 pub scope: VisibilityScope
364 ///////////////////////////////////////////////////////////////////////////
365 // Mutability and borrow kinds
367 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
368 pub enum Mutability {
373 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
374 pub enum BorrowKind {
375 /// Data must be immutable and is aliasable.
378 /// Data must be immutable but not aliasable. This kind of borrow
379 /// cannot currently be expressed by the user and is used only in
380 /// implicit closure bindings. It is needed when you the closure
381 /// is borrowing or mutating a mutable referent, e.g.:
383 /// let x: &mut isize = ...;
384 /// let y = || *x += 5;
386 /// If we were to try to translate this closure into a more explicit
387 /// form, we'd encounter an error with the code as written:
389 /// struct Env { x: & &mut isize }
390 /// let x: &mut isize = ...;
391 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
392 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
394 /// This is then illegal because you cannot mutate a `&mut` found
395 /// in an aliasable location. To solve, you'd have to translate with
396 /// an `&mut` borrow:
398 /// struct Env { x: & &mut isize }
399 /// let x: &mut isize = ...;
400 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
401 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
403 /// Now the assignment to `**env.x` is legal, but creating a
404 /// mutable pointer to `x` is not because `x` is not mutable. We
405 /// could fix this by declaring `x` as `let mut x`. This is ok in
406 /// user code, if awkward, but extra weird for closures, since the
407 /// borrow is hidden.
409 /// So we introduce a "unique imm" borrow -- the referent is
410 /// immutable, but not aliasable. This solves the problem. For
411 /// simplicity, we don't give users the way to express this
412 /// borrow, it's just used when translating closures.
415 /// Data is mutable and not aliasable.
417 /// True if this borrow arose from method-call auto-ref
418 /// (i.e. `adjustment::Adjust::Borrow`)
419 allow_two_phase_borrow: bool
424 pub fn allows_two_phase_borrow(&self) -> bool {
426 BorrowKind::Shared | BorrowKind::Unique => false,
427 BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
432 ///////////////////////////////////////////////////////////////////////////
433 // Variables and temps
437 DEBUG_FORMAT = "_{}",
438 const RETURN_PLACE = 0,
441 /// Classifies locals into categories. See `Mir::local_kind`.
442 #[derive(PartialEq, Eq, Debug)]
444 /// User-declared variable binding
446 /// Compiler-introduced temporary
448 /// Function argument
450 /// Location of function's return value
456 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
457 /// argument, or the return place.
458 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
459 pub struct LocalDecl<'tcx> {
460 /// `let mut x` vs `let x`.
462 /// Temporaries and the return place are always mutable.
463 pub mutability: Mutability,
465 /// True if this corresponds to a user-declared local variable.
466 pub is_user_variable: bool,
468 /// True if this is an internal local
470 /// These locals are not based on types in the source code and are only used
471 /// for a few desugarings at the moment.
473 /// The generator transformation will sanity check the locals which are live
474 /// across a suspension point against the type components of the generator
475 /// which type checking knows are live across a suspension point. We need to
476 /// flag drop flags to avoid triggering this check as they are introduced
479 /// Unsafety checking will also ignore dereferences of these locals,
480 /// so they can be used for raw pointers only used in a desugaring.
482 /// This should be sound because the drop flags are fully algebraic, and
483 /// therefore don't affect the OIBIT or outlives properties of the
487 /// Type of this local.
490 /// Name of the local, used in debuginfo and pretty-printing.
492 /// Note that function arguments can also have this set to `Some(_)`
493 /// to generate better debuginfo.
494 pub name: Option<Name>,
496 /// Source info of the local.
497 pub source_info: SourceInfo,
499 /// The *syntactic* visibility scope the local is defined
500 /// in. If the local was defined in a let-statement, this
501 /// is *within* the let-statement, rather than outside
504 /// This is needed because visibility scope of locals within a let-statement
507 /// The reason is that we want the local to be *within* the let-statement
508 /// for lint purposes, but we want the local to be *after* the let-statement
509 /// for names-in-scope purposes.
511 /// That's it, if we have a let-statement like the one in this
515 /// fn foo(x: &str) {
516 /// #[allow(unused_mut)]
517 /// let mut x: u32 = { // <- one unused mut
518 /// let mut y: u32 = x.parse().unwrap();
525 /// Then, from a lint point of view, the declaration of `x: u32`
526 /// (and `y: u32`) are within the `#[allow(unused_mut)]` scope - the
527 /// lint scopes are the same as the AST/HIR nesting.
529 /// However, from a name lookup point of view, the scopes look more like
530 /// as if the let-statements were `match` expressions:
533 /// fn foo(x: &str) {
535 /// match x.parse().unwrap() {
544 /// We care about the name-lookup scopes for debuginfo - if the
545 /// debuginfo instruction pointer is at the call to `x.parse()`, we
546 /// want `x` to refer to `x: &str`, but if it is at the call to
547 /// `drop(x)`, we want it to refer to `x: u32`.
549 /// To allow both uses to work, we need to have more than a single scope
550 /// for a local. We have the `syntactic_scope` represent the
551 /// "syntactic" lint scope (with a variable being under its let
552 /// block) while the source-info scope represents the "local variable"
553 /// scope (where the "rest" of a block is under all prior let-statements).
555 /// The end result looks like this:
559 /// │{ argument x: &str }
561 /// │ │{ #[allow(unused_mut] } // this is actually split into 2 scopes
562 /// │ │ // in practice because I'm lazy.
564 /// │ │← x.syntactic_scope
565 /// │ │← `x.parse().unwrap()`
567 /// │ │ │← y.syntactic_scope
569 /// │ │ │{ let y: u32 }
571 /// │ │ │← y.source_info.scope
574 /// │ │{ let x: u32 }
575 /// │ │← x.source_info.scope
576 /// │ │← `drop(x)` // this accesses `x: u32`
578 pub syntactic_scope: VisibilityScope,
581 impl<'tcx> LocalDecl<'tcx> {
582 /// Create a new `LocalDecl` for a temporary.
584 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
586 mutability: Mutability::Mut,
589 source_info: SourceInfo {
591 scope: ARGUMENT_VISIBILITY_SCOPE
593 syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
595 is_user_variable: false
599 /// Create a new `LocalDecl` for a internal temporary.
601 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
603 mutability: Mutability::Mut,
606 source_info: SourceInfo {
608 scope: ARGUMENT_VISIBILITY_SCOPE
610 syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
612 is_user_variable: false
616 /// Builds a `LocalDecl` for the return place.
618 /// This must be inserted into the `local_decls` list as the first local.
620 pub fn new_return_place(return_ty: Ty, span: Span) -> LocalDecl {
622 mutability: Mutability::Mut,
624 source_info: SourceInfo {
626 scope: ARGUMENT_VISIBILITY_SCOPE
628 syntactic_scope: ARGUMENT_VISIBILITY_SCOPE,
630 name: None, // FIXME maybe we do want some name here?
631 is_user_variable: false
636 /// A closure capture, with its name and mode.
637 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
638 pub struct UpvarDecl {
639 pub debug_name: Name,
641 /// If true, the capture is behind a reference.
644 pub mutability: Mutability,
647 ///////////////////////////////////////////////////////////////////////////
650 newtype_index!(BasicBlock { DEBUG_FORMAT = "bb{}" });
653 pub fn start_location(self) -> Location {
661 ///////////////////////////////////////////////////////////////////////////
662 // BasicBlockData and Terminator
664 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
665 pub struct BasicBlockData<'tcx> {
666 /// List of statements in this block.
667 pub statements: Vec<Statement<'tcx>>,
669 /// Terminator for this block.
671 /// NB. This should generally ONLY be `None` during construction.
672 /// Therefore, you should generally access it via the
673 /// `terminator()` or `terminator_mut()` methods. The only
674 /// exception is that certain passes, such as `simplify_cfg`, swap
675 /// out the terminator temporarily with `None` while they continue
676 /// to recurse over the set of basic blocks.
677 pub terminator: Option<Terminator<'tcx>>,
679 /// If true, this block lies on an unwind path. This is used
680 /// during trans where distinct kinds of basic blocks may be
681 /// generated (particularly for MSVC cleanup). Unwind blocks must
682 /// only branch to other unwind blocks.
683 pub is_cleanup: bool,
686 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
687 pub struct Terminator<'tcx> {
688 pub source_info: SourceInfo,
689 pub kind: TerminatorKind<'tcx>
692 #[derive(Clone, RustcEncodable, RustcDecodable)]
693 pub enum TerminatorKind<'tcx> {
694 /// block should have one successor in the graph; we jump there
699 /// operand evaluates to an integer; jump depending on its value
700 /// to one of the targets, and otherwise fallback to `otherwise`
702 /// discriminant value being tested
703 discr: Operand<'tcx>,
705 /// type of value being tested
708 /// Possible values. The locations to branch to in each case
709 /// are found in the corresponding indices from the `targets` vector.
710 values: Cow<'tcx, [ConstInt]>,
712 /// Possible branch sites. The last element of this vector is used
713 /// for the otherwise branch, so targets.len() == values.len() + 1
715 // This invariant is quite non-obvious and also could be improved.
716 // One way to make this invariant is to have something like this instead:
718 // branches: Vec<(ConstInt, BasicBlock)>,
719 // otherwise: Option<BasicBlock> // exhaustive if None
721 // However we’ve decided to keep this as-is until we figure a case
722 // where some other approach seems to be strictly better than other.
723 targets: Vec<BasicBlock>,
726 /// Indicates that the landing pad is finished and unwinding should
727 /// continue. Emitted by build::scope::diverge_cleanup.
730 /// Indicates that the landing pad is finished and that the process
731 /// should abort. Used to prevent unwinding for foreign items.
734 /// Indicates a normal return. The return place should have
735 /// been filled in by now. This should occur at most once.
738 /// Indicates a terminator that can never be reached.
743 location: Place<'tcx>,
745 unwind: Option<BasicBlock>
748 /// Drop the Place and assign the new value over it. This ensures
749 /// that the assignment to `P` occurs *even if* the destructor for
750 /// place unwinds. Its semantics are best explained by by the
755 /// DropAndReplace(P <- V, goto BB1, unwind BB2)
763 /// Drop(P, goto BB1, unwind BB2)
766 /// // P is now unitialized
770 /// // P is now unitialized -- its dtor panicked
775 location: Place<'tcx>,
776 value: Operand<'tcx>,
778 unwind: Option<BasicBlock>,
781 /// Block ends with a call of a converging function
783 /// The function that’s being called
785 /// Arguments the function is called with.
786 /// These are owned by the callee, which is free to modify them.
787 /// This allows the memory occupied by "by-value" arguments to be
788 /// reused across function calls without duplicating the contents.
789 args: Vec<Operand<'tcx>>,
790 /// Destination for the return value. If some, the call is converging.
791 destination: Option<(Place<'tcx>, BasicBlock)>,
792 /// Cleanups to be done if the call unwinds.
793 cleanup: Option<BasicBlock>
796 /// Jump to the target if the condition has the expected value,
797 /// otherwise panic with a message and a cleanup target.
801 msg: AssertMessage<'tcx>,
803 cleanup: Option<BasicBlock>
808 /// The value to return
809 value: Operand<'tcx>,
810 /// Where to resume to
812 /// Cleanup to be done if the generator is dropped at this suspend point
813 drop: Option<BasicBlock>,
816 /// Indicates the end of the dropping of a generator
819 /// A block where control flow only ever takes one real path, but borrowck
820 /// needs to be more conservative.
822 /// The target normal control flow will take
823 real_target: BasicBlock,
824 /// The list of blocks control flow could conceptually take, but won't
826 imaginary_targets: Vec<BasicBlock>,
828 /// A terminator for blocks that only take one path in reality, but where we
829 /// reserve the right to unwind in borrowck, even if it won't happen in practice.
830 /// This can arise in infinite loops with no function calls for example.
832 /// The target normal control flow will take
833 real_target: BasicBlock,
834 /// The imaginary cleanup block link. This particular path will never be taken
835 /// in practice, but in order to avoid fragility we want to always
836 /// consider it in borrowck. We don't want to accept programs which
837 /// pass borrowck only when panic=abort or some assertions are disabled
838 /// due to release vs. debug mode builds. This needs to be an Option because
839 /// of the remove_noop_landing_pads and no_landing_pads passes
840 unwind: Option<BasicBlock>,
844 impl<'tcx> Terminator<'tcx> {
845 pub fn successors(&self) -> Cow<[BasicBlock]> {
846 self.kind.successors()
849 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
850 self.kind.successors_mut()
853 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
854 self.kind.unwind_mut()
858 impl<'tcx> TerminatorKind<'tcx> {
859 pub fn if_<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
860 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
861 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
862 TerminatorKind::SwitchInt {
864 switch_ty: tcx.types.bool,
865 values: From::from(BOOL_SWITCH_FALSE),
870 pub fn successors(&self) -> Cow<[BasicBlock]> {
871 use self::TerminatorKind::*;
873 Goto { target: ref b } => slice::from_ref(b).into_cow(),
874 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
875 Resume | Abort | GeneratorDrop => (&[]).into_cow(),
876 Return => (&[]).into_cow(),
877 Unreachable => (&[]).into_cow(),
878 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
879 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
880 slice::from_ref(t).into_cow(),
881 Call { destination: None, cleanup: Some(ref c), .. } => slice::from_ref(c).into_cow(),
882 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
883 Yield { resume: t, drop: Some(c), .. } => vec![t, c].into_cow(),
884 Yield { resume: ref t, drop: None, .. } => slice::from_ref(t).into_cow(),
885 DropAndReplace { target, unwind: Some(unwind), .. } |
886 Drop { target, unwind: Some(unwind), .. } => {
887 vec![target, unwind].into_cow()
889 DropAndReplace { ref target, unwind: None, .. } |
890 Drop { ref target, unwind: None, .. } => {
891 slice::from_ref(target).into_cow()
893 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
894 Assert { ref target, .. } => slice::from_ref(target).into_cow(),
895 FalseEdges { ref real_target, ref imaginary_targets } => {
896 let mut s = vec![*real_target];
897 s.extend_from_slice(imaginary_targets);
900 FalseUnwind { real_target: t, unwind: Some(u) } => vec![t, u].into_cow(),
901 FalseUnwind { real_target: ref t, unwind: None } => slice::from_ref(t).into_cow(),
905 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
906 // `Vec<&mut BasicBlock>` would look like in the first place.
907 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
908 use self::TerminatorKind::*;
910 Goto { target: ref mut b } => vec![b],
911 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
912 Resume | Abort | GeneratorDrop => Vec::new(),
913 Return => Vec::new(),
914 Unreachable => Vec::new(),
915 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
916 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
917 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
918 Call { destination: None, cleanup: None, .. } => vec![],
919 Yield { resume: ref mut t, drop: Some(ref mut c), .. } => vec![t, c],
920 Yield { resume: ref mut t, drop: None, .. } => vec![t],
921 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
922 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
923 DropAndReplace { ref mut target, unwind: None, .. } |
924 Drop { ref mut target, unwind: None, .. } => {
927 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
928 Assert { ref mut target, .. } => vec![target],
929 FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
930 let mut s = vec![real_target];
931 s.extend(imaginary_targets.iter_mut());
934 FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => vec![t, u],
935 FalseUnwind { ref mut real_target, unwind: None } => vec![real_target],
939 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
941 TerminatorKind::Goto { .. } |
942 TerminatorKind::Resume |
943 TerminatorKind::Abort |
944 TerminatorKind::Return |
945 TerminatorKind::Unreachable |
946 TerminatorKind::GeneratorDrop |
947 TerminatorKind::Yield { .. } |
948 TerminatorKind::SwitchInt { .. } |
949 TerminatorKind::FalseEdges { .. } => {
952 TerminatorKind::Call { cleanup: ref mut unwind, .. } |
953 TerminatorKind::Assert { cleanup: ref mut unwind, .. } |
954 TerminatorKind::DropAndReplace { ref mut unwind, .. } |
955 TerminatorKind::Drop { ref mut unwind, .. } |
956 TerminatorKind::FalseUnwind { ref mut unwind, .. } => {
963 impl<'tcx> BasicBlockData<'tcx> {
964 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
972 /// Accessor for terminator.
974 /// Terminator may not be None after construction of the basic block is complete. This accessor
975 /// provides a convenience way to reach the terminator.
976 pub fn terminator(&self) -> &Terminator<'tcx> {
977 self.terminator.as_ref().expect("invalid terminator state")
980 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
981 self.terminator.as_mut().expect("invalid terminator state")
984 pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement) -> bool {
985 for s in &mut self.statements {
987 s.kind = StatementKind::Nop;
992 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
993 if index < self.statements.len() {
994 &self.statements[index]
1001 impl<'tcx> Debug for TerminatorKind<'tcx> {
1002 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1003 self.fmt_head(fmt)?;
1004 let successors = self.successors();
1005 let labels = self.fmt_successor_labels();
1006 assert_eq!(successors.len(), labels.len());
1008 match successors.len() {
1011 1 => write!(fmt, " -> {:?}", successors[0]),
1014 write!(fmt, " -> [")?;
1015 for (i, target) in successors.iter().enumerate() {
1019 write!(fmt, "{}: {:?}", labels[i], target)?;
1028 impl<'tcx> TerminatorKind<'tcx> {
1029 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
1030 /// successor basic block, if any. The only information not included is the list of possible
1031 /// successors, which may be rendered differently between the text and the graphviz format.
1032 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
1033 use self::TerminatorKind::*;
1035 Goto { .. } => write!(fmt, "goto"),
1036 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
1037 Return => write!(fmt, "return"),
1038 GeneratorDrop => write!(fmt, "generator_drop"),
1039 Resume => write!(fmt, "resume"),
1040 Abort => write!(fmt, "abort"),
1041 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
1042 Unreachable => write!(fmt, "unreachable"),
1043 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
1044 DropAndReplace { ref location, ref value, .. } =>
1045 write!(fmt, "replace({:?} <- {:?})", location, value),
1046 Call { ref func, ref args, ref destination, .. } => {
1047 if let Some((ref destination, _)) = *destination {
1048 write!(fmt, "{:?} = ", destination)?;
1050 write!(fmt, "{:?}(", func)?;
1051 for (index, arg) in args.iter().enumerate() {
1055 write!(fmt, "{:?}", arg)?;
1059 Assert { ref cond, expected, ref msg, .. } => {
1060 write!(fmt, "assert(")?;
1064 write!(fmt, "{:?}, ", cond)?;
1067 AssertMessage::BoundsCheck { ref len, ref index } => {
1068 write!(fmt, "{:?}, {:?}, {:?}",
1069 "index out of bounds: the len is {} but the index is {}",
1072 AssertMessage::Math(ref err) => {
1073 write!(fmt, "{:?}", err.description())?;
1075 AssertMessage::GeneratorResumedAfterReturn => {
1076 write!(fmt, "{:?}", "generator resumed after completion")?;
1078 AssertMessage::GeneratorResumedAfterPanic => {
1079 write!(fmt, "{:?}", "generator resumed after panicking")?;
1085 FalseEdges { .. } => write!(fmt, "falseEdges"),
1086 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1090 /// Return the list of labels for the edges to the successor basic blocks.
1091 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1092 use self::TerminatorKind::*;
1094 Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
1095 Goto { .. } => vec!["".into()],
1096 SwitchInt { ref values, .. } => {
1099 let mut buf = String::new();
1100 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
1103 .chain(iter::once(String::from("otherwise").into()))
1106 Call { destination: Some(_), cleanup: Some(_), .. } =>
1107 vec!["return".into_cow(), "unwind".into_cow()],
1108 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
1109 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
1110 Call { destination: None, cleanup: None, .. } => vec![],
1111 Yield { drop: Some(_), .. } =>
1112 vec!["resume".into_cow(), "drop".into_cow()],
1113 Yield { drop: None, .. } => vec!["resume".into_cow()],
1114 DropAndReplace { unwind: None, .. } |
1115 Drop { unwind: None, .. } => vec!["return".into_cow()],
1116 DropAndReplace { unwind: Some(_), .. } |
1117 Drop { unwind: Some(_), .. } => {
1118 vec!["return".into_cow(), "unwind".into_cow()]
1120 Assert { cleanup: None, .. } => vec!["".into()],
1122 vec!["success".into_cow(), "unwind".into_cow()],
1123 FalseEdges { ref imaginary_targets, .. } => {
1124 let mut l = vec!["real".into()];
1125 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1128 FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
1129 FalseUnwind { unwind: None, .. } => vec!["real".into()],
1134 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1135 pub enum AssertMessage<'tcx> {
1138 index: Operand<'tcx>
1141 GeneratorResumedAfterReturn,
1142 GeneratorResumedAfterPanic,
1145 ///////////////////////////////////////////////////////////////////////////
1148 #[derive(Clone, RustcEncodable, RustcDecodable)]
1149 pub struct Statement<'tcx> {
1150 pub source_info: SourceInfo,
1151 pub kind: StatementKind<'tcx>,
1154 impl<'tcx> Statement<'tcx> {
1155 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1156 /// invalidating statement indices in `Location`s.
1157 pub fn make_nop(&mut self) {
1158 self.kind = StatementKind::Nop
1162 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1163 pub enum StatementKind<'tcx> {
1164 /// Write the RHS Rvalue to the LHS Place.
1165 Assign(Place<'tcx>, Rvalue<'tcx>),
1167 /// Write the discriminant for a variant to the enum Place.
1168 SetDiscriminant { place: Place<'tcx>, variant_index: usize },
1170 /// Start a live range for the storage of the local.
1173 /// End the current live range for the storage of the local.
1176 /// Execute a piece of inline Assembly.
1178 asm: Box<InlineAsm>,
1179 outputs: Vec<Place<'tcx>>,
1180 inputs: Vec<Operand<'tcx>>
1183 /// Assert the given places to be valid inhabitants of their type. These statements are
1184 /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1185 /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1186 Validate(ValidationOp, Vec<ValidationOperand<'tcx, Place<'tcx>>>),
1188 /// Mark one terminating point of a region scope (i.e. static region).
1189 /// (The starting point(s) arise implicitly from borrows.)
1190 EndRegion(region::Scope),
1192 /// No-op. Useful for deleting instructions without affecting statement indices.
1196 /// The `ValidationOp` describes what happens with each of the operands of a
1197 /// `Validate` statement.
1198 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1199 pub enum ValidationOp {
1200 /// Recursively traverse the place following the type and validate that all type
1201 /// invariants are maintained. Furthermore, acquire exclusive/read-only access to the
1202 /// memory reachable from the place.
1204 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1207 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1208 /// access *until* the given region ends. Then, access will be recovered.
1209 Suspend(region::Scope),
1212 impl Debug for ValidationOp {
1213 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1214 use self::ValidationOp::*;
1216 Acquire => write!(fmt, "Acquire"),
1217 Release => write!(fmt, "Release"),
1218 // (reuse lifetime rendering policy from ppaux.)
1219 Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1224 // This is generic so that it can be reused by miri
1225 #[derive(Clone, RustcEncodable, RustcDecodable)]
1226 pub struct ValidationOperand<'tcx, T> {
1229 pub re: Option<region::Scope>,
1230 pub mutbl: hir::Mutability,
1233 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1234 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1235 write!(fmt, "{:?}: {:?}", self.place, self.ty)?;
1236 if let Some(ce) = self.re {
1237 // (reuse lifetime rendering policy from ppaux.)
1238 write!(fmt, "/{}", ty::ReScope(ce))?;
1240 if let hir::MutImmutable = self.mutbl {
1241 write!(fmt, " (imm)")?;
1247 impl<'tcx> Debug for Statement<'tcx> {
1248 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1249 use self::StatementKind::*;
1251 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1252 // (reuse lifetime rendering policy from ppaux.)
1253 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1254 Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
1255 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1256 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1257 SetDiscriminant { ref place, variant_index } => {
1258 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1260 InlineAsm { ref asm, ref outputs, ref inputs } => {
1261 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1263 Nop => write!(fmt, "nop"),
1268 ///////////////////////////////////////////////////////////////////////////
1271 /// A path to a value; something that can be evaluated without
1272 /// changing or disturbing program state.
1273 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1274 pub enum Place<'tcx> {
1278 /// static or static mut variable
1279 Static(Box<Static<'tcx>>),
1281 /// projection out of a place (access a field, deref a pointer, etc)
1282 Projection(Box<PlaceProjection<'tcx>>),
1285 /// The def-id of a static, along with its normalized type (which is
1286 /// stored to avoid requiring normalization when reading MIR).
1287 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1288 pub struct Static<'tcx> {
1293 impl_stable_hash_for!(struct Static<'tcx> {
1298 /// The `Projection` data structure defines things of the form `B.x`
1299 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1300 /// shared between `Constant` and `Place`. See the aliases
1301 /// `PlaceProjection` etc below.
1302 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1303 pub struct Projection<'tcx, B, V, T> {
1305 pub elem: ProjectionElem<'tcx, V, T>,
1308 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1309 pub enum ProjectionElem<'tcx, V, T> {
1314 /// These indices are generated by slice patterns. Easiest to explain
1318 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1319 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1320 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1321 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1324 /// index or -index (in Python terms), depending on from_end
1326 /// thing being indexed must be at least this long
1328 /// counting backwards from end?
1332 /// These indices are generated by slice patterns.
1334 /// slice[from:-to] in Python terms.
1340 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1341 /// this for ADTs with more than one variant. It may be better to
1342 /// just introduce it always, or always for enums.
1343 Downcast(&'tcx AdtDef, usize),
1346 /// Alias for projections as they appear in places, where the base is a place
1347 /// and the index is a local.
1348 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1350 /// Alias for projections as they appear in places, where the base is a place
1351 /// and the index is a local.
1352 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1354 newtype_index!(Field { DEBUG_FORMAT = "field[{}]" });
1356 impl<'tcx> Place<'tcx> {
1357 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1358 self.elem(ProjectionElem::Field(f, ty))
1361 pub fn deref(self) -> Place<'tcx> {
1362 self.elem(ProjectionElem::Deref)
1365 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1366 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1369 pub fn index(self, index: Local) -> Place<'tcx> {
1370 self.elem(ProjectionElem::Index(index))
1373 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1374 Place::Projection(Box::new(PlaceProjection {
1381 impl<'tcx> Debug for Place<'tcx> {
1382 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1386 Local(id) => write!(fmt, "{:?}", id),
1387 Static(box self::Static { def_id, ty }) =>
1388 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
1389 Projection(ref data) =>
1391 ProjectionElem::Downcast(ref adt_def, index) =>
1392 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
1393 ProjectionElem::Deref =>
1394 write!(fmt, "(*{:?})", data.base),
1395 ProjectionElem::Field(field, ty) =>
1396 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
1397 ProjectionElem::Index(ref index) =>
1398 write!(fmt, "{:?}[{:?}]", data.base, index),
1399 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
1400 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
1401 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
1402 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
1403 ProjectionElem::Subslice { from, to } if to == 0 =>
1404 write!(fmt, "{:?}[{:?}:]", data.base, from),
1405 ProjectionElem::Subslice { from, to } if from == 0 =>
1406 write!(fmt, "{:?}[:-{:?}]", data.base, to),
1407 ProjectionElem::Subslice { from, to } =>
1408 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
1416 ///////////////////////////////////////////////////////////////////////////
1419 newtype_index!(VisibilityScope
1421 DEBUG_FORMAT = "scope[{}]",
1422 const ARGUMENT_VISIBILITY_SCOPE = 0,
1425 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1426 pub struct VisibilityScopeData {
1428 pub parent_scope: Option<VisibilityScope>,
1431 ///////////////////////////////////////////////////////////////////////////
1434 /// These are values that can appear inside an rvalue (or an index
1435 /// place). They are intentionally limited to prevent rvalues from
1436 /// being nested in one another.
1437 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1438 pub enum Operand<'tcx> {
1439 /// Copy: The value must be available for use afterwards.
1441 /// This implies that the type of the place must be `Copy`; this is true
1442 /// by construction during build, but also checked by the MIR type checker.
1444 /// Move: The value (including old borrows of it) will not be used again.
1446 /// Safe for values of all types (modulo future developments towards `?Move`).
1447 /// Correct usage patterns are enforced by the borrow checker for safe code.
1448 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1450 Constant(Box<Constant<'tcx>>),
1453 impl<'tcx> Debug for Operand<'tcx> {
1454 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1455 use self::Operand::*;
1457 Constant(ref a) => write!(fmt, "{:?}", a),
1458 Copy(ref place) => write!(fmt, "{:?}", place),
1459 Move(ref place) => write!(fmt, "move {:?}", place),
1464 impl<'tcx> Operand<'tcx> {
1465 pub fn function_handle<'a>(
1466 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1468 substs: &'tcx Substs<'tcx>,
1471 let ty = tcx.type_of(def_id).subst(tcx, substs);
1472 Operand::Constant(box Constant {
1475 literal: Literal::Value {
1476 value: tcx.mk_const(ty::Const {
1477 val: ConstVal::Function(def_id, substs),
1484 pub fn to_copy(&self) -> Self {
1486 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1487 Operand::Move(ref place) => Operand::Copy(place.clone())
1492 ///////////////////////////////////////////////////////////////////////////
1495 #[derive(Clone, RustcEncodable, RustcDecodable)]
1496 pub enum Rvalue<'tcx> {
1497 /// x (either a move or copy, depending on type of x)
1501 Repeat(Operand<'tcx>, ConstUsize),
1504 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1506 /// length of a [X] or [X;n] value
1509 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1511 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1512 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1514 NullaryOp(NullOp, Ty<'tcx>),
1515 UnaryOp(UnOp, Operand<'tcx>),
1517 /// Read the discriminant of an ADT.
1519 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1520 /// be defined to return, say, a 0) if ADT is not an enum.
1521 Discriminant(Place<'tcx>),
1523 /// Create an aggregate value, like a tuple or struct. This is
1524 /// only needed because we want to distinguish `dest = Foo { x:
1525 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1526 /// that `Foo` has a destructor. These rvalues can be optimized
1527 /// away after type-checking and before lowering.
1528 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1531 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1535 /// Convert unique, zero-sized type for a fn to fn()
1538 /// Convert non capturing closure to fn()
1541 /// Convert safe fn() to unsafe fn()
1544 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1545 /// trans must figure out the details once full monomorphization
1546 /// is known. For example, this could be used to cast from a
1547 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1548 /// (presuming `T: Trait`).
1552 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1553 pub enum AggregateKind<'tcx> {
1554 /// The type is of the element
1558 /// The second field is the variant index. It's equal to 0 for struct
1559 /// and union expressions. The fourth field is
1560 /// active field number and is present only for union expressions
1561 /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
1562 /// active field index would identity the field `c`
1563 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1565 Closure(DefId, ClosureSubsts<'tcx>),
1566 Generator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
1569 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1571 /// The `+` operator (addition)
1573 /// The `-` operator (subtraction)
1575 /// The `*` operator (multiplication)
1577 /// The `/` operator (division)
1579 /// The `%` operator (modulus)
1581 /// The `^` operator (bitwise xor)
1583 /// The `&` operator (bitwise and)
1585 /// The `|` operator (bitwise or)
1587 /// The `<<` operator (shift left)
1589 /// The `>>` operator (shift right)
1591 /// The `==` operator (equality)
1593 /// The `<` operator (less than)
1595 /// The `<=` operator (less than or equal to)
1597 /// The `!=` operator (not equal to)
1599 /// The `>=` operator (greater than or equal to)
1601 /// The `>` operator (greater than)
1603 /// The `ptr.offset` operator
1608 pub fn is_checkable(self) -> bool {
1611 Add | Sub | Mul | Shl | Shr => true,
1617 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1619 /// Return the size of a value of that type
1621 /// Create a new uninitialized box for a value of that type
1625 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1627 /// The `!` operator for logical inversion
1629 /// The `-` operator for negation
1633 impl<'tcx> Debug for Rvalue<'tcx> {
1634 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1635 use self::Rvalue::*;
1638 Use(ref place) => write!(fmt, "{:?}", place),
1639 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1640 Len(ref a) => write!(fmt, "Len({:?})", a),
1641 Cast(ref kind, ref place, ref ty) => {
1642 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
1644 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1645 CheckedBinaryOp(ref op, ref a, ref b) => {
1646 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1648 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1649 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
1650 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1651 Ref(region, borrow_kind, ref place) => {
1652 let kind_str = match borrow_kind {
1653 BorrowKind::Shared => "",
1654 BorrowKind::Mut { .. } | BorrowKind::Unique => "mut ",
1657 // When printing regions, add trailing space if necessary.
1658 let region = if ppaux::verbose() || ppaux::identify_regions() {
1659 let mut region = format!("{}", region);
1660 if region.len() > 0 { region.push(' '); }
1663 // Do not even print 'static
1666 write!(fmt, "&{}{}{:?}", region, kind_str, place)
1669 Aggregate(ref kind, ref places) => {
1670 fn fmt_tuple(fmt: &mut Formatter, places: &[Operand]) -> fmt::Result {
1671 let mut tuple_fmt = fmt.debug_tuple("");
1672 for place in places {
1673 tuple_fmt.field(place);
1679 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
1681 AggregateKind::Tuple => {
1682 match places.len() {
1683 0 => write!(fmt, "()"),
1684 1 => write!(fmt, "({:?},)", places[0]),
1685 _ => fmt_tuple(fmt, places),
1689 AggregateKind::Adt(adt_def, variant, substs, _) => {
1690 let variant_def = &adt_def.variants[variant];
1692 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1694 match variant_def.ctor_kind {
1695 CtorKind::Const => Ok(()),
1696 CtorKind::Fn => fmt_tuple(fmt, places),
1697 CtorKind::Fictive => {
1698 let mut struct_fmt = fmt.debug_struct("");
1699 for (field, place) in variant_def.fields.iter().zip(places) {
1700 struct_fmt.field(&field.name.as_str(), place);
1707 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1708 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1709 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1710 format!("[closure@{:?}]", node_id)
1712 format!("[closure@{:?}]", tcx.hir.span(node_id))
1714 let mut struct_fmt = fmt.debug_struct(&name);
1716 tcx.with_freevars(node_id, |freevars| {
1717 for (freevar, place) in freevars.iter().zip(places) {
1718 let var_name = tcx.hir.name(freevar.var_id());
1719 struct_fmt.field(&var_name.as_str(), place);
1725 write!(fmt, "[closure]")
1729 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
1730 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1731 let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
1732 let mut struct_fmt = fmt.debug_struct(&name);
1734 tcx.with_freevars(node_id, |freevars| {
1735 for (freevar, place) in freevars.iter().zip(places) {
1736 let var_name = tcx.hir.name(freevar.var_id());
1737 struct_fmt.field(&var_name.as_str(), place);
1739 struct_fmt.field("$state", &places[freevars.len()]);
1740 for i in (freevars.len() + 1)..places.len() {
1741 struct_fmt.field(&format!("${}", i - freevars.len() - 1),
1748 write!(fmt, "[generator]")
1757 ///////////////////////////////////////////////////////////////////////////
1760 /// Two constants are equal if they are the same constant. Note that
1761 /// this does not necessarily mean that they are "==" in Rust -- in
1762 /// particular one must be wary of `NaN`!
1764 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1765 pub struct Constant<'tcx> {
1768 pub literal: Literal<'tcx>,
1771 newtype_index!(Promoted { DEBUG_FORMAT = "promoted[{}]" });
1774 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1775 pub enum Literal<'tcx> {
1777 value: &'tcx ty::Const<'tcx>,
1780 // Index into the `promoted` vector of `Mir`.
1785 impl<'tcx> Debug for Constant<'tcx> {
1786 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1787 write!(fmt, "{:?}", self.literal)
1791 impl<'tcx> Debug for Literal<'tcx> {
1792 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1793 use self::Literal::*;
1795 Value { value } => {
1796 write!(fmt, "const ")?;
1797 fmt_const_val(fmt, &value.val)
1799 Promoted { index } => {
1800 write!(fmt, "{:?}", index)
1806 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1807 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1808 use middle::const_val::ConstVal::*;
1810 Float(f) => write!(fmt, "{:?}", f),
1811 Integral(n) => write!(fmt, "{}", n),
1812 Str(s) => write!(fmt, "{:?}", s),
1814 let escaped: String = bytes.data
1816 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1818 write!(fmt, "b\"{}\"", escaped)
1820 Bool(b) => write!(fmt, "{:?}", b),
1821 Char(c) => write!(fmt, "{:?}", c),
1823 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1824 Aggregate(_) => bug!("`ConstVal::{:?}` should not be in MIR", const_val),
1825 Unevaluated(..) => write!(fmt, "{:?}", const_val)
1829 fn item_path_str(def_id: DefId) -> String {
1830 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1833 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1835 type Node = BasicBlock;
1837 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1839 fn start_node(&self) -> Self::Node { START_BLOCK }
1841 fn predecessors<'graph>(&'graph self, node: Self::Node)
1842 -> <Self as GraphPredecessors<'graph>>::Iter
1844 self.predecessors_for(node).clone().into_iter()
1846 fn successors<'graph>(&'graph self, node: Self::Node)
1847 -> <Self as GraphSuccessors<'graph>>::Iter
1849 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1853 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1854 type Item = BasicBlock;
1855 type Iter = IntoIter<BasicBlock>;
1858 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1859 type Item = BasicBlock;
1860 type Iter = IntoIter<BasicBlock>;
1863 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1864 pub struct Location {
1865 /// the location is within this block
1866 pub block: BasicBlock,
1868 /// the location is the start of the statement; or, if `statement_index`
1869 /// == num-statements, then the start of the terminator.
1870 pub statement_index: usize,
1873 impl fmt::Debug for Location {
1874 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1875 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1880 /// Returns the location immediately after this one within the enclosing block.
1882 /// Note that if this location represents a terminator, then the
1883 /// resulting location would be out of bounds and invalid.
1884 pub fn successor_within_block(&self) -> Location {
1885 Location { block: self.block, statement_index: self.statement_index + 1 }
1888 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1889 if self.block == other.block {
1890 self.statement_index <= other.statement_index
1892 dominators.is_dominated_by(other.block, self.block)
1897 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1898 pub enum UnsafetyViolationKind {
1900 ExternStatic(ast::NodeId),
1901 BorrowPacked(ast::NodeId),
1904 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1905 pub struct UnsafetyViolation {
1906 pub source_info: SourceInfo,
1907 pub description: InternedString,
1908 pub kind: UnsafetyViolationKind,
1911 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1912 pub struct UnsafetyCheckResult {
1913 /// Violations that are propagated *upwards* from this function
1914 pub violations: Rc<[UnsafetyViolation]>,
1915 /// unsafe blocks in this function, along with whether they are used. This is
1916 /// used for the "unused_unsafe" lint.
1917 pub unsafe_blocks: Rc<[(ast::NodeId, bool)]>,
1920 /// The layout of generator state
1921 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1922 pub struct GeneratorLayout<'tcx> {
1923 pub fields: Vec<LocalDecl<'tcx>>,
1926 /// After we borrow check a closure, we are left with various
1927 /// requirements that we have inferred between the free regions that
1928 /// appear in the closure's signature or on its field types. These
1929 /// requirements are then verified and proved by the closure's
1930 /// creating function. This struct encodes those requirements.
1932 /// The requirements are listed as being between various
1933 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
1934 /// vids refer to the free regions that appear in the closure (or
1935 /// generator's) type, in order of appearance. (This numbering is
1936 /// actually defined by the `UniversalRegions` struct in the NLL
1937 /// region checker. See for example
1938 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
1939 /// regions in the closure's type "as if" they were erased, so their
1940 /// precise identity is not important, only their position.
1942 /// Example: If type check produces a closure with the closure substs:
1945 /// ClosureSubsts = [
1946 /// i8, // the "closure kind"
1947 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
1948 /// &'a String, // some upvar
1952 /// here, there is one unique free region (`'a`) but it appears
1953 /// twice. We would "renumber" each occurence to a unique vid, as follows:
1956 /// ClosureSubsts = [
1957 /// i8, // the "closure kind"
1958 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
1959 /// &'2 String, // some upvar
1963 /// Now the code might impose a requirement like `'1: '2`. When an
1964 /// instance of the closure is created, the corresponding free regions
1965 /// can be extracted from its type and constrained to have the given
1966 /// outlives relationship.
1968 /// In some cases, we have to record outlives requirements between
1969 /// types and regions as well. In that case, if those types include
1970 /// any regions, those regions are recorded as `ReClosureBound`
1971 /// instances assigned one of these same indices. Those regions will
1972 /// be substituted away by the creator. We use `ReClosureBound` in
1973 /// that case because the regions must be allocated in the global
1974 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
1975 /// internally within the rest of the NLL code).
1976 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1977 pub struct ClosureRegionRequirements<'gcx> {
1978 /// The number of external regions defined on the closure. In our
1979 /// example above, it would be 3 -- one for `'static`, then `'1`
1980 /// and `'2`. This is just used for a sanity check later on, to
1981 /// make sure that the number of regions we see at the callsite
1983 pub num_external_vids: usize,
1985 /// Requirements between the various free regions defined in
1987 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
1990 /// Indicates an outlives constraint between a type or between two
1991 /// free-regions declared on the closure.
1992 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
1993 pub struct ClosureOutlivesRequirement<'tcx> {
1994 // This region or type ...
1995 pub subject: ClosureOutlivesSubject<'tcx>,
1997 // .. must outlive this one.
1998 pub outlived_free_region: ty::RegionVid,
2000 // If not, report an error here.
2001 pub blame_span: Span,
2004 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
2005 /// that must outlive some region.
2006 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
2007 pub enum ClosureOutlivesSubject<'tcx> {
2008 /// Subject is a type, typically a type parameter, but could also
2009 /// be a projection. Indicates a requirement like `T: 'a` being
2010 /// passed to the caller, where the type here is `T`.
2012 /// The type here is guaranteed not to contain any free regions at
2016 /// Subject is a free region from the closure. Indicates a requirement
2017 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
2018 Region(ty::RegionVid),
2022 * TypeFoldable implementations for MIR types
2025 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
2026 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2028 basic_blocks: self.basic_blocks.fold_with(folder),
2029 visibility_scopes: self.visibility_scopes.clone(),
2030 visibility_scope_info: self.visibility_scope_info.clone(),
2031 promoted: self.promoted.fold_with(folder),
2032 yield_ty: self.yield_ty.fold_with(folder),
2033 generator_drop: self.generator_drop.fold_with(folder),
2034 generator_layout: self.generator_layout.fold_with(folder),
2035 local_decls: self.local_decls.fold_with(folder),
2036 arg_count: self.arg_count,
2037 upvar_decls: self.upvar_decls.clone(),
2038 spread_arg: self.spread_arg,
2040 cache: cache::Cache::new()
2044 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2045 self.basic_blocks.visit_with(visitor) ||
2046 self.generator_drop.visit_with(visitor) ||
2047 self.generator_layout.visit_with(visitor) ||
2048 self.yield_ty.visit_with(visitor) ||
2049 self.promoted.visit_with(visitor) ||
2050 self.local_decls.visit_with(visitor)
2054 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
2055 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2057 fields: self.fields.fold_with(folder),
2061 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2062 self.fields.visit_with(visitor)
2066 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
2067 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2069 ty: self.ty.fold_with(folder),
2074 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2075 self.ty.visit_with(visitor)
2079 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
2080 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2082 statements: self.statements.fold_with(folder),
2083 terminator: self.terminator.fold_with(folder),
2084 is_cleanup: self.is_cleanup
2088 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2089 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
2093 impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Place<'tcx>> {
2094 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2096 place: self.place.fold_with(folder),
2097 ty: self.ty.fold_with(folder),
2103 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2104 self.place.visit_with(visitor) || self.ty.visit_with(visitor)
2108 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
2109 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2110 use mir::StatementKind::*;
2112 let kind = match self.kind {
2113 Assign(ref place, ref rval) => Assign(place.fold_with(folder), rval.fold_with(folder)),
2114 SetDiscriminant { ref place, variant_index } => SetDiscriminant {
2115 place: place.fold_with(folder),
2118 StorageLive(ref local) => StorageLive(local.fold_with(folder)),
2119 StorageDead(ref local) => StorageDead(local.fold_with(folder)),
2120 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
2122 outputs: outputs.fold_with(folder),
2123 inputs: inputs.fold_with(folder)
2126 // Note for future: If we want to expose the region scopes
2127 // during the fold, we need to either generalize EndRegion
2128 // to carry `[ty::Region]`, or extend the `TypeFolder`
2129 // trait with a `fn fold_scope`.
2130 EndRegion(ref region_scope) => EndRegion(region_scope.clone()),
2132 Validate(ref op, ref places) =>
2133 Validate(op.clone(),
2134 places.iter().map(|operand| operand.fold_with(folder)).collect()),
2139 source_info: self.source_info,
2144 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2145 use mir::StatementKind::*;
2148 Assign(ref place, ref rval) => { place.visit_with(visitor) || rval.visit_with(visitor) }
2149 SetDiscriminant { ref place, .. } => place.visit_with(visitor),
2150 StorageLive(ref local) |
2151 StorageDead(ref local) => local.visit_with(visitor),
2152 InlineAsm { ref outputs, ref inputs, .. } =>
2153 outputs.visit_with(visitor) || inputs.visit_with(visitor),
2155 // Note for future: If we want to expose the region scopes
2156 // during the visit, we need to either generalize EndRegion
2157 // to carry `[ty::Region]`, or extend the `TypeVisitor`
2158 // trait with a `fn visit_scope`.
2159 EndRegion(ref _scope) => false,
2161 Validate(ref _op, ref places) =>
2162 places.iter().any(|ty_and_place| ty_and_place.visit_with(visitor)),
2169 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2170 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2171 use mir::TerminatorKind::*;
2173 let kind = match self.kind {
2174 Goto { target } => Goto { target: target },
2175 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2176 discr: discr.fold_with(folder),
2177 switch_ty: switch_ty.fold_with(folder),
2178 values: values.clone(),
2179 targets: targets.clone()
2181 Drop { ref location, target, unwind } => Drop {
2182 location: location.fold_with(folder),
2186 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2187 location: location.fold_with(folder),
2188 value: value.fold_with(folder),
2192 Yield { ref value, resume, drop } => Yield {
2193 value: value.fold_with(folder),
2197 Call { ref func, ref args, ref destination, cleanup } => {
2198 let dest = destination.as_ref().map(|&(ref loc, dest)| {
2199 (loc.fold_with(folder), dest)
2203 func: func.fold_with(folder),
2204 args: args.fold_with(folder),
2209 Assert { ref cond, expected, ref msg, target, cleanup } => {
2210 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2211 AssertMessage::BoundsCheck {
2212 len: len.fold_with(folder),
2213 index: index.fold_with(folder),
2219 cond: cond.fold_with(folder),
2226 GeneratorDrop => GeneratorDrop,
2230 Unreachable => Unreachable,
2231 FalseEdges { real_target, ref imaginary_targets } =>
2232 FalseEdges { real_target, imaginary_targets: imaginary_targets.clone() },
2233 FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
2236 source_info: self.source_info,
2241 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2242 use mir::TerminatorKind::*;
2245 SwitchInt { ref discr, switch_ty, .. } =>
2246 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
2247 Drop { ref location, ..} => location.visit_with(visitor),
2248 DropAndReplace { ref location, ref value, ..} =>
2249 location.visit_with(visitor) || value.visit_with(visitor),
2250 Yield { ref value, ..} =>
2251 value.visit_with(visitor),
2252 Call { ref func, ref args, ref destination, .. } => {
2253 let dest = if let Some((ref loc, _)) = *destination {
2254 loc.visit_with(visitor)
2256 dest || func.visit_with(visitor) || args.visit_with(visitor)
2258 Assert { ref cond, ref msg, .. } => {
2259 if cond.visit_with(visitor) {
2260 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2261 len.visit_with(visitor) || index.visit_with(visitor)
2276 FalseUnwind { .. } => false
2281 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
2282 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2284 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
2289 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2290 if let &Place::Projection(ref p) = self {
2291 p.visit_with(visitor)
2298 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
2299 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2302 Use(ref op) => Use(op.fold_with(folder)),
2303 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
2304 Ref(region, bk, ref place) =>
2305 Ref(region.fold_with(folder), bk, place.fold_with(folder)),
2306 Len(ref place) => Len(place.fold_with(folder)),
2307 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
2308 BinaryOp(op, ref rhs, ref lhs) =>
2309 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2310 CheckedBinaryOp(op, ref rhs, ref lhs) =>
2311 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2312 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
2313 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
2314 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
2315 Aggregate(ref kind, ref fields) => {
2316 let kind = box match **kind {
2317 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
2318 AggregateKind::Tuple => AggregateKind::Tuple,
2319 AggregateKind::Adt(def, v, substs, n) =>
2320 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
2321 AggregateKind::Closure(id, substs) =>
2322 AggregateKind::Closure(id, substs.fold_with(folder)),
2323 AggregateKind::Generator(id, substs, interior) =>
2324 AggregateKind::Generator(id,
2325 substs.fold_with(folder),
2326 interior.fold_with(folder)),
2328 Aggregate(kind, fields.fold_with(folder))
2333 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2336 Use(ref op) => op.visit_with(visitor),
2337 Repeat(ref op, _) => op.visit_with(visitor),
2338 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
2339 Len(ref place) => place.visit_with(visitor),
2340 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
2341 BinaryOp(_, ref rhs, ref lhs) |
2342 CheckedBinaryOp(_, ref rhs, ref lhs) =>
2343 rhs.visit_with(visitor) || lhs.visit_with(visitor),
2344 UnaryOp(_, ref val) => val.visit_with(visitor),
2345 Discriminant(ref place) => place.visit_with(visitor),
2346 NullaryOp(_, ty) => ty.visit_with(visitor),
2347 Aggregate(ref kind, ref fields) => {
2349 AggregateKind::Array(ty) => ty.visit_with(visitor),
2350 AggregateKind::Tuple => false,
2351 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
2352 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
2353 AggregateKind::Generator(_, substs, interior) => substs.visit_with(visitor) ||
2354 interior.visit_with(visitor),
2355 }) || fields.visit_with(visitor)
2361 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
2362 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2364 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
2365 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
2366 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
2370 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2372 Operand::Copy(ref place) |
2373 Operand::Move(ref place) => place.visit_with(visitor),
2374 Operand::Constant(ref c) => c.visit_with(visitor)
2379 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
2380 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>
2382 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2383 use mir::ProjectionElem::*;
2385 let base = self.base.fold_with(folder);
2386 let elem = match self.elem {
2388 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
2389 Index(ref v) => Index(v.fold_with(folder)),
2390 ref elem => elem.clone()
2399 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2400 use mir::ProjectionElem::*;
2402 self.base.visit_with(visitor) ||
2404 Field(_, ref ty) => ty.visit_with(visitor),
2405 Index(ref v) => v.visit_with(visitor),
2411 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
2412 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2414 span: self.span.clone(),
2415 ty: self.ty.fold_with(folder),
2416 literal: self.literal.fold_with(folder)
2419 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2420 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
2424 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
2425 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2427 Literal::Value { value } => Literal::Value {
2428 value: value.fold_with(folder)
2430 Literal::Promoted { index } => Literal::Promoted { index }
2433 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2435 Literal::Value { value } => value.visit_with(visitor),
2436 Literal::Promoted { .. } => false