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 README](README.md) for details.
13 use graphviz::IntoCow;
14 use middle::const_val::ConstVal;
16 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
17 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
18 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
19 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
20 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
21 use rustc_serialize as serialize;
22 use hir::def::CtorKind;
23 use hir::def_id::DefId;
24 use mir::visit::MirVisitable;
25 use ty::subst::{Subst, Substs};
26 use ty::{self, AdtDef, ClosureSubsts, Region, Ty, TyCtxt, GeneratorInterior};
27 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
30 use hir::{self, InlineAsm};
32 use std::borrow::{Cow};
34 use std::fmt::{self, Debug, Formatter, Write};
36 use std::ops::{Index, IndexMut};
38 use std::vec::IntoIter;
39 use syntax::ast::{self, Name};
40 use syntax::symbol::InternedString;
51 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
53 pub trait HasLocalDecls<'tcx> {
54 fn local_decls(&self) -> &LocalDecls<'tcx>;
57 impl<'tcx> HasLocalDecls<'tcx> for LocalDecls<'tcx> {
58 fn local_decls(&self) -> &LocalDecls<'tcx> {
63 impl<'tcx> HasLocalDecls<'tcx> for Mir<'tcx> {
64 fn local_decls(&self) -> &LocalDecls<'tcx> {
69 /// Lowered representation of a single function.
70 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
71 pub struct Mir<'tcx> {
72 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
73 /// that indexes into this vector.
74 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
76 /// List of visibility (lexical) scopes; these are referenced by statements
77 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
78 pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
80 /// Crate-local information for each visibility scope, that can't (and
81 /// needn't) be tracked across crates.
82 pub visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope, VisibilityScopeInfo>>,
84 /// Rvalues promoted from this function, such as borrows of constants.
85 /// Each of them is the Mir of a constant with the fn's type parameters
86 /// in scope, but a separate set of locals.
87 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
89 /// Yield type of the function, if it is a generator.
90 pub yield_ty: Option<Ty<'tcx>>,
92 /// Generator drop glue
93 pub generator_drop: Option<Box<Mir<'tcx>>>,
95 /// The layout of a generator. Produced by the state transformation.
96 pub generator_layout: Option<GeneratorLayout<'tcx>>,
98 /// Declarations of locals.
100 /// The first local is the return value pointer, followed by `arg_count`
101 /// locals for the function arguments, followed by any user-declared
102 /// variables and temporaries.
103 pub local_decls: LocalDecls<'tcx>,
105 /// Number of arguments this function takes.
107 /// Starting at local 1, `arg_count` locals will be provided by the caller
108 /// and can be assumed to be initialized.
110 /// If this MIR was built for a constant, this will be 0.
111 pub arg_count: usize,
113 /// Names and capture modes of all the closure upvars, assuming
114 /// the first argument is either the closure or a reference to it.
115 pub upvar_decls: Vec<UpvarDecl>,
117 /// Mark an argument local (which must be a tuple) as getting passed as
118 /// its individual components at the LLVM level.
120 /// This is used for the "rust-call" ABI.
121 pub spread_arg: Option<Local>,
123 /// A span representing this MIR, for error reporting
126 /// A cache for various calculations
130 /// where execution begins
131 pub const START_BLOCK: BasicBlock = BasicBlock(0);
133 impl<'tcx> Mir<'tcx> {
134 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
135 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
136 visibility_scope_info: ClearCrossCrate<IndexVec<VisibilityScope,
137 VisibilityScopeInfo>>,
138 promoted: IndexVec<Promoted, Mir<'tcx>>,
139 yield_ty: Option<Ty<'tcx>>,
140 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
142 upvar_decls: Vec<UpvarDecl>,
145 // We need `arg_count` locals, and one for the return place
146 assert!(local_decls.len() >= arg_count + 1,
147 "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
152 visibility_scope_info,
155 generator_drop: None,
156 generator_layout: None,
162 cache: cache::Cache::new()
167 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
172 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
173 self.cache.invalidate();
174 &mut self.basic_blocks
178 pub fn basic_blocks_and_local_decls_mut(&mut self) -> (
179 &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
180 &mut LocalDecls<'tcx>,
182 self.cache.invalidate();
183 (&mut self.basic_blocks, &mut self.local_decls)
187 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
188 self.cache.predecessors(self)
192 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
193 Ref::map(self.predecessors(), |p| &p[bb])
197 pub fn dominators(&self) -> Dominators<BasicBlock> {
202 pub fn local_kind(&self, local: Local) -> LocalKind {
203 let index = local.0 as usize;
205 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
206 "return place should be mutable");
208 LocalKind::ReturnPointer
209 } else if index < self.arg_count + 1 {
211 } else if self.local_decls[local].name.is_some() {
214 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
215 "temp should be mutable");
221 /// Returns an iterator over all temporaries.
223 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
224 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
225 let local = Local::new(index);
226 if self.local_decls[local].is_user_variable {
234 /// Returns an iterator over all user-declared locals.
236 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
237 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
238 let local = Local::new(index);
239 if self.local_decls[local].is_user_variable {
247 /// Returns an iterator over all function arguments.
249 pub fn args_iter(&self) -> impl Iterator<Item=Local> {
250 let arg_count = self.arg_count;
251 (1..arg_count+1).map(Local::new)
254 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
255 /// locals that are neither arguments nor the return place).
257 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
258 let arg_count = self.arg_count;
259 let local_count = self.local_decls.len();
260 (arg_count+1..local_count).map(Local::new)
263 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
264 /// invalidating statement indices in `Location`s.
265 pub fn make_statement_nop(&mut self, location: Location) {
266 let block = &mut self[location.block];
267 debug_assert!(location.statement_index < block.statements.len());
268 block.statements[location.statement_index].make_nop()
271 /// Returns the source info associated with `location`.
272 pub fn source_info(&self, location: Location) -> &SourceInfo {
273 let block = &self[location.block];
274 let stmts = &block.statements;
275 let idx = location.statement_index;
276 if idx < stmts.len() {
277 &stmts[idx].source_info
279 assert!(idx == stmts.len());
280 &block.terminator().source_info
284 /// Return the return type, it always return first element from `local_decls` array
285 pub fn return_ty(&self) -> Ty<'tcx> {
286 self.local_decls[RETURN_PLACE].ty
290 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
291 pub struct VisibilityScopeInfo {
292 /// A NodeId with lint levels equivalent to this scope's lint levels.
293 pub lint_root: ast::NodeId,
294 /// The unsafe block that contains this node.
298 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
301 /// Unsafe because of a PushUnsafeBlock
303 /// Unsafe because of an unsafe fn
305 /// Unsafe because of an `unsafe` block
306 ExplicitUnsafe(ast::NodeId)
309 impl_stable_hash_for!(struct Mir<'tcx> {
312 visibility_scope_info,
325 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
326 type Output = BasicBlockData<'tcx>;
329 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
330 &self.basic_blocks()[index]
334 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
336 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
337 &mut self.basic_blocks_mut()[index]
341 #[derive(Clone, Debug)]
342 pub enum ClearCrossCrate<T> {
347 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
348 impl<T: serialize::Decodable> serialize::UseSpecializedDecodable for ClearCrossCrate<T> {}
350 /// Grouped information about the source code origin of a MIR entity.
351 /// Intended to be inspected by diagnostics and debuginfo.
352 /// Most passes can work with it as a whole, within a single function.
353 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
354 pub struct SourceInfo {
355 /// Source span for the AST pertaining to this MIR entity.
358 /// The lexical visibility scope, i.e. which bindings can be seen.
359 pub scope: VisibilityScope
362 ///////////////////////////////////////////////////////////////////////////
363 // Mutability and borrow kinds
365 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
366 pub enum Mutability {
371 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
372 pub enum BorrowKind {
373 /// Data must be immutable and is aliasable.
376 /// Data must be immutable but not aliasable. This kind of borrow
377 /// cannot currently be expressed by the user and is used only in
378 /// implicit closure bindings. It is needed when you the closure
379 /// is borrowing or mutating a mutable referent, e.g.:
381 /// let x: &mut isize = ...;
382 /// let y = || *x += 5;
384 /// If we were to try to translate this closure into a more explicit
385 /// form, we'd encounter an error with the code as written:
387 /// struct Env { x: & &mut isize }
388 /// let x: &mut isize = ...;
389 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
390 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
392 /// This is then illegal because you cannot mutate a `&mut` found
393 /// in an aliasable location. To solve, you'd have to translate with
394 /// an `&mut` borrow:
396 /// struct Env { x: & &mut isize }
397 /// let x: &mut isize = ...;
398 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
399 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
401 /// Now the assignment to `**env.x` is legal, but creating a
402 /// mutable pointer to `x` is not because `x` is not mutable. We
403 /// could fix this by declaring `x` as `let mut x`. This is ok in
404 /// user code, if awkward, but extra weird for closures, since the
405 /// borrow is hidden.
407 /// So we introduce a "unique imm" borrow -- the referent is
408 /// immutable, but not aliasable. This solves the problem. For
409 /// simplicity, we don't give users the way to express this
410 /// borrow, it's just used when translating closures.
413 /// Data is mutable and not aliasable.
417 ///////////////////////////////////////////////////////////////////////////
418 // Variables and temps
422 DEBUG_FORMAT = "_{}",
423 const RETURN_PLACE = 0,
426 /// Classifies locals into categories. See `Mir::local_kind`.
427 #[derive(PartialEq, Eq, Debug)]
429 /// User-declared variable binding
431 /// Compiler-introduced temporary
433 /// Function argument
435 /// Location of function's return value
441 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
442 /// argument, or the return place.
443 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
444 pub struct LocalDecl<'tcx> {
445 /// `let mut x` vs `let x`.
447 /// Temporaries and the return place are always mutable.
448 pub mutability: Mutability,
450 /// True if this corresponds to a user-declared local variable.
451 pub is_user_variable: bool,
453 /// True if this is an internal local
455 /// These locals are not based on types in the source code and are only used
456 /// for a few desugarings at the moment.
458 /// The generator transformation will sanity check the locals which are live
459 /// across a suspension point against the type components of the generator
460 /// which type checking knows are live across a suspension point. We need to
461 /// flag drop flags to avoid triggering this check as they are introduced
464 /// Unsafety checking will also ignore dereferences of these locals,
465 /// so they can be used for raw pointers only used in a desugaring.
467 /// This should be sound because the drop flags are fully algebraic, and
468 /// therefore don't affect the OIBIT or outlives properties of the
472 /// Type of this local.
475 /// Name of the local, used in debuginfo and pretty-printing.
477 /// Note that function arguments can also have this set to `Some(_)`
478 /// to generate better debuginfo.
479 pub name: Option<Name>,
481 /// Source info of the local.
482 pub source_info: SourceInfo,
484 /// The *lexical* visibility scope the local is defined
485 /// in. If the local was defined in a let-statement, this
486 /// is *within* the let-statement, rather than outside
488 pub lexical_scope: VisibilityScope,
491 impl<'tcx> LocalDecl<'tcx> {
492 /// Create a new `LocalDecl` for a temporary.
494 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
496 mutability: Mutability::Mut,
499 source_info: SourceInfo {
501 scope: ARGUMENT_VISIBILITY_SCOPE
503 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
505 is_user_variable: false
509 /// Create a new `LocalDecl` for a internal temporary.
511 pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
513 mutability: Mutability::Mut,
516 source_info: SourceInfo {
518 scope: ARGUMENT_VISIBILITY_SCOPE
520 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
522 is_user_variable: false
526 /// Builds a `LocalDecl` for the return place.
528 /// This must be inserted into the `local_decls` list as the first local.
530 pub fn new_return_place(return_ty: Ty, span: Span) -> LocalDecl {
532 mutability: Mutability::Mut,
534 source_info: SourceInfo {
536 scope: ARGUMENT_VISIBILITY_SCOPE
538 lexical_scope: ARGUMENT_VISIBILITY_SCOPE,
540 name: None, // FIXME maybe we do want some name here?
541 is_user_variable: false
546 /// A closure capture, with its name and mode.
547 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
548 pub struct UpvarDecl {
549 pub debug_name: Name,
551 /// If true, the capture is behind a reference.
554 pub mutability: Mutability,
557 ///////////////////////////////////////////////////////////////////////////
560 newtype_index!(BasicBlock { DEBUG_FORMAT = "bb{}" });
563 pub fn start_location(self) -> Location {
571 ///////////////////////////////////////////////////////////////////////////
572 // BasicBlockData and Terminator
574 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
575 pub struct BasicBlockData<'tcx> {
576 /// List of statements in this block.
577 pub statements: Vec<Statement<'tcx>>,
579 /// Terminator for this block.
581 /// NB. This should generally ONLY be `None` during construction.
582 /// Therefore, you should generally access it via the
583 /// `terminator()` or `terminator_mut()` methods. The only
584 /// exception is that certain passes, such as `simplify_cfg`, swap
585 /// out the terminator temporarily with `None` while they continue
586 /// to recurse over the set of basic blocks.
587 pub terminator: Option<Terminator<'tcx>>,
589 /// If true, this block lies on an unwind path. This is used
590 /// during trans where distinct kinds of basic blocks may be
591 /// generated (particularly for MSVC cleanup). Unwind blocks must
592 /// only branch to other unwind blocks.
593 pub is_cleanup: bool,
596 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
597 pub struct Terminator<'tcx> {
598 pub source_info: SourceInfo,
599 pub kind: TerminatorKind<'tcx>
602 #[derive(Clone, RustcEncodable, RustcDecodable)]
603 pub enum TerminatorKind<'tcx> {
604 /// block should have one successor in the graph; we jump there
609 /// operand evaluates to an integer; jump depending on its value
610 /// to one of the targets, and otherwise fallback to `otherwise`
612 /// discriminant value being tested
613 discr: Operand<'tcx>,
615 /// type of value being tested
618 /// Possible values. The locations to branch to in each case
619 /// are found in the corresponding indices from the `targets` vector.
620 values: Cow<'tcx, [ConstInt]>,
622 /// Possible branch sites. The last element of this vector is used
623 /// for the otherwise branch, so targets.len() == values.len() + 1
625 // This invariant is quite non-obvious and also could be improved.
626 // One way to make this invariant is to have something like this instead:
628 // branches: Vec<(ConstInt, BasicBlock)>,
629 // otherwise: Option<BasicBlock> // exhaustive if None
631 // However we’ve decided to keep this as-is until we figure a case
632 // where some other approach seems to be strictly better than other.
633 targets: Vec<BasicBlock>,
636 /// Indicates that the landing pad is finished and unwinding should
637 /// continue. Emitted by build::scope::diverge_cleanup.
640 /// Indicates a normal return. The return place should have
641 /// been filled in by now. This should occur at most once.
644 /// Indicates a terminator that can never be reached.
649 location: Place<'tcx>,
651 unwind: Option<BasicBlock>
654 /// Drop the Place and assign the new value over it. This ensures
655 /// that the assignment to LV occurs *even if* the destructor for
656 /// place unwinds. Its semantics are best explained by by the
661 /// DropAndReplace(LV <- RV, goto BB1, unwind BB2)
669 /// Drop(LV, goto BB1, unwind BB2)
672 /// // LV is now unitialized
676 /// // LV is now unitialized -- its dtor panicked
681 location: Place<'tcx>,
682 value: Operand<'tcx>,
684 unwind: Option<BasicBlock>,
687 /// Block ends with a call of a converging function
689 /// The function that’s being called
691 /// Arguments the function is called with.
692 /// These are owned by the callee, which is free to modify them.
693 /// This allows the memory occupied by "by-value" arguments to be
694 /// reused across function calls without duplicating the contents.
695 args: Vec<Operand<'tcx>>,
696 /// Destination for the return value. If some, the call is converging.
697 destination: Option<(Place<'tcx>, BasicBlock)>,
698 /// Cleanups to be done if the call unwinds.
699 cleanup: Option<BasicBlock>
702 /// Jump to the target if the condition has the expected value,
703 /// otherwise panic with a message and a cleanup target.
707 msg: AssertMessage<'tcx>,
709 cleanup: Option<BasicBlock>
714 /// The value to return
715 value: Operand<'tcx>,
716 /// Where to resume to
718 /// Cleanup to be done if the generator is dropped at this suspend point
719 drop: Option<BasicBlock>,
722 /// Indicates the end of the dropping of a generator
726 real_target: BasicBlock,
727 imaginary_targets: Vec<BasicBlock>
731 impl<'tcx> Terminator<'tcx> {
732 pub fn successors(&self) -> Cow<[BasicBlock]> {
733 self.kind.successors()
736 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
737 self.kind.successors_mut()
740 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
741 self.kind.unwind_mut()
745 impl<'tcx> TerminatorKind<'tcx> {
746 pub fn if_<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
747 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
748 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
749 TerminatorKind::SwitchInt {
751 switch_ty: tcx.types.bool,
752 values: From::from(BOOL_SWITCH_FALSE),
757 pub fn successors(&self) -> Cow<[BasicBlock]> {
758 use self::TerminatorKind::*;
760 Goto { target: ref b } => slice::from_ref(b).into_cow(),
761 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
762 Resume | GeneratorDrop => (&[]).into_cow(),
763 Return => (&[]).into_cow(),
764 Unreachable => (&[]).into_cow(),
765 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
766 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
767 slice::from_ref(t).into_cow(),
768 Call { destination: None, cleanup: Some(ref c), .. } => slice::from_ref(c).into_cow(),
769 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
770 Yield { resume: t, drop: Some(c), .. } => vec![t, c].into_cow(),
771 Yield { resume: ref t, drop: None, .. } => slice::from_ref(t).into_cow(),
772 DropAndReplace { target, unwind: Some(unwind), .. } |
773 Drop { target, unwind: Some(unwind), .. } => {
774 vec![target, unwind].into_cow()
776 DropAndReplace { ref target, unwind: None, .. } |
777 Drop { ref target, unwind: None, .. } => {
778 slice::from_ref(target).into_cow()
780 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
781 Assert { ref target, .. } => slice::from_ref(target).into_cow(),
782 FalseEdges { ref real_target, ref imaginary_targets } => {
783 let mut s = vec![*real_target];
784 s.extend_from_slice(imaginary_targets);
790 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
791 // `Vec<&mut BasicBlock>` would look like in the first place.
792 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
793 use self::TerminatorKind::*;
795 Goto { target: ref mut b } => vec![b],
796 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
797 Resume | GeneratorDrop => Vec::new(),
798 Return => Vec::new(),
799 Unreachable => Vec::new(),
800 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
801 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
802 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
803 Call { destination: None, cleanup: None, .. } => vec![],
804 Yield { resume: ref mut t, drop: Some(ref mut c), .. } => vec![t, c],
805 Yield { resume: ref mut t, drop: None, .. } => vec![t],
806 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
807 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
808 DropAndReplace { ref mut target, unwind: None, .. } |
809 Drop { ref mut target, unwind: None, .. } => {
812 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
813 Assert { ref mut target, .. } => vec![target],
814 FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
815 let mut s = vec![real_target];
816 s.extend(imaginary_targets.iter_mut());
822 pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
824 TerminatorKind::Goto { .. } |
825 TerminatorKind::Resume |
826 TerminatorKind::Return |
827 TerminatorKind::Unreachable |
828 TerminatorKind::GeneratorDrop |
829 TerminatorKind::Yield { .. } |
830 TerminatorKind::SwitchInt { .. } |
831 TerminatorKind::FalseEdges { .. } => {
834 TerminatorKind::Call { cleanup: ref mut unwind, .. } |
835 TerminatorKind::Assert { cleanup: ref mut unwind, .. } |
836 TerminatorKind::DropAndReplace { ref mut unwind, .. } |
837 TerminatorKind::Drop { ref mut unwind, .. } => {
844 impl<'tcx> BasicBlockData<'tcx> {
845 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
853 /// Accessor for terminator.
855 /// Terminator may not be None after construction of the basic block is complete. This accessor
856 /// provides a convenience way to reach the terminator.
857 pub fn terminator(&self) -> &Terminator<'tcx> {
858 self.terminator.as_ref().expect("invalid terminator state")
861 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
862 self.terminator.as_mut().expect("invalid terminator state")
865 pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement) -> bool {
866 for s in &mut self.statements {
868 s.kind = StatementKind::Nop;
873 pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> {
874 if index < self.statements.len() {
875 &self.statements[index]
882 impl<'tcx> Debug for TerminatorKind<'tcx> {
883 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
885 let successors = self.successors();
886 let labels = self.fmt_successor_labels();
887 assert_eq!(successors.len(), labels.len());
889 match successors.len() {
892 1 => write!(fmt, " -> {:?}", successors[0]),
895 write!(fmt, " -> [")?;
896 for (i, target) in successors.iter().enumerate() {
900 write!(fmt, "{}: {:?}", labels[i], target)?;
909 impl<'tcx> TerminatorKind<'tcx> {
910 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
911 /// successor basic block, if any. The only information not included is the list of possible
912 /// successors, which may be rendered differently between the text and the graphviz format.
913 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
914 use self::TerminatorKind::*;
916 Goto { .. } => write!(fmt, "goto"),
917 SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
918 Return => write!(fmt, "return"),
919 GeneratorDrop => write!(fmt, "generator_drop"),
920 Resume => write!(fmt, "resume"),
921 Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
922 Unreachable => write!(fmt, "unreachable"),
923 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
924 DropAndReplace { ref location, ref value, .. } =>
925 write!(fmt, "replace({:?} <- {:?})", location, value),
926 Call { ref func, ref args, ref destination, .. } => {
927 if let Some((ref destination, _)) = *destination {
928 write!(fmt, "{:?} = ", destination)?;
930 write!(fmt, "{:?}(", func)?;
931 for (index, arg) in args.iter().enumerate() {
935 write!(fmt, "{:?}", arg)?;
939 Assert { ref cond, expected, ref msg, .. } => {
940 write!(fmt, "assert(")?;
944 write!(fmt, "{:?}, ", cond)?;
947 AssertMessage::BoundsCheck { ref len, ref index } => {
948 write!(fmt, "{:?}, {:?}, {:?}",
949 "index out of bounds: the len is {} but the index is {}",
952 AssertMessage::Math(ref err) => {
953 write!(fmt, "{:?}", err.description())?;
955 AssertMessage::GeneratorResumedAfterReturn => {
956 write!(fmt, "{:?}", "generator resumed after completion")?;
958 AssertMessage::GeneratorResumedAfterPanic => {
959 write!(fmt, "{:?}", "generator resumed after panicking")?;
965 FalseEdges { .. } => write!(fmt, "falseEdges")
969 /// Return the list of labels for the edges to the successor basic blocks.
970 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
971 use self::TerminatorKind::*;
973 Return | Resume | Unreachable | GeneratorDrop => vec![],
974 Goto { .. } => vec!["".into()],
975 SwitchInt { ref values, .. } => {
978 let mut buf = String::new();
979 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
982 .chain(iter::once(String::from("otherwise").into()))
985 Call { destination: Some(_), cleanup: Some(_), .. } =>
986 vec!["return".into_cow(), "unwind".into_cow()],
987 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
988 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
989 Call { destination: None, cleanup: None, .. } => vec![],
990 Yield { drop: Some(_), .. } =>
991 vec!["resume".into_cow(), "drop".into_cow()],
992 Yield { drop: None, .. } => vec!["resume".into_cow()],
993 DropAndReplace { unwind: None, .. } |
994 Drop { unwind: None, .. } => vec!["return".into_cow()],
995 DropAndReplace { unwind: Some(_), .. } |
996 Drop { unwind: Some(_), .. } => {
997 vec!["return".into_cow(), "unwind".into_cow()]
999 Assert { cleanup: None, .. } => vec!["".into()],
1001 vec!["success".into_cow(), "unwind".into_cow()],
1002 FalseEdges { ref imaginary_targets, .. } => {
1003 let mut l = vec!["real".into()];
1004 l.resize(imaginary_targets.len() + 1, "imaginary".into());
1011 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1012 pub enum AssertMessage<'tcx> {
1015 index: Operand<'tcx>
1018 GeneratorResumedAfterReturn,
1019 GeneratorResumedAfterPanic,
1022 ///////////////////////////////////////////////////////////////////////////
1025 #[derive(Clone, RustcEncodable, RustcDecodable)]
1026 pub struct Statement<'tcx> {
1027 pub source_info: SourceInfo,
1028 pub kind: StatementKind<'tcx>,
1031 impl<'tcx> Statement<'tcx> {
1032 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
1033 /// invalidating statement indices in `Location`s.
1034 pub fn make_nop(&mut self) {
1035 self.kind = StatementKind::Nop
1039 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1040 pub enum StatementKind<'tcx> {
1041 /// Write the RHS Rvalue to the LHS Place.
1042 Assign(Place<'tcx>, Rvalue<'tcx>),
1044 /// Write the discriminant for a variant to the enum Place.
1045 SetDiscriminant { place: Place<'tcx>, variant_index: usize },
1047 /// Start a live range for the storage of the local.
1050 /// End the current live range for the storage of the local.
1053 /// Execute a piece of inline Assembly.
1055 asm: Box<InlineAsm>,
1056 outputs: Vec<Place<'tcx>>,
1057 inputs: Vec<Operand<'tcx>>
1060 /// Assert the given places to be valid inhabitants of their type. These statements are
1061 /// currently only interpreted by miri and only generated when "-Z mir-emit-validate" is passed.
1062 /// See <https://internals.rust-lang.org/t/types-as-contracts/5562/73> for more details.
1063 Validate(ValidationOp, Vec<ValidationOperand<'tcx, Place<'tcx>>>),
1065 /// Mark one terminating point of a region scope (i.e. static region).
1066 /// (The starting point(s) arise implicitly from borrows.)
1067 EndRegion(region::Scope),
1069 /// No-op. Useful for deleting instructions without affecting statement indices.
1073 /// The `ValidationOp` describes what happens with each of the operands of a
1074 /// `Validate` statement.
1075 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq)]
1076 pub enum ValidationOp {
1077 /// Recursively traverse the place following the type and validate that all type
1078 /// invariants are maintained. Furthermore, acquire exclusive/read-only access to the
1079 /// memory reachable from the place.
1081 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1084 /// Recursive traverse the *mutable* part of the type and relinquish all exclusive
1085 /// access *until* the given region ends. Then, access will be recovered.
1086 Suspend(region::Scope),
1089 impl Debug for ValidationOp {
1090 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1091 use self::ValidationOp::*;
1093 Acquire => write!(fmt, "Acquire"),
1094 Release => write!(fmt, "Release"),
1095 // (reuse lifetime rendering policy from ppaux.)
1096 Suspend(ref ce) => write!(fmt, "Suspend({})", ty::ReScope(*ce)),
1101 // This is generic so that it can be reused by miri
1102 #[derive(Clone, RustcEncodable, RustcDecodable)]
1103 pub struct ValidationOperand<'tcx, T> {
1106 pub re: Option<region::Scope>,
1107 pub mutbl: hir::Mutability,
1110 impl<'tcx, T: Debug> Debug for ValidationOperand<'tcx, T> {
1111 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1112 write!(fmt, "{:?}: {:?}", self.place, self.ty)?;
1113 if let Some(ce) = self.re {
1114 // (reuse lifetime rendering policy from ppaux.)
1115 write!(fmt, "/{}", ty::ReScope(ce))?;
1117 if let hir::MutImmutable = self.mutbl {
1118 write!(fmt, " (imm)")?;
1124 impl<'tcx> Debug for Statement<'tcx> {
1125 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1126 use self::StatementKind::*;
1128 Assign(ref place, ref rv) => write!(fmt, "{:?} = {:?}", place, rv),
1129 // (reuse lifetime rendering policy from ppaux.)
1130 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
1131 Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
1132 StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
1133 StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
1134 SetDiscriminant { ref place, variant_index } => {
1135 write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
1137 InlineAsm { ref asm, ref outputs, ref inputs } => {
1138 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1140 Nop => write!(fmt, "nop"),
1145 ///////////////////////////////////////////////////////////////////////////
1148 /// A path to a value; something that can be evaluated without
1149 /// changing or disturbing program state.
1150 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1151 pub enum Place<'tcx> {
1155 /// static or static mut variable
1156 Static(Box<Static<'tcx>>),
1158 /// projection out of a place (access a field, deref a pointer, etc)
1159 Projection(Box<PlaceProjection<'tcx>>),
1162 /// The def-id of a static, along with its normalized type (which is
1163 /// stored to avoid requiring normalization when reading MIR).
1164 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1165 pub struct Static<'tcx> {
1170 impl_stable_hash_for!(struct Static<'tcx> {
1175 /// The `Projection` data structure defines things of the form `B.x`
1176 /// or `*B` or `B[index]`. Note that it is parameterized because it is
1177 /// shared between `Constant` and `Place`. See the aliases
1178 /// `PlaceProjection` etc below.
1179 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1180 pub struct Projection<'tcx, B, V, T> {
1182 pub elem: ProjectionElem<'tcx, V, T>,
1185 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1186 pub enum ProjectionElem<'tcx, V, T> {
1191 /// These indices are generated by slice patterns. Easiest to explain
1195 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
1196 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
1197 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
1198 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
1201 /// index or -index (in Python terms), depending on from_end
1203 /// thing being indexed must be at least this long
1205 /// counting backwards from end?
1209 /// These indices are generated by slice patterns.
1211 /// slice[from:-to] in Python terms.
1217 /// "Downcast" to a variant of an ADT. Currently, we only introduce
1218 /// this for ADTs with more than one variant. It may be better to
1219 /// just introduce it always, or always for enums.
1220 Downcast(&'tcx AdtDef, usize),
1223 /// Alias for projections as they appear in places, where the base is a place
1224 /// and the index is a local.
1225 pub type PlaceProjection<'tcx> = Projection<'tcx, Place<'tcx>, Local, Ty<'tcx>>;
1227 /// Alias for projections as they appear in places, where the base is a place
1228 /// and the index is a local.
1229 pub type PlaceElem<'tcx> = ProjectionElem<'tcx, Local, Ty<'tcx>>;
1231 newtype_index!(Field { DEBUG_FORMAT = "field[{}]" });
1233 impl<'tcx> Place<'tcx> {
1234 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Place<'tcx> {
1235 self.elem(ProjectionElem::Field(f, ty))
1238 pub fn deref(self) -> Place<'tcx> {
1239 self.elem(ProjectionElem::Deref)
1242 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Place<'tcx> {
1243 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
1246 pub fn index(self, index: Local) -> Place<'tcx> {
1247 self.elem(ProjectionElem::Index(index))
1250 pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
1251 Place::Projection(Box::new(PlaceProjection {
1258 impl<'tcx> Debug for Place<'tcx> {
1259 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1263 Local(id) => write!(fmt, "{:?}", id),
1264 Static(box self::Static { def_id, ty }) =>
1265 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
1266 Projection(ref data) =>
1268 ProjectionElem::Downcast(ref adt_def, index) =>
1269 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
1270 ProjectionElem::Deref =>
1271 write!(fmt, "(*{:?})", data.base),
1272 ProjectionElem::Field(field, ty) =>
1273 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
1274 ProjectionElem::Index(ref index) =>
1275 write!(fmt, "{:?}[{:?}]", data.base, index),
1276 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
1277 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
1278 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
1279 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
1280 ProjectionElem::Subslice { from, to } if to == 0 =>
1281 write!(fmt, "{:?}[{:?}:]", data.base, from),
1282 ProjectionElem::Subslice { from, to } if from == 0 =>
1283 write!(fmt, "{:?}[:-{:?}]", data.base, to),
1284 ProjectionElem::Subslice { from, to } =>
1285 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
1293 ///////////////////////////////////////////////////////////////////////////
1296 newtype_index!(VisibilityScope
1298 DEBUG_FORMAT = "scope[{}]",
1299 const ARGUMENT_VISIBILITY_SCOPE = 0,
1302 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1303 pub struct VisibilityScopeData {
1305 pub parent_scope: Option<VisibilityScope>,
1308 ///////////////////////////////////////////////////////////////////////////
1311 /// These are values that can appear inside an rvalue (or an index
1312 /// place). They are intentionally limited to prevent rvalues from
1313 /// being nested in one another.
1314 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1315 pub enum Operand<'tcx> {
1316 /// Copy: The value must be available for use afterwards.
1318 /// This implies that the type of the place must be `Copy`; this is true
1319 /// by construction during build, but also checked by the MIR type checker.
1321 /// Move: The value (including old borrows of it) will not be used again.
1323 /// Safe for values of all types (modulo future developments towards `?Move`).
1324 /// Correct usage patterns are enforced by the borrow checker for safe code.
1325 /// `Copy` may be converted to `Move` to enable "last-use" optimizations.
1327 Constant(Box<Constant<'tcx>>),
1330 impl<'tcx> Debug for Operand<'tcx> {
1331 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1332 use self::Operand::*;
1334 Constant(ref a) => write!(fmt, "{:?}", a),
1335 Copy(ref place) => write!(fmt, "{:?}", place),
1336 Move(ref place) => write!(fmt, "move {:?}", place),
1341 impl<'tcx> Operand<'tcx> {
1342 pub fn function_handle<'a>(
1343 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1345 substs: &'tcx Substs<'tcx>,
1348 let ty = tcx.type_of(def_id).subst(tcx, substs);
1349 Operand::Constant(box Constant {
1352 literal: Literal::Value {
1353 value: tcx.mk_const(ty::Const {
1354 val: ConstVal::Function(def_id, substs),
1361 pub fn to_copy(&self) -> Self {
1363 Operand::Copy(_) | Operand::Constant(_) => self.clone(),
1364 Operand::Move(ref place) => Operand::Copy(place.clone())
1369 ///////////////////////////////////////////////////////////////////////////
1372 #[derive(Clone, RustcEncodable, RustcDecodable)]
1373 pub enum Rvalue<'tcx> {
1374 /// x (either a move or copy, depending on type of x)
1378 Repeat(Operand<'tcx>, ConstUsize),
1381 Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
1383 /// length of a [X] or [X;n] value
1386 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1388 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1389 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1391 NullaryOp(NullOp, Ty<'tcx>),
1392 UnaryOp(UnOp, Operand<'tcx>),
1394 /// Read the discriminant of an ADT.
1396 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1397 /// be defined to return, say, a 0) if ADT is not an enum.
1398 Discriminant(Place<'tcx>),
1400 /// Create an aggregate value, like a tuple or struct. This is
1401 /// only needed because we want to distinguish `dest = Foo { x:
1402 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1403 /// that `Foo` has a destructor. These rvalues can be optimized
1404 /// away after type-checking and before lowering.
1405 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1408 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1412 /// Convert unique, zero-sized type for a fn to fn()
1415 /// Convert non capturing closure to fn()
1418 /// Convert safe fn() to unsafe fn()
1421 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1422 /// trans must figure out the details once full monomorphization
1423 /// is known. For example, this could be used to cast from a
1424 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1425 /// (presuming `T: Trait`).
1429 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1430 pub enum AggregateKind<'tcx> {
1431 /// The type is of the element
1435 /// The second field is variant number (discriminant), it's equal
1436 /// to 0 for struct and union expressions. The fourth field is
1437 /// active field number and is present only for union expressions
1438 /// -- e.g. for a union expression `SomeUnion { c: .. }`, the
1439 /// active field index would identity the field `c`
1440 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1442 Closure(DefId, ClosureSubsts<'tcx>),
1443 Generator(DefId, ClosureSubsts<'tcx>, GeneratorInterior<'tcx>),
1446 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1448 /// The `+` operator (addition)
1450 /// The `-` operator (subtraction)
1452 /// The `*` operator (multiplication)
1454 /// The `/` operator (division)
1456 /// The `%` operator (modulus)
1458 /// The `^` operator (bitwise xor)
1460 /// The `&` operator (bitwise and)
1462 /// The `|` operator (bitwise or)
1464 /// The `<<` operator (shift left)
1466 /// The `>>` operator (shift right)
1468 /// The `==` operator (equality)
1470 /// The `<` operator (less than)
1472 /// The `<=` operator (less than or equal to)
1474 /// The `!=` operator (not equal to)
1476 /// The `>=` operator (greater than or equal to)
1478 /// The `>` operator (greater than)
1480 /// The `ptr.offset` operator
1485 pub fn is_checkable(self) -> bool {
1488 Add | Sub | Mul | Shl | Shr => true,
1494 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1496 /// Return the size of a value of that type
1498 /// Create a new uninitialized box for a value of that type
1502 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1504 /// The `!` operator for logical inversion
1506 /// The `-` operator for negation
1510 impl<'tcx> Debug for Rvalue<'tcx> {
1511 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1512 use self::Rvalue::*;
1515 Use(ref place) => write!(fmt, "{:?}", place),
1516 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1517 Len(ref a) => write!(fmt, "Len({:?})", a),
1518 Cast(ref kind, ref place, ref ty) => {
1519 write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
1521 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1522 CheckedBinaryOp(ref op, ref a, ref b) => {
1523 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1525 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1526 Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
1527 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1528 Ref(region, borrow_kind, ref place) => {
1529 let kind_str = match borrow_kind {
1530 BorrowKind::Shared => "",
1531 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1534 // When printing regions, add trailing space if necessary.
1535 let region = if ppaux::verbose() || ppaux::identify_regions() {
1536 let mut region = format!("{}", region);
1537 if region.len() > 0 { region.push(' '); }
1540 // Do not even print 'static
1543 write!(fmt, "&{}{}{:?}", region, kind_str, place)
1546 Aggregate(ref kind, ref places) => {
1547 fn fmt_tuple(fmt: &mut Formatter, places: &[Operand]) -> fmt::Result {
1548 let mut tuple_fmt = fmt.debug_tuple("");
1549 for place in places {
1550 tuple_fmt.field(place);
1556 AggregateKind::Array(_) => write!(fmt, "{:?}", places),
1558 AggregateKind::Tuple => {
1559 match places.len() {
1560 0 => write!(fmt, "()"),
1561 1 => write!(fmt, "({:?},)", places[0]),
1562 _ => fmt_tuple(fmt, places),
1566 AggregateKind::Adt(adt_def, variant, substs, _) => {
1567 let variant_def = &adt_def.variants[variant];
1569 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1571 match variant_def.ctor_kind {
1572 CtorKind::Const => Ok(()),
1573 CtorKind::Fn => fmt_tuple(fmt, places),
1574 CtorKind::Fictive => {
1575 let mut struct_fmt = fmt.debug_struct("");
1576 for (field, place) in variant_def.fields.iter().zip(places) {
1577 struct_fmt.field(&field.name.as_str(), place);
1584 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1585 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1586 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1587 format!("[closure@{:?}]", node_id)
1589 format!("[closure@{:?}]", tcx.hir.span(node_id))
1591 let mut struct_fmt = fmt.debug_struct(&name);
1593 tcx.with_freevars(node_id, |freevars| {
1594 for (freevar, place) in freevars.iter().zip(places) {
1595 let var_name = tcx.hir.name(freevar.var_id());
1596 struct_fmt.field(&var_name.as_str(), place);
1602 write!(fmt, "[closure]")
1606 AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
1607 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1608 let name = format!("[generator@{:?}]", tcx.hir.span(node_id));
1609 let mut struct_fmt = fmt.debug_struct(&name);
1611 tcx.with_freevars(node_id, |freevars| {
1612 for (freevar, place) in freevars.iter().zip(places) {
1613 let var_name = tcx.hir.name(freevar.var_id());
1614 struct_fmt.field(&var_name.as_str(), place);
1616 struct_fmt.field("$state", &places[freevars.len()]);
1617 for i in (freevars.len() + 1)..places.len() {
1618 struct_fmt.field(&format!("${}", i - freevars.len() - 1),
1625 write!(fmt, "[generator]")
1634 ///////////////////////////////////////////////////////////////////////////
1637 /// Two constants are equal if they are the same constant. Note that
1638 /// this does not necessarily mean that they are "==" in Rust -- in
1639 /// particular one must be wary of `NaN`!
1641 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1642 pub struct Constant<'tcx> {
1645 pub literal: Literal<'tcx>,
1648 newtype_index!(Promoted { DEBUG_FORMAT = "promoted[{}]" });
1651 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1652 pub enum Literal<'tcx> {
1654 value: &'tcx ty::Const<'tcx>,
1657 // Index into the `promoted` vector of `Mir`.
1662 impl<'tcx> Debug for Constant<'tcx> {
1663 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1664 write!(fmt, "{:?}", self.literal)
1668 impl<'tcx> Debug for Literal<'tcx> {
1669 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1670 use self::Literal::*;
1672 Value { value } => {
1673 write!(fmt, "const ")?;
1674 fmt_const_val(fmt, &value.val)
1676 Promoted { index } => {
1677 write!(fmt, "{:?}", index)
1683 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1684 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1685 use middle::const_val::ConstVal::*;
1687 Float(f) => write!(fmt, "{:?}", f),
1688 Integral(n) => write!(fmt, "{}", n),
1689 Str(s) => write!(fmt, "{:?}", s),
1691 let escaped: String = bytes.data
1693 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1695 write!(fmt, "b\"{}\"", escaped)
1697 Bool(b) => write!(fmt, "{:?}", b),
1698 Char(c) => write!(fmt, "{:?}", c),
1700 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1701 Aggregate(_) => bug!("`ConstVal::{:?}` should not be in MIR", const_val),
1702 Unevaluated(..) => write!(fmt, "{:?}", const_val)
1706 fn item_path_str(def_id: DefId) -> String {
1707 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1710 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1712 type Node = BasicBlock;
1714 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1716 fn start_node(&self) -> Self::Node { START_BLOCK }
1718 fn predecessors<'graph>(&'graph self, node: Self::Node)
1719 -> <Self as GraphPredecessors<'graph>>::Iter
1721 self.predecessors_for(node).clone().into_iter()
1723 fn successors<'graph>(&'graph self, node: Self::Node)
1724 -> <Self as GraphSuccessors<'graph>>::Iter
1726 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1730 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1731 type Item = BasicBlock;
1732 type Iter = IntoIter<BasicBlock>;
1735 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1736 type Item = BasicBlock;
1737 type Iter = IntoIter<BasicBlock>;
1740 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1741 pub struct Location {
1742 /// the location is within this block
1743 pub block: BasicBlock,
1745 /// the location is the start of the this statement; or, if `statement_index`
1746 /// == num-statements, then the start of the terminator.
1747 pub statement_index: usize,
1750 impl fmt::Debug for Location {
1751 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1752 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1757 /// Returns the location immediately after this one within the enclosing block.
1759 /// Note that if this location represents a terminator, then the
1760 /// resulting location would be out of bounds and invalid.
1761 pub fn successor_within_block(&self) -> Location {
1762 Location { block: self.block, statement_index: self.statement_index + 1 }
1765 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1766 if self.block == other.block {
1767 self.statement_index <= other.statement_index
1769 dominators.is_dominated_by(other.block, self.block)
1774 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1775 pub enum UnsafetyViolationKind {
1777 ExternStatic(ast::NodeId),
1778 BorrowPacked(ast::NodeId),
1781 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1782 pub struct UnsafetyViolation {
1783 pub source_info: SourceInfo,
1784 pub description: InternedString,
1785 pub kind: UnsafetyViolationKind,
1788 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1789 pub struct UnsafetyCheckResult {
1790 /// Violations that are propagated *upwards* from this function
1791 pub violations: Rc<[UnsafetyViolation]>,
1792 /// unsafe blocks in this function, along with whether they are used. This is
1793 /// used for the "unused_unsafe" lint.
1794 pub unsafe_blocks: Rc<[(ast::NodeId, bool)]>,
1797 /// The layout of generator state
1798 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1799 pub struct GeneratorLayout<'tcx> {
1800 pub fields: Vec<LocalDecl<'tcx>>,
1803 /// After we borrow check a closure, we are left with various
1804 /// requirements that we have inferred between the free regions that
1805 /// appear in the closure's signature or on its field types. These
1806 /// requirements are then verified and proved by the closure's
1807 /// creating function. This struct encodes those requirements.
1809 /// The requirements are listed as being between various
1810 /// `RegionVid`. The 0th region refers to `'static`; subsequent region
1811 /// vids refer to the free regions that appear in the closure (or
1812 /// generator's) type, in order of appearance. (This numbering is
1813 /// actually defined by the `UniversalRegions` struct in the NLL
1814 /// region checker. See for example
1815 /// `UniversalRegions::closure_mapping`.) Note that we treat the free
1816 /// regions in the closure's type "as if" they were erased, so their
1817 /// precise identity is not important, only their position.
1819 /// Example: If type check produces a closure with the closure substs:
1822 /// ClosureSubsts = [
1823 /// i8, // the "closure kind"
1824 /// for<'x> fn(&'a &'x u32) -> &'x u32, // the "closure signature"
1825 /// &'a String, // some upvar
1829 /// here, there is one unique free region (`'a`) but it appears
1830 /// twice. We would "renumber" each occurence to a unique vid, as follows:
1833 /// ClosureSubsts = [
1834 /// i8, // the "closure kind"
1835 /// for<'x> fn(&'1 &'x u32) -> &'x u32, // the "closure signature"
1836 /// &'2 String, // some upvar
1840 /// Now the code might impose a requirement like `'1: '2`. When an
1841 /// instance of the closure is created, the corresponding free regions
1842 /// can be extracted from its type and constrained to have the given
1843 /// outlives relationship.
1845 /// In some cases, we have to record outlives requirements between
1846 /// types and regions as well. In that case, if those types include
1847 /// any regions, those regions are recorded as `ReClosureBound`
1848 /// instances assigned one of these same indices. Those regions will
1849 /// be substituted away by the creator. We use `ReClosureBound` in
1850 /// that case because the regions must be allocated in the global
1851 /// TyCtxt, and hence we cannot use `ReVar` (which is what we use
1852 /// internally within the rest of the NLL code).
1853 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
1854 pub struct ClosureRegionRequirements<'gcx> {
1855 /// The number of external regions defined on the closure. In our
1856 /// example above, it would be 3 -- one for `'static`, then `'1`
1857 /// and `'2`. This is just used for a sanity check later on, to
1858 /// make sure that the number of regions we see at the callsite
1860 pub num_external_vids: usize,
1862 /// Requirements between the various free regions defined in
1864 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'gcx>>,
1867 /// Indicates an outlives constraint between a type or between two
1868 /// free-regions declared on the closure.
1869 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
1870 pub struct ClosureOutlivesRequirement<'tcx> {
1871 // This region or type ...
1872 pub subject: ClosureOutlivesSubject<'tcx>,
1874 // .. must outlive this one.
1875 pub outlived_free_region: ty::RegionVid,
1877 // If not, report an error here.
1878 pub blame_span: Span,
1881 /// The subject of a ClosureOutlivesRequirement -- that is, the thing
1882 /// that must outlive some region.
1883 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
1884 pub enum ClosureOutlivesSubject<'tcx> {
1885 /// Subject is a type, typically a type parameter, but could also
1886 /// be a projection. Indicates a requirement like `T: 'a` being
1887 /// passed to the caller, where the type here is `T`.
1889 /// The type here is guaranteed not to contain any free regions at
1893 /// Subject is a free region from the closure. Indicates a requirement
1894 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
1895 Region(ty::RegionVid),
1899 * TypeFoldable implementations for MIR types
1902 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1903 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1905 basic_blocks: self.basic_blocks.fold_with(folder),
1906 visibility_scopes: self.visibility_scopes.clone(),
1907 visibility_scope_info: self.visibility_scope_info.clone(),
1908 promoted: self.promoted.fold_with(folder),
1909 yield_ty: self.yield_ty.fold_with(folder),
1910 generator_drop: self.generator_drop.fold_with(folder),
1911 generator_layout: self.generator_layout.fold_with(folder),
1912 local_decls: self.local_decls.fold_with(folder),
1913 arg_count: self.arg_count,
1914 upvar_decls: self.upvar_decls.clone(),
1915 spread_arg: self.spread_arg,
1917 cache: cache::Cache::new()
1921 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1922 self.basic_blocks.visit_with(visitor) ||
1923 self.generator_drop.visit_with(visitor) ||
1924 self.generator_layout.visit_with(visitor) ||
1925 self.yield_ty.visit_with(visitor) ||
1926 self.promoted.visit_with(visitor) ||
1927 self.local_decls.visit_with(visitor)
1931 impl<'tcx> TypeFoldable<'tcx> for GeneratorLayout<'tcx> {
1932 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1934 fields: self.fields.fold_with(folder),
1938 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1939 self.fields.visit_with(visitor)
1943 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1944 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1946 ty: self.ty.fold_with(folder),
1951 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1952 self.ty.visit_with(visitor)
1956 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1957 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1959 statements: self.statements.fold_with(folder),
1960 terminator: self.terminator.fold_with(folder),
1961 is_cleanup: self.is_cleanup
1965 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1966 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1970 impl<'tcx> TypeFoldable<'tcx> for ValidationOperand<'tcx, Place<'tcx>> {
1971 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1973 place: self.place.fold_with(folder),
1974 ty: self.ty.fold_with(folder),
1980 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1981 self.place.visit_with(visitor) || self.ty.visit_with(visitor)
1985 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1986 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1987 use mir::StatementKind::*;
1989 let kind = match self.kind {
1990 Assign(ref place, ref rval) => Assign(place.fold_with(folder), rval.fold_with(folder)),
1991 SetDiscriminant { ref place, variant_index } => SetDiscriminant {
1992 place: place.fold_with(folder),
1995 StorageLive(ref local) => StorageLive(local.fold_with(folder)),
1996 StorageDead(ref local) => StorageDead(local.fold_with(folder)),
1997 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1999 outputs: outputs.fold_with(folder),
2000 inputs: inputs.fold_with(folder)
2003 // Note for future: If we want to expose the region scopes
2004 // during the fold, we need to either generalize EndRegion
2005 // to carry `[ty::Region]`, or extend the `TypeFolder`
2006 // trait with a `fn fold_scope`.
2007 EndRegion(ref region_scope) => EndRegion(region_scope.clone()),
2009 Validate(ref op, ref places) =>
2010 Validate(op.clone(),
2011 places.iter().map(|operand| operand.fold_with(folder)).collect()),
2016 source_info: self.source_info,
2021 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2022 use mir::StatementKind::*;
2025 Assign(ref place, ref rval) => { place.visit_with(visitor) || rval.visit_with(visitor) }
2026 SetDiscriminant { ref place, .. } => place.visit_with(visitor),
2027 StorageLive(ref local) |
2028 StorageDead(ref local) => local.visit_with(visitor),
2029 InlineAsm { ref outputs, ref inputs, .. } =>
2030 outputs.visit_with(visitor) || inputs.visit_with(visitor),
2032 // Note for future: If we want to expose the region scopes
2033 // during the visit, we need to either generalize EndRegion
2034 // to carry `[ty::Region]`, or extend the `TypeVisitor`
2035 // trait with a `fn visit_scope`.
2036 EndRegion(ref _scope) => false,
2038 Validate(ref _op, ref places) =>
2039 places.iter().any(|ty_and_place| ty_and_place.visit_with(visitor)),
2046 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
2047 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2048 use mir::TerminatorKind::*;
2050 let kind = match self.kind {
2051 Goto { target } => Goto { target: target },
2052 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
2053 discr: discr.fold_with(folder),
2054 switch_ty: switch_ty.fold_with(folder),
2055 values: values.clone(),
2056 targets: targets.clone()
2058 Drop { ref location, target, unwind } => Drop {
2059 location: location.fold_with(folder),
2063 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
2064 location: location.fold_with(folder),
2065 value: value.fold_with(folder),
2069 Yield { ref value, resume, drop } => Yield {
2070 value: value.fold_with(folder),
2074 Call { ref func, ref args, ref destination, cleanup } => {
2075 let dest = destination.as_ref().map(|&(ref loc, dest)| {
2076 (loc.fold_with(folder), dest)
2080 func: func.fold_with(folder),
2081 args: args.fold_with(folder),
2086 Assert { ref cond, expected, ref msg, target, cleanup } => {
2087 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2088 AssertMessage::BoundsCheck {
2089 len: len.fold_with(folder),
2090 index: index.fold_with(folder),
2096 cond: cond.fold_with(folder),
2103 GeneratorDrop => GeneratorDrop,
2106 Unreachable => Unreachable,
2107 FalseEdges { real_target, ref imaginary_targets } =>
2108 FalseEdges { real_target, imaginary_targets: imaginary_targets.clone() }
2111 source_info: self.source_info,
2116 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2117 use mir::TerminatorKind::*;
2120 SwitchInt { ref discr, switch_ty, .. } =>
2121 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
2122 Drop { ref location, ..} => location.visit_with(visitor),
2123 DropAndReplace { ref location, ref value, ..} =>
2124 location.visit_with(visitor) || value.visit_with(visitor),
2125 Yield { ref value, ..} =>
2126 value.visit_with(visitor),
2127 Call { ref func, ref args, ref destination, .. } => {
2128 let dest = if let Some((ref loc, _)) = *destination {
2129 loc.visit_with(visitor)
2131 dest || func.visit_with(visitor) || args.visit_with(visitor)
2133 Assert { ref cond, ref msg, .. } => {
2134 if cond.visit_with(visitor) {
2135 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
2136 len.visit_with(visitor) || index.visit_with(visitor)
2149 FalseEdges { .. } => false
2154 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
2155 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2157 &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
2162 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2163 if let &Place::Projection(ref p) = self {
2164 p.visit_with(visitor)
2171 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
2172 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2175 Use(ref op) => Use(op.fold_with(folder)),
2176 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
2177 Ref(region, bk, ref place) =>
2178 Ref(region.fold_with(folder), bk, place.fold_with(folder)),
2179 Len(ref place) => Len(place.fold_with(folder)),
2180 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
2181 BinaryOp(op, ref rhs, ref lhs) =>
2182 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2183 CheckedBinaryOp(op, ref rhs, ref lhs) =>
2184 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
2185 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
2186 Discriminant(ref place) => Discriminant(place.fold_with(folder)),
2187 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
2188 Aggregate(ref kind, ref fields) => {
2189 let kind = box match **kind {
2190 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
2191 AggregateKind::Tuple => AggregateKind::Tuple,
2192 AggregateKind::Adt(def, v, substs, n) =>
2193 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
2194 AggregateKind::Closure(id, substs) =>
2195 AggregateKind::Closure(id, substs.fold_with(folder)),
2196 AggregateKind::Generator(id, substs, interior) =>
2197 AggregateKind::Generator(id,
2198 substs.fold_with(folder),
2199 interior.fold_with(folder)),
2201 Aggregate(kind, fields.fold_with(folder))
2206 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2209 Use(ref op) => op.visit_with(visitor),
2210 Repeat(ref op, _) => op.visit_with(visitor),
2211 Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
2212 Len(ref place) => place.visit_with(visitor),
2213 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
2214 BinaryOp(_, ref rhs, ref lhs) |
2215 CheckedBinaryOp(_, ref rhs, ref lhs) =>
2216 rhs.visit_with(visitor) || lhs.visit_with(visitor),
2217 UnaryOp(_, ref val) => val.visit_with(visitor),
2218 Discriminant(ref place) => place.visit_with(visitor),
2219 NullaryOp(_, ty) => ty.visit_with(visitor),
2220 Aggregate(ref kind, ref fields) => {
2222 AggregateKind::Array(ty) => ty.visit_with(visitor),
2223 AggregateKind::Tuple => false,
2224 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
2225 AggregateKind::Closure(_, substs) => substs.visit_with(visitor),
2226 AggregateKind::Generator(_, substs, interior) => substs.visit_with(visitor) ||
2227 interior.visit_with(visitor),
2228 }) || fields.visit_with(visitor)
2234 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
2235 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2237 Operand::Copy(ref place) => Operand::Copy(place.fold_with(folder)),
2238 Operand::Move(ref place) => Operand::Move(place.fold_with(folder)),
2239 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
2243 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2245 Operand::Copy(ref place) |
2246 Operand::Move(ref place) => place.visit_with(visitor),
2247 Operand::Constant(ref c) => c.visit_with(visitor)
2252 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
2253 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>
2255 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2256 use mir::ProjectionElem::*;
2258 let base = self.base.fold_with(folder);
2259 let elem = match self.elem {
2261 Field(f, ref ty) => Field(f, ty.fold_with(folder)),
2262 Index(ref v) => Index(v.fold_with(folder)),
2263 ref elem => elem.clone()
2272 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
2273 use mir::ProjectionElem::*;
2275 self.base.visit_with(visitor) ||
2277 Field(_, ref ty) => ty.visit_with(visitor),
2278 Index(ref v) => v.visit_with(visitor),
2284 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
2285 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2287 span: self.span.clone(),
2288 ty: self.ty.fold_with(folder),
2289 literal: self.literal.fold_with(folder)
2292 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2293 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
2297 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
2298 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
2300 Literal::Value { value } => Literal::Value {
2301 value: value.fold_with(folder)
2303 Literal::Promoted { index } => Literal::Promoted { index }
2306 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
2308 Literal::Value { value } => value.visit_with(visitor),
2309 Literal::Promoted { .. } => false