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;
15 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
16 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
17 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
18 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
19 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
20 use hir::def::CtorKind;
21 use hir::def_id::DefId;
22 use ty::subst::{Subst, Substs};
23 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
24 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
26 use rustc_back::slice;
29 use std::borrow::{Cow};
31 use std::fmt::{self, Debug, Formatter, Write};
33 use std::ops::{Index, IndexMut};
34 use std::vec::IntoIter;
35 use syntax::ast::Name;
44 macro_rules! newtype_index {
45 ($name:ident, $debug_name:expr) => (
46 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
47 RustcEncodable, RustcDecodable)]
48 pub struct $name(u32);
51 fn new(value: usize) -> Self {
52 assert!(value < (u32::MAX) as usize);
55 fn index(self) -> usize {
60 impl Debug for $name {
61 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
62 write!(fmt, "{}{}", $debug_name, self.0)
68 /// Lowered representation of a single function.
69 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
70 pub struct Mir<'tcx> {
71 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
72 /// that indexes into this vector.
73 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
75 /// List of visibility (lexical) scopes; these are referenced by statements
76 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
77 pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
79 /// Rvalues promoted from this function, such as borrows of constants.
80 /// Each of them is the Mir of a constant with the fn's type parameters
81 /// in scope, but a separate set of locals.
82 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
84 /// Return type of the function.
85 pub return_ty: Ty<'tcx>,
87 /// Declarations of locals.
89 /// The first local is the return value pointer, followed by `arg_count`
90 /// locals for the function arguments, followed by any user-declared
91 /// variables and temporaries.
92 pub local_decls: IndexVec<Local, LocalDecl<'tcx>>,
94 /// Number of arguments this function takes.
96 /// Starting at local 1, `arg_count` locals will be provided by the caller
97 /// and can be assumed to be initialized.
99 /// If this MIR was built for a constant, this will be 0.
100 pub arg_count: usize,
102 /// Names and capture modes of all the closure upvars, assuming
103 /// the first argument is either the closure or a reference to it.
104 pub upvar_decls: Vec<UpvarDecl>,
106 /// Mark an argument local (which must be a tuple) as getting passed as
107 /// its individual components at the LLVM level.
109 /// This is used for the "rust-call" ABI.
110 pub spread_arg: Option<Local>,
112 /// A span representing this MIR, for error reporting
115 /// A cache for various calculations
119 /// where execution begins
120 pub const START_BLOCK: BasicBlock = BasicBlock(0);
122 impl<'tcx> Mir<'tcx> {
123 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
124 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
125 promoted: IndexVec<Promoted, Mir<'tcx>>,
127 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
129 upvar_decls: Vec<UpvarDecl>,
132 // We need `arg_count` locals, and one for the return pointer
133 assert!(local_decls.len() >= arg_count + 1,
134 "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
135 assert_eq!(local_decls[RETURN_POINTER].ty, return_ty);
138 basic_blocks: basic_blocks,
139 visibility_scopes: visibility_scopes,
141 return_ty: return_ty,
142 local_decls: local_decls,
143 arg_count: arg_count,
144 upvar_decls: upvar_decls,
147 cache: cache::Cache::new()
152 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
157 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
158 self.cache.invalidate();
159 &mut self.basic_blocks
163 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
164 self.cache.predecessors(self)
168 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
169 Ref::map(self.predecessors(), |p| &p[bb])
173 pub fn dominators(&self) -> Dominators<BasicBlock> {
178 pub fn local_kind(&self, local: Local) -> LocalKind {
179 let index = local.0 as usize;
181 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
182 "return pointer should be mutable");
184 LocalKind::ReturnPointer
185 } else if index < self.arg_count + 1 {
187 } else if self.local_decls[local].name.is_some() {
190 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
191 "temp should be mutable");
197 /// Returns an iterator over all temporaries.
199 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
200 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
201 let local = Local::new(index);
202 if self.local_decls[local].is_user_variable {
210 /// Returns an iterator over all user-declared locals.
212 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
213 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
214 let local = Local::new(index);
215 if self.local_decls[local].is_user_variable {
223 /// Returns an iterator over all function arguments.
225 pub fn args_iter(&self) -> impl Iterator<Item=Local> {
226 let arg_count = self.arg_count;
227 (1..arg_count+1).map(Local::new)
230 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
231 /// locals that are neither arguments nor the return pointer).
233 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
234 let arg_count = self.arg_count;
235 let local_count = self.local_decls.len();
236 (arg_count+1..local_count).map(Local::new)
239 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
240 /// invalidating statement indices in `Location`s.
241 pub fn make_statement_nop(&mut self, location: Location) {
242 let block = &mut self[location.block];
243 debug_assert!(location.statement_index < block.statements.len());
244 block.statements[location.statement_index].make_nop()
248 impl_stable_hash_for!(struct Mir<'tcx> {
261 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
262 type Output = BasicBlockData<'tcx>;
265 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
266 &self.basic_blocks()[index]
270 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
272 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
273 &mut self.basic_blocks_mut()[index]
277 /// Grouped information about the source code origin of a MIR entity.
278 /// Intended to be inspected by diagnostics and debuginfo.
279 /// Most passes can work with it as a whole, within a single function.
280 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
281 pub struct SourceInfo {
282 /// Source span for the AST pertaining to this MIR entity.
285 /// The lexical visibility scope, i.e. which bindings can be seen.
286 pub scope: VisibilityScope
289 ///////////////////////////////////////////////////////////////////////////
290 // Mutability and borrow kinds
292 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
293 pub enum Mutability {
298 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
299 pub enum BorrowKind {
300 /// Data must be immutable and is aliasable.
303 /// Data must be immutable but not aliasable. This kind of borrow
304 /// cannot currently be expressed by the user and is used only in
305 /// implicit closure bindings. It is needed when you the closure
306 /// is borrowing or mutating a mutable referent, e.g.:
308 /// let x: &mut isize = ...;
309 /// let y = || *x += 5;
311 /// If we were to try to translate this closure into a more explicit
312 /// form, we'd encounter an error with the code as written:
314 /// struct Env { x: & &mut isize }
315 /// let x: &mut isize = ...;
316 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
317 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
319 /// This is then illegal because you cannot mutate a `&mut` found
320 /// in an aliasable location. To solve, you'd have to translate with
321 /// an `&mut` borrow:
323 /// struct Env { x: & &mut isize }
324 /// let x: &mut isize = ...;
325 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
326 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
328 /// Now the assignment to `**env.x` is legal, but creating a
329 /// mutable pointer to `x` is not because `x` is not mutable. We
330 /// could fix this by declaring `x` as `let mut x`. This is ok in
331 /// user code, if awkward, but extra weird for closures, since the
332 /// borrow is hidden.
334 /// So we introduce a "unique imm" borrow -- the referent is
335 /// immutable, but not aliasable. This solves the problem. For
336 /// simplicity, we don't give users the way to express this
337 /// borrow, it's just used when translating closures.
340 /// Data is mutable and not aliasable.
344 ///////////////////////////////////////////////////////////////////////////
345 // Variables and temps
347 newtype_index!(Local, "_");
349 pub const RETURN_POINTER: Local = Local(0);
351 /// Classifies locals into categories. See `Mir::local_kind`.
352 #[derive(PartialEq, Eq, Debug)]
354 /// User-declared variable binding
356 /// Compiler-introduced temporary
358 /// Function argument
360 /// Location of function's return value
366 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
367 /// argument, or the return pointer.
368 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
369 pub struct LocalDecl<'tcx> {
370 /// `let mut x` vs `let x`.
372 /// Temporaries and the return pointer are always mutable.
373 pub mutability: Mutability,
375 /// True if this corresponds to a user-declared local variable.
376 pub is_user_variable: bool,
378 /// Type of this local.
381 /// Name of the local, used in debuginfo and pretty-printing.
383 /// Note that function arguments can also have this set to `Some(_)`
384 /// to generate better debuginfo.
385 pub name: Option<Name>,
387 /// Source info of the local.
388 pub source_info: SourceInfo,
391 impl<'tcx> LocalDecl<'tcx> {
392 /// Create a new `LocalDecl` for a temporary.
394 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
396 mutability: Mutability::Mut,
399 source_info: SourceInfo {
401 scope: ARGUMENT_VISIBILITY_SCOPE
403 is_user_variable: false
407 /// Builds a `LocalDecl` for the return pointer.
409 /// This must be inserted into the `local_decls` list as the first local.
411 pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
413 mutability: Mutability::Mut,
415 source_info: SourceInfo {
417 scope: ARGUMENT_VISIBILITY_SCOPE
419 name: None, // FIXME maybe we do want some name here?
420 is_user_variable: false
425 /// A closure capture, with its name and mode.
426 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
427 pub struct UpvarDecl {
428 pub debug_name: Name,
430 /// If true, the capture is behind a reference.
434 ///////////////////////////////////////////////////////////////////////////
437 newtype_index!(BasicBlock, "bb");
439 ///////////////////////////////////////////////////////////////////////////
440 // BasicBlockData and Terminator
442 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
443 pub struct BasicBlockData<'tcx> {
444 /// List of statements in this block.
445 pub statements: Vec<Statement<'tcx>>,
447 /// Terminator for this block.
449 /// NB. This should generally ONLY be `None` during construction.
450 /// Therefore, you should generally access it via the
451 /// `terminator()` or `terminator_mut()` methods. The only
452 /// exception is that certain passes, such as `simplify_cfg`, swap
453 /// out the terminator temporarily with `None` while they continue
454 /// to recurse over the set of basic blocks.
455 pub terminator: Option<Terminator<'tcx>>,
457 /// If true, this block lies on an unwind path. This is used
458 /// during trans where distinct kinds of basic blocks may be
459 /// generated (particularly for MSVC cleanup). Unwind blocks must
460 /// only branch to other unwind blocks.
461 pub is_cleanup: bool,
464 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
465 pub struct Terminator<'tcx> {
466 pub source_info: SourceInfo,
467 pub kind: TerminatorKind<'tcx>
470 #[derive(Clone, RustcEncodable, RustcDecodable)]
471 pub enum TerminatorKind<'tcx> {
472 /// block should have one successor in the graph; we jump there
477 /// operand evaluates to an integer; jump depending on its value
478 /// to one of the targets, and otherwise fallback to `otherwise`
480 /// discriminant value being tested
481 discr: Operand<'tcx>,
483 /// type of value being tested
486 /// Possible values. The locations to branch to in each case
487 /// are found in the corresponding indices from the `targets` vector.
488 values: Cow<'tcx, [ConstInt]>,
490 /// Possible branch sites. The last element of this vector is used
491 /// for the otherwise branch, so targets.len() == values.len() + 1
493 // This invariant is quite non-obvious and also could be improved.
494 // One way to make this invariant is to have something like this instead:
496 // branches: Vec<(ConstInt, BasicBlock)>,
497 // otherwise: Option<BasicBlock> // exhaustive if None
499 // However we’ve decided to keep this as-is until we figure a case
500 // where some other approach seems to be strictly better than other.
501 targets: Vec<BasicBlock>,
504 /// Indicates that the landing pad is finished and unwinding should
505 /// continue. Emitted by build::scope::diverge_cleanup.
508 /// Indicates a normal return. The return pointer lvalue should
509 /// have been filled in by now. This should occur at most once.
512 /// Indicates a terminator that can never be reached.
517 location: Lvalue<'tcx>,
519 unwind: Option<BasicBlock>
522 /// Drop the Lvalue and assign the new value over it
524 location: Lvalue<'tcx>,
525 value: Operand<'tcx>,
527 unwind: Option<BasicBlock>,
530 /// Block ends with a call of a converging function
532 /// The function that’s being called
534 /// Arguments the function is called with
535 args: Vec<Operand<'tcx>>,
536 /// Destination for the return value. If some, the call is converging.
537 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
538 /// Cleanups to be done if the call unwinds.
539 cleanup: Option<BasicBlock>
542 /// Jump to the target if the condition has the expected value,
543 /// otherwise panic with a message and a cleanup target.
547 msg: AssertMessage<'tcx>,
549 cleanup: Option<BasicBlock>
553 impl<'tcx> Terminator<'tcx> {
554 pub fn successors(&self) -> Cow<[BasicBlock]> {
555 self.kind.successors()
558 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
559 self.kind.successors_mut()
563 impl<'tcx> TerminatorKind<'tcx> {
564 pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
565 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
566 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
567 TerminatorKind::SwitchInt {
569 switch_ty: tcx.types.bool,
570 values: From::from(BOOL_SWITCH_FALSE),
575 pub fn successors(&self) -> Cow<[BasicBlock]> {
576 use self::TerminatorKind::*;
578 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
579 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
580 Resume => (&[]).into_cow(),
581 Return => (&[]).into_cow(),
582 Unreachable => (&[]).into_cow(),
583 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
584 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
585 slice::ref_slice(t).into_cow(),
586 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
587 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
588 DropAndReplace { target, unwind: Some(unwind), .. } |
589 Drop { target, unwind: Some(unwind), .. } => {
590 vec![target, unwind].into_cow()
592 DropAndReplace { ref target, unwind: None, .. } |
593 Drop { ref target, unwind: None, .. } => {
594 slice::ref_slice(target).into_cow()
596 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
597 Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
601 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
602 // `Vec<&mut BasicBlock>` would look like in the first place.
603 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
604 use self::TerminatorKind::*;
606 Goto { target: ref mut b } => vec![b],
607 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
608 Resume => Vec::new(),
609 Return => Vec::new(),
610 Unreachable => Vec::new(),
611 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
612 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
613 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
614 Call { destination: None, cleanup: None, .. } => vec![],
615 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
616 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
617 DropAndReplace { ref mut target, unwind: None, .. } |
618 Drop { ref mut target, unwind: None, .. } => {
621 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
622 Assert { ref mut target, .. } => vec![target]
627 impl<'tcx> BasicBlockData<'tcx> {
628 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
631 terminator: terminator,
636 /// Accessor for terminator.
638 /// Terminator may not be None after construction of the basic block is complete. This accessor
639 /// provides a convenience way to reach the terminator.
640 pub fn terminator(&self) -> &Terminator<'tcx> {
641 self.terminator.as_ref().expect("invalid terminator state")
644 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
645 self.terminator.as_mut().expect("invalid terminator state")
649 impl<'tcx> Debug for TerminatorKind<'tcx> {
650 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
652 let successors = self.successors();
653 let labels = self.fmt_successor_labels();
654 assert_eq!(successors.len(), labels.len());
656 match successors.len() {
659 1 => write!(fmt, " -> {:?}", successors[0]),
662 write!(fmt, " -> [")?;
663 for (i, target) in successors.iter().enumerate() {
667 write!(fmt, "{}: {:?}", labels[i], target)?;
676 impl<'tcx> TerminatorKind<'tcx> {
677 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
678 /// successor basic block, if any. The only information not inlcuded is the list of possible
679 /// successors, which may be rendered differently between the text and the graphviz format.
680 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
681 use self::TerminatorKind::*;
683 Goto { .. } => write!(fmt, "goto"),
684 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
685 Return => write!(fmt, "return"),
686 Resume => write!(fmt, "resume"),
687 Unreachable => write!(fmt, "unreachable"),
688 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
689 DropAndReplace { ref location, ref value, .. } =>
690 write!(fmt, "replace({:?} <- {:?})", location, value),
691 Call { ref func, ref args, ref destination, .. } => {
692 if let Some((ref destination, _)) = *destination {
693 write!(fmt, "{:?} = ", destination)?;
695 write!(fmt, "{:?}(", func)?;
696 for (index, arg) in args.iter().enumerate() {
700 write!(fmt, "{:?}", arg)?;
704 Assert { ref cond, expected, ref msg, .. } => {
705 write!(fmt, "assert(")?;
709 write!(fmt, "{:?}, ", cond)?;
712 AssertMessage::BoundsCheck { ref len, ref index } => {
713 write!(fmt, "{:?}, {:?}, {:?}",
714 "index out of bounds: the len is {} but the index is {}",
717 AssertMessage::Math(ref err) => {
718 write!(fmt, "{:?}", err.description())?;
727 /// Return the list of labels for the edges to the successor basic blocks.
728 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
729 use self::TerminatorKind::*;
731 Return | Resume | Unreachable => vec![],
732 Goto { .. } => vec!["".into()],
733 SwitchInt { ref values, .. } => {
736 let mut buf = String::new();
737 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
740 .chain(iter::once(String::from("otherwise").into()))
743 Call { destination: Some(_), cleanup: Some(_), .. } =>
744 vec!["return".into_cow(), "unwind".into_cow()],
745 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
746 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
747 Call { destination: None, cleanup: None, .. } => vec![],
748 DropAndReplace { unwind: None, .. } |
749 Drop { unwind: None, .. } => vec!["return".into_cow()],
750 DropAndReplace { unwind: Some(_), .. } |
751 Drop { unwind: Some(_), .. } => {
752 vec!["return".into_cow(), "unwind".into_cow()]
754 Assert { cleanup: None, .. } => vec!["".into()],
756 vec!["success".into_cow(), "unwind".into_cow()]
761 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
762 pub enum AssertMessage<'tcx> {
770 ///////////////////////////////////////////////////////////////////////////
773 #[derive(Clone, RustcEncodable, RustcDecodable)]
774 pub struct Statement<'tcx> {
775 pub source_info: SourceInfo,
776 pub kind: StatementKind<'tcx>,
779 impl<'tcx> Statement<'tcx> {
780 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
781 /// invalidating statement indices in `Location`s.
782 pub fn make_nop(&mut self) {
783 self.kind = StatementKind::Nop
787 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
788 pub enum StatementKind<'tcx> {
789 /// Write the RHS Rvalue to the LHS Lvalue.
790 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
792 /// Write the discriminant for a variant to the enum Lvalue.
793 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
795 /// Start a live range for the storage of the local.
796 StorageLive(Lvalue<'tcx>),
798 /// End the current live range for the storage of the local.
799 StorageDead(Lvalue<'tcx>),
803 outputs: Vec<Lvalue<'tcx>>,
804 inputs: Vec<Operand<'tcx>>
807 /// No-op. Useful for deleting instructions without affecting statement indices.
811 impl<'tcx> Debug for Statement<'tcx> {
812 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
813 use self::StatementKind::*;
815 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
816 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
817 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
818 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
819 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
821 InlineAsm { ref asm, ref outputs, ref inputs } => {
822 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
824 Nop => write!(fmt, "nop"),
829 ///////////////////////////////////////////////////////////////////////////
832 /// A path to a value; something that can be evaluated without
833 /// changing or disturbing program state.
834 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
835 pub enum Lvalue<'tcx> {
839 /// static or static mut variable
840 Static(Box<Static<'tcx>>),
842 /// projection out of an lvalue (access a field, deref a pointer, etc)
843 Projection(Box<LvalueProjection<'tcx>>),
846 /// The def-id of a static, along with its normalized type (which is
847 /// stored to avoid requiring normalization when reading MIR).
848 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
849 pub struct Static<'tcx> {
854 impl_stable_hash_for!(struct Static<'tcx> {
859 /// The `Projection` data structure defines things of the form `B.x`
860 /// or `*B` or `B[index]`. Note that it is parameterized because it is
861 /// shared between `Constant` and `Lvalue`. See the aliases
862 /// `LvalueProjection` etc below.
863 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
864 pub struct Projection<'tcx, B, V> {
866 pub elem: ProjectionElem<'tcx, V>,
869 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
870 pub enum ProjectionElem<'tcx, V> {
872 Field(Field, Ty<'tcx>),
875 /// These indices are generated by slice patterns. Easiest to explain
879 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
880 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
881 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
882 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
885 /// index or -index (in Python terms), depending on from_end
887 /// thing being indexed must be at least this long
889 /// counting backwards from end?
893 /// These indices are generated by slice patterns.
895 /// slice[from:-to] in Python terms.
901 /// "Downcast" to a variant of an ADT. Currently, we only introduce
902 /// this for ADTs with more than one variant. It may be better to
903 /// just introduce it always, or always for enums.
904 Downcast(&'tcx AdtDef, usize),
907 /// Alias for projections as they appear in lvalues, where the base is an lvalue
908 /// and the index is an operand.
909 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
911 /// Alias for projections as they appear in lvalues, where the base is an lvalue
912 /// and the index is an operand.
913 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
915 newtype_index!(Field, "field");
917 impl<'tcx> Lvalue<'tcx> {
918 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
919 self.elem(ProjectionElem::Field(f, ty))
922 pub fn deref(self) -> Lvalue<'tcx> {
923 self.elem(ProjectionElem::Deref)
926 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
927 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
930 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
931 self.elem(ProjectionElem::Index(index))
934 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
935 Lvalue::Projection(Box::new(LvalueProjection {
942 impl<'tcx> Debug for Lvalue<'tcx> {
943 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
947 Local(id) => write!(fmt, "{:?}", id),
948 Static(box self::Static { def_id, ty }) =>
949 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
950 Projection(ref data) =>
952 ProjectionElem::Downcast(ref adt_def, index) =>
953 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
954 ProjectionElem::Deref =>
955 write!(fmt, "(*{:?})", data.base),
956 ProjectionElem::Field(field, ty) =>
957 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
958 ProjectionElem::Index(ref index) =>
959 write!(fmt, "{:?}[{:?}]", data.base, index),
960 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
961 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
962 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
963 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
964 ProjectionElem::Subslice { from, to } if to == 0 =>
965 write!(fmt, "{:?}[{:?}:]", data.base, from),
966 ProjectionElem::Subslice { from, to } if from == 0 =>
967 write!(fmt, "{:?}[:-{:?}]", data.base, to),
968 ProjectionElem::Subslice { from, to } =>
969 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
977 ///////////////////////////////////////////////////////////////////////////
980 newtype_index!(VisibilityScope, "scope");
981 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
983 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
984 pub struct VisibilityScopeData {
986 pub parent_scope: Option<VisibilityScope>,
989 ///////////////////////////////////////////////////////////////////////////
992 /// These are values that can appear inside an rvalue (or an index
993 /// lvalue). They are intentionally limited to prevent rvalues from
994 /// being nested in one another.
995 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
996 pub enum Operand<'tcx> {
997 Consume(Lvalue<'tcx>),
998 Constant(Box<Constant<'tcx>>),
1001 impl<'tcx> Debug for Operand<'tcx> {
1002 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1003 use self::Operand::*;
1005 Constant(ref a) => write!(fmt, "{:?}", a),
1006 Consume(ref lv) => write!(fmt, "{:?}", lv),
1011 impl<'tcx> Operand<'tcx> {
1012 pub fn function_handle<'a>(
1013 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1015 substs: &'tcx Substs<'tcx>,
1018 Operand::Constant(box Constant {
1020 ty: tcx.type_of(def_id).subst(tcx, substs),
1021 literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1027 ///////////////////////////////////////////////////////////////////////////
1030 #[derive(Clone, RustcEncodable, RustcDecodable)]
1031 pub enum Rvalue<'tcx> {
1032 /// x (either a move or copy, depending on type of x)
1036 Repeat(Operand<'tcx>, ConstUsize),
1039 Ref(Region<'tcx>, BorrowKind, Lvalue<'tcx>),
1041 /// length of a [X] or [X;n] value
1044 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1046 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1047 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1049 UnaryOp(UnOp, Operand<'tcx>),
1051 /// Read the discriminant of an ADT.
1053 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1054 /// be defined to return, say, a 0) if ADT is not an enum.
1055 Discriminant(Lvalue<'tcx>),
1057 /// Creates an *uninitialized* Box
1060 /// Create an aggregate value, like a tuple or struct. This is
1061 /// only needed because we want to distinguish `dest = Foo { x:
1062 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1063 /// that `Foo` has a destructor. These rvalues can be optimized
1064 /// away after type-checking and before lowering.
1065 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1068 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1072 /// Convert unique, zero-sized type for a fn to fn()
1075 /// Convert non capturing closure to fn()
1078 /// Convert safe fn() to unsafe fn()
1081 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1082 /// trans must figure out the details once full monomorphization
1083 /// is known. For example, this could be used to cast from a
1084 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1085 /// (presuming `T: Trait`).
1089 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1090 pub enum AggregateKind<'tcx> {
1091 /// The type is of the element
1094 /// The second field is variant number (discriminant), it's equal to 0
1095 /// for struct and union expressions. The fourth field is active field
1096 /// number and is present only for union expressions.
1097 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1098 Closure(DefId, ClosureSubsts<'tcx>),
1101 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1103 /// The `+` operator (addition)
1105 /// The `-` operator (subtraction)
1107 /// The `*` operator (multiplication)
1109 /// The `/` operator (division)
1111 /// The `%` operator (modulus)
1113 /// The `^` operator (bitwise xor)
1115 /// The `&` operator (bitwise and)
1117 /// The `|` operator (bitwise or)
1119 /// The `<<` operator (shift left)
1121 /// The `>>` operator (shift right)
1123 /// The `==` operator (equality)
1125 /// The `<` operator (less than)
1127 /// The `<=` operator (less than or equal to)
1129 /// The `!=` operator (not equal to)
1131 /// The `>=` operator (greater than or equal to)
1133 /// The `>` operator (greater than)
1138 pub fn is_checkable(self) -> bool {
1141 Add | Sub | Mul | Shl | Shr => true,
1147 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1149 /// The `!` operator for logical inversion
1151 /// The `-` operator for negation
1155 impl<'tcx> Debug for Rvalue<'tcx> {
1156 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1157 use self::Rvalue::*;
1160 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1161 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1162 Len(ref a) => write!(fmt, "Len({:?})", a),
1163 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1164 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1165 CheckedBinaryOp(ref op, ref a, ref b) => {
1166 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1168 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1169 Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1170 Box(ref t) => write!(fmt, "Box({:?})", t),
1171 Ref(_, borrow_kind, ref lv) => {
1172 let kind_str = match borrow_kind {
1173 BorrowKind::Shared => "",
1174 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1176 write!(fmt, "&{}{:?}", kind_str, lv)
1179 Aggregate(ref kind, ref lvs) => {
1180 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1181 let mut tuple_fmt = fmt.debug_tuple("");
1183 tuple_fmt.field(lv);
1189 AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1191 AggregateKind::Tuple => {
1193 0 => write!(fmt, "()"),
1194 1 => write!(fmt, "({:?},)", lvs[0]),
1195 _ => fmt_tuple(fmt, lvs),
1199 AggregateKind::Adt(adt_def, variant, substs, _) => {
1200 let variant_def = &adt_def.variants[variant];
1202 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1204 match variant_def.ctor_kind {
1205 CtorKind::Const => Ok(()),
1206 CtorKind::Fn => fmt_tuple(fmt, lvs),
1207 CtorKind::Fictive => {
1208 let mut struct_fmt = fmt.debug_struct("");
1209 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1210 struct_fmt.field(&field.name.as_str(), lv);
1217 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1218 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1219 let name = format!("[closure@{:?}]", tcx.hir.span(node_id));
1220 let mut struct_fmt = fmt.debug_struct(&name);
1222 tcx.with_freevars(node_id, |freevars| {
1223 for (freevar, lv) in freevars.iter().zip(lvs) {
1224 let def_id = freevar.def.def_id();
1225 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1226 let var_name = tcx.local_var_name_str(var_id);
1227 struct_fmt.field(&var_name, lv);
1233 write!(fmt, "[closure]")
1242 ///////////////////////////////////////////////////////////////////////////
1245 /// Two constants are equal if they are the same constant. Note that
1246 /// this does not necessarily mean that they are "==" in Rust -- in
1247 /// particular one must be wary of `NaN`!
1249 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1250 pub struct Constant<'tcx> {
1253 pub literal: Literal<'tcx>,
1256 newtype_index!(Promoted, "promoted");
1258 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1259 pub enum Literal<'tcx> {
1262 substs: &'tcx Substs<'tcx>,
1265 value: ConstVal<'tcx>,
1268 // Index into the `promoted` vector of `Mir`.
1273 impl<'tcx> Debug for Constant<'tcx> {
1274 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1275 write!(fmt, "{:?}", self.literal)
1279 impl<'tcx> Debug for Literal<'tcx> {
1280 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1281 use self::Literal::*;
1283 Item { def_id, substs } => {
1284 ppaux::parameterized(fmt, substs, def_id, &[])
1286 Value { ref value } => {
1287 write!(fmt, "const ")?;
1288 fmt_const_val(fmt, value)
1290 Promoted { index } => {
1291 write!(fmt, "{:?}", index)
1297 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1298 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1299 use middle::const_val::ConstVal::*;
1301 Float(f) => write!(fmt, "{:?}", f),
1302 Integral(n) => write!(fmt, "{}", n),
1303 Str(ref s) => write!(fmt, "{:?}", s),
1304 ByteStr(ref bytes) => {
1305 let escaped: String = bytes
1307 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1309 write!(fmt, "b\"{}\"", escaped)
1311 Bool(b) => write!(fmt, "{:?}", b),
1312 Char(c) => write!(fmt, "{:?}", c),
1314 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1315 Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1316 bug!("ConstVal `{:?}` should not be in MIR", const_val),
1320 fn item_path_str(def_id: DefId) -> String {
1321 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1324 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1326 type Node = BasicBlock;
1328 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1330 fn start_node(&self) -> Self::Node { START_BLOCK }
1332 fn predecessors<'graph>(&'graph self, node: Self::Node)
1333 -> <Self as GraphPredecessors<'graph>>::Iter
1335 self.predecessors_for(node).clone().into_iter()
1337 fn successors<'graph>(&'graph self, node: Self::Node)
1338 -> <Self as GraphSuccessors<'graph>>::Iter
1340 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1344 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1345 type Item = BasicBlock;
1346 type Iter = IntoIter<BasicBlock>;
1349 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1350 type Item = BasicBlock;
1351 type Iter = IntoIter<BasicBlock>;
1354 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1355 pub struct Location {
1356 /// the location is within this block
1357 pub block: BasicBlock,
1359 /// the location is the start of the this statement; or, if `statement_index`
1360 /// == num-statements, then the start of the terminator.
1361 pub statement_index: usize,
1364 impl fmt::Debug for Location {
1365 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1366 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1371 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1372 if self.block == other.block {
1373 self.statement_index <= other.statement_index
1375 dominators.is_dominated_by(other.block, self.block)
1382 * TypeFoldable implementations for MIR types
1385 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1386 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1388 basic_blocks: self.basic_blocks.fold_with(folder),
1389 visibility_scopes: self.visibility_scopes.clone(),
1390 promoted: self.promoted.fold_with(folder),
1391 return_ty: self.return_ty.fold_with(folder),
1392 local_decls: self.local_decls.fold_with(folder),
1393 arg_count: self.arg_count,
1394 upvar_decls: self.upvar_decls.clone(),
1395 spread_arg: self.spread_arg,
1397 cache: cache::Cache::new()
1401 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1402 self.basic_blocks.visit_with(visitor) ||
1403 self.promoted.visit_with(visitor) ||
1404 self.return_ty.visit_with(visitor) ||
1405 self.local_decls.visit_with(visitor)
1409 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1410 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1412 ty: self.ty.fold_with(folder),
1417 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1418 self.ty.visit_with(visitor)
1422 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1423 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1425 statements: self.statements.fold_with(folder),
1426 terminator: self.terminator.fold_with(folder),
1427 is_cleanup: self.is_cleanup
1431 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1432 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1436 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1437 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1438 use mir::StatementKind::*;
1440 let kind = match self.kind {
1441 Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1442 SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1443 lvalue: lvalue.fold_with(folder),
1444 variant_index: variant_index
1446 StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1447 StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1448 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1450 outputs: outputs.fold_with(folder),
1451 inputs: inputs.fold_with(folder)
1456 source_info: self.source_info,
1461 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1462 use mir::StatementKind::*;
1465 Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1466 SetDiscriminant { ref lvalue, .. } |
1467 StorageLive(ref lvalue) |
1468 StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1469 InlineAsm { ref outputs, ref inputs, .. } =>
1470 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1476 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1477 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1478 use mir::TerminatorKind::*;
1480 let kind = match self.kind {
1481 Goto { target } => Goto { target: target },
1482 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1483 discr: discr.fold_with(folder),
1484 switch_ty: switch_ty.fold_with(folder),
1485 values: values.clone(),
1486 targets: targets.clone()
1488 Drop { ref location, target, unwind } => Drop {
1489 location: location.fold_with(folder),
1493 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1494 location: location.fold_with(folder),
1495 value: value.fold_with(folder),
1499 Call { ref func, ref args, ref destination, cleanup } => {
1500 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1501 (loc.fold_with(folder), dest)
1505 func: func.fold_with(folder),
1506 args: args.fold_with(folder),
1511 Assert { ref cond, expected, ref msg, target, cleanup } => {
1512 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1513 AssertMessage::BoundsCheck {
1514 len: len.fold_with(folder),
1515 index: index.fold_with(folder),
1521 cond: cond.fold_with(folder),
1530 Unreachable => Unreachable,
1533 source_info: self.source_info,
1538 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1539 use mir::TerminatorKind::*;
1542 SwitchInt { ref discr, switch_ty, .. } =>
1543 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1544 Drop { ref location, ..} => location.visit_with(visitor),
1545 DropAndReplace { ref location, ref value, ..} =>
1546 location.visit_with(visitor) || value.visit_with(visitor),
1547 Call { ref func, ref args, ref destination, .. } => {
1548 let dest = if let Some((ref loc, _)) = *destination {
1549 loc.visit_with(visitor)
1551 dest || func.visit_with(visitor) || args.visit_with(visitor)
1553 Assert { ref cond, ref msg, .. } => {
1554 if cond.visit_with(visitor) {
1555 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1556 len.visit_with(visitor) || index.visit_with(visitor)
1567 Unreachable => false
1572 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1573 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1575 &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1580 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1581 if let &Lvalue::Projection(ref p) = self {
1582 p.visit_with(visitor)
1589 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1590 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1593 Use(ref op) => Use(op.fold_with(folder)),
1594 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1595 Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1596 Len(ref lval) => Len(lval.fold_with(folder)),
1597 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1598 BinaryOp(op, ref rhs, ref lhs) =>
1599 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1600 CheckedBinaryOp(op, ref rhs, ref lhs) =>
1601 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1602 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1603 Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1604 Box(ty) => Box(ty.fold_with(folder)),
1605 Aggregate(ref kind, ref fields) => {
1606 let kind = box match **kind {
1607 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1608 AggregateKind::Tuple => AggregateKind::Tuple,
1609 AggregateKind::Adt(def, v, substs, n) =>
1610 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1611 AggregateKind::Closure(id, substs) =>
1612 AggregateKind::Closure(id, substs.fold_with(folder))
1614 Aggregate(kind, fields.fold_with(folder))
1619 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1622 Use(ref op) => op.visit_with(visitor),
1623 Repeat(ref op, _) => op.visit_with(visitor),
1624 Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1625 Len(ref lval) => lval.visit_with(visitor),
1626 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1627 BinaryOp(_, ref rhs, ref lhs) |
1628 CheckedBinaryOp(_, ref rhs, ref lhs) =>
1629 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1630 UnaryOp(_, ref val) => val.visit_with(visitor),
1631 Discriminant(ref lval) => lval.visit_with(visitor),
1632 Box(ty) => ty.visit_with(visitor),
1633 Aggregate(ref kind, ref fields) => {
1635 AggregateKind::Array(ty) => ty.visit_with(visitor),
1636 AggregateKind::Tuple => false,
1637 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1638 AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1639 }) || fields.visit_with(visitor)
1645 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1646 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1648 Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1649 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1653 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1655 Operand::Consume(ref lval) => lval.visit_with(visitor),
1656 Operand::Constant(ref c) => c.visit_with(visitor)
1661 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1662 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1664 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1665 use mir::ProjectionElem::*;
1667 let base = self.base.fold_with(folder);
1668 let elem = match self.elem {
1670 Field(f, ty) => Field(f, ty.fold_with(folder)),
1671 Index(ref v) => Index(v.fold_with(folder)),
1672 ref elem => elem.clone()
1681 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1682 use mir::ProjectionElem::*;
1684 self.base.visit_with(visitor) ||
1686 Field(_, ty) => ty.visit_with(visitor),
1687 Index(ref v) => v.visit_with(visitor),
1693 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1694 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1696 span: self.span.clone(),
1697 ty: self.ty.fold_with(folder),
1698 literal: self.literal.fold_with(folder)
1701 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1702 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1706 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1707 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1709 Literal::Item { def_id, substs } => Literal::Item {
1711 substs: substs.fold_with(folder)
1716 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1718 Literal::Item { substs, .. } => substs.visit_with(visitor),