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 use graphviz::IntoCow;
12 use middle::const_val::ConstVal;
13 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
14 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
15 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
16 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
17 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
18 use hir::def::CtorKind;
19 use hir::def_id::DefId;
20 use ty::subst::{Subst, Substs};
21 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
22 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
24 use rustc_back::slice;
27 use std::borrow::{Cow};
29 use std::fmt::{self, Debug, Formatter, Write};
31 use std::ops::{Index, IndexMut};
32 use std::vec::IntoIter;
33 use syntax::ast::Name;
42 macro_rules! newtype_index {
43 ($name:ident, $debug_name:expr) => (
44 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
45 RustcEncodable, RustcDecodable)]
46 pub struct $name(u32);
49 fn new(value: usize) -> Self {
50 assert!(value < (u32::MAX) as usize);
53 fn index(self) -> usize {
58 impl Debug for $name {
59 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
60 write!(fmt, "{}{}", $debug_name, self.0)
66 /// Lowered representation of a single function.
67 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
68 pub struct Mir<'tcx> {
69 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
70 /// that indexes into this vector.
71 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
73 /// List of visibility (lexical) scopes; these are referenced by statements
74 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
75 pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
77 /// Rvalues promoted from this function, such as borrows of constants.
78 /// Each of them is the Mir of a constant with the fn's type parameters
79 /// in scope, but a separate set of locals.
80 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
82 /// Return type of the function.
83 pub return_ty: Ty<'tcx>,
85 /// Declarations of locals.
87 /// The first local is the return value pointer, followed by `arg_count`
88 /// locals for the function arguments, followed by any user-declared
89 /// variables and temporaries.
90 pub local_decls: IndexVec<Local, LocalDecl<'tcx>>,
92 /// Number of arguments this function takes.
94 /// Starting at local 1, `arg_count` locals will be provided by the caller
95 /// and can be assumed to be initialized.
97 /// If this MIR was built for a constant, this will be 0.
100 /// Names and capture modes of all the closure upvars, assuming
101 /// the first argument is either the closure or a reference to it.
102 pub upvar_decls: Vec<UpvarDecl>,
104 /// Mark an argument local (which must be a tuple) as getting passed as
105 /// its individual components at the LLVM level.
107 /// This is used for the "rust-call" ABI.
108 pub spread_arg: Option<Local>,
110 /// A span representing this MIR, for error reporting
113 /// A cache for various calculations
117 /// where execution begins
118 pub const START_BLOCK: BasicBlock = BasicBlock(0);
120 impl<'tcx> Mir<'tcx> {
121 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
122 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
123 promoted: IndexVec<Promoted, Mir<'tcx>>,
125 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
127 upvar_decls: Vec<UpvarDecl>,
130 // We need `arg_count` locals, and one for the return pointer
131 assert!(local_decls.len() >= arg_count + 1,
132 "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
133 assert_eq!(local_decls[RETURN_POINTER].ty, return_ty);
136 basic_blocks: basic_blocks,
137 visibility_scopes: visibility_scopes,
139 return_ty: return_ty,
140 local_decls: local_decls,
141 arg_count: arg_count,
142 upvar_decls: upvar_decls,
145 cache: cache::Cache::new()
150 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
155 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
156 self.cache.invalidate();
157 &mut self.basic_blocks
161 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
162 self.cache.predecessors(self)
166 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
167 Ref::map(self.predecessors(), |p| &p[bb])
171 pub fn dominators(&self) -> Dominators<BasicBlock> {
176 pub fn local_kind(&self, local: Local) -> LocalKind {
177 let index = local.0 as usize;
179 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
180 "return pointer should be mutable");
182 LocalKind::ReturnPointer
183 } else if index < self.arg_count + 1 {
185 } else if self.local_decls[local].name.is_some() {
188 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
189 "temp should be mutable");
195 /// Returns an iterator over all temporaries.
197 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
198 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
199 let local = Local::new(index);
200 if self.local_decls[local].source_info.is_none() {
208 /// Returns an iterator over all user-declared locals.
210 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
211 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
212 let local = Local::new(index);
213 if self.local_decls[local].source_info.is_none() {
221 /// Returns an iterator over all function arguments.
223 pub fn args_iter(&self) -> impl Iterator<Item=Local> {
224 let arg_count = self.arg_count;
225 (1..arg_count+1).map(Local::new)
228 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
229 /// locals that are neither arguments nor the return pointer).
231 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
232 let arg_count = self.arg_count;
233 let local_count = self.local_decls.len();
234 (arg_count+1..local_count).map(Local::new)
237 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
238 /// invalidating statement indices in `Location`s.
239 pub fn make_statement_nop(&mut self, location: Location) {
240 let block = &mut self[location.block];
241 debug_assert!(location.statement_index < block.statements.len());
242 block.statements[location.statement_index].make_nop()
246 impl_stable_hash_for!(struct Mir<'tcx> {
259 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
260 type Output = BasicBlockData<'tcx>;
263 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
264 &self.basic_blocks()[index]
268 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
270 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
271 &mut self.basic_blocks_mut()[index]
275 /// Grouped information about the source code origin of a MIR entity.
276 /// Intended to be inspected by diagnostics and debuginfo.
277 /// Most passes can work with it as a whole, within a single function.
278 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
279 pub struct SourceInfo {
280 /// Source span for the AST pertaining to this MIR entity.
283 /// The lexical visibility scope, i.e. which bindings can be seen.
284 pub scope: VisibilityScope
287 ///////////////////////////////////////////////////////////////////////////
288 // Mutability and borrow kinds
290 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
291 pub enum Mutability {
296 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
297 pub enum BorrowKind {
298 /// Data must be immutable and is aliasable.
301 /// Data must be immutable but not aliasable. This kind of borrow
302 /// cannot currently be expressed by the user and is used only in
303 /// implicit closure bindings. It is needed when you the closure
304 /// is borrowing or mutating a mutable referent, e.g.:
306 /// let x: &mut isize = ...;
307 /// let y = || *x += 5;
309 /// If we were to try to translate this closure into a more explicit
310 /// form, we'd encounter an error with the code as written:
312 /// struct Env { x: & &mut isize }
313 /// let x: &mut isize = ...;
314 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
315 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
317 /// This is then illegal because you cannot mutate a `&mut` found
318 /// in an aliasable location. To solve, you'd have to translate with
319 /// an `&mut` borrow:
321 /// struct Env { x: & &mut isize }
322 /// let x: &mut isize = ...;
323 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
324 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
326 /// Now the assignment to `**env.x` is legal, but creating a
327 /// mutable pointer to `x` is not because `x` is not mutable. We
328 /// could fix this by declaring `x` as `let mut x`. This is ok in
329 /// user code, if awkward, but extra weird for closures, since the
330 /// borrow is hidden.
332 /// So we introduce a "unique imm" borrow -- the referent is
333 /// immutable, but not aliasable. This solves the problem. For
334 /// simplicity, we don't give users the way to express this
335 /// borrow, it's just used when translating closures.
338 /// Data is mutable and not aliasable.
342 ///////////////////////////////////////////////////////////////////////////
343 // Variables and temps
345 newtype_index!(Local, "_");
347 pub const RETURN_POINTER: Local = Local(0);
349 /// Classifies locals into categories. See `Mir::local_kind`.
350 #[derive(PartialEq, Eq, Debug)]
352 /// User-declared variable binding
354 /// Compiler-introduced temporary
356 /// Function argument
358 /// Location of function's return value
364 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
365 /// argument, or the return pointer.
366 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
367 pub struct LocalDecl<'tcx> {
368 /// `let mut x` vs `let x`.
370 /// Temporaries and the return pointer are always mutable.
371 pub mutability: Mutability,
373 /// Type of this local.
376 /// Name of the local, used in debuginfo and pretty-printing.
378 /// Note that function arguments can also have this set to `Some(_)`
379 /// to generate better debuginfo.
380 pub name: Option<Name>,
382 /// For user-declared variables, stores their source information.
384 /// For temporaries, this is `None`.
386 /// This is the primary way to differentiate between user-declared
387 /// variables and compiler-generated temporaries.
388 pub source_info: Option<SourceInfo>,
391 impl<'tcx> LocalDecl<'tcx> {
392 /// Create a new `LocalDecl` for a temporary.
394 pub fn new_temp(ty: Ty<'tcx>) -> Self {
396 mutability: Mutability::Mut,
403 /// Builds a `LocalDecl` for the return pointer.
405 /// This must be inserted into the `local_decls` list as the first local.
407 pub fn new_return_pointer(return_ty: Ty) -> LocalDecl {
409 mutability: Mutability::Mut,
412 name: None, // FIXME maybe we do want some name here?
417 /// A closure capture, with its name and mode.
418 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
419 pub struct UpvarDecl {
420 pub debug_name: Name,
422 /// If true, the capture is behind a reference.
426 ///////////////////////////////////////////////////////////////////////////
429 newtype_index!(BasicBlock, "bb");
431 ///////////////////////////////////////////////////////////////////////////
432 // BasicBlockData and Terminator
434 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
435 pub struct BasicBlockData<'tcx> {
436 /// List of statements in this block.
437 pub statements: Vec<Statement<'tcx>>,
439 /// Terminator for this block.
441 /// NB. This should generally ONLY be `None` during construction.
442 /// Therefore, you should generally access it via the
443 /// `terminator()` or `terminator_mut()` methods. The only
444 /// exception is that certain passes, such as `simplify_cfg`, swap
445 /// out the terminator temporarily with `None` while they continue
446 /// to recurse over the set of basic blocks.
447 pub terminator: Option<Terminator<'tcx>>,
449 /// If true, this block lies on an unwind path. This is used
450 /// during trans where distinct kinds of basic blocks may be
451 /// generated (particularly for MSVC cleanup). Unwind blocks must
452 /// only branch to other unwind blocks.
453 pub is_cleanup: bool,
456 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
457 pub struct Terminator<'tcx> {
458 pub source_info: SourceInfo,
459 pub kind: TerminatorKind<'tcx>
462 #[derive(Clone, RustcEncodable, RustcDecodable)]
463 pub enum TerminatorKind<'tcx> {
464 /// block should have one successor in the graph; we jump there
469 /// operand evaluates to an integer; jump depending on its value
470 /// to one of the targets, and otherwise fallback to `otherwise`
472 /// discriminant value being tested
473 discr: Operand<'tcx>,
475 /// type of value being tested
478 /// Possible values. The locations to branch to in each case
479 /// are found in the corresponding indices from the `targets` vector.
480 values: Cow<'tcx, [ConstInt]>,
482 /// Possible branch sites. The last element of this vector is used
483 /// for the otherwise branch, so targets.len() == values.len() + 1
485 // This invariant is quite non-obvious and also could be improved.
486 // One way to make this invariant is to have something like this instead:
488 // branches: Vec<(ConstInt, BasicBlock)>,
489 // otherwise: Option<BasicBlock> // exhaustive if None
491 // However we’ve decided to keep this as-is until we figure a case
492 // where some other approach seems to be strictly better than other.
493 targets: Vec<BasicBlock>,
496 /// Indicates that the landing pad is finished and unwinding should
497 /// continue. Emitted by build::scope::diverge_cleanup.
500 /// Indicates a normal return. The return pointer lvalue should
501 /// have been filled in by now. This should occur at most once.
504 /// Indicates a terminator that can never be reached.
509 location: Lvalue<'tcx>,
511 unwind: Option<BasicBlock>
514 /// Drop the Lvalue and assign the new value over it
516 location: Lvalue<'tcx>,
517 value: Operand<'tcx>,
519 unwind: Option<BasicBlock>,
522 /// Block ends with a call of a converging function
524 /// The function that’s being called
526 /// Arguments the function is called with
527 args: Vec<Operand<'tcx>>,
528 /// Destination for the return value. If some, the call is converging.
529 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
530 /// Cleanups to be done if the call unwinds.
531 cleanup: Option<BasicBlock>
534 /// Jump to the target if the condition has the expected value,
535 /// otherwise panic with a message and a cleanup target.
539 msg: AssertMessage<'tcx>,
541 cleanup: Option<BasicBlock>
545 impl<'tcx> Terminator<'tcx> {
546 pub fn successors(&self) -> Cow<[BasicBlock]> {
547 self.kind.successors()
550 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
551 self.kind.successors_mut()
555 impl<'tcx> TerminatorKind<'tcx> {
556 pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
557 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
558 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
559 TerminatorKind::SwitchInt {
561 switch_ty: tcx.types.bool,
562 values: From::from(BOOL_SWITCH_FALSE),
567 pub fn successors(&self) -> Cow<[BasicBlock]> {
568 use self::TerminatorKind::*;
570 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
571 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
572 Resume => (&[]).into_cow(),
573 Return => (&[]).into_cow(),
574 Unreachable => (&[]).into_cow(),
575 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
576 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
577 slice::ref_slice(t).into_cow(),
578 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
579 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
580 DropAndReplace { target, unwind: Some(unwind), .. } |
581 Drop { target, unwind: Some(unwind), .. } => {
582 vec![target, unwind].into_cow()
584 DropAndReplace { ref target, unwind: None, .. } |
585 Drop { ref target, unwind: None, .. } => {
586 slice::ref_slice(target).into_cow()
588 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
589 Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
593 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
594 // `Vec<&mut BasicBlock>` would look like in the first place.
595 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
596 use self::TerminatorKind::*;
598 Goto { target: ref mut b } => vec![b],
599 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
600 Resume => Vec::new(),
601 Return => Vec::new(),
602 Unreachable => Vec::new(),
603 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
604 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
605 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
606 Call { destination: None, cleanup: None, .. } => vec![],
607 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
608 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
609 DropAndReplace { ref mut target, unwind: None, .. } |
610 Drop { ref mut target, unwind: None, .. } => {
613 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
614 Assert { ref mut target, .. } => vec![target]
619 impl<'tcx> BasicBlockData<'tcx> {
620 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
623 terminator: terminator,
628 /// Accessor for terminator.
630 /// Terminator may not be None after construction of the basic block is complete. This accessor
631 /// provides a convenience way to reach the terminator.
632 pub fn terminator(&self) -> &Terminator<'tcx> {
633 self.terminator.as_ref().expect("invalid terminator state")
636 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
637 self.terminator.as_mut().expect("invalid terminator state")
641 impl<'tcx> Debug for TerminatorKind<'tcx> {
642 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
644 let successors = self.successors();
645 let labels = self.fmt_successor_labels();
646 assert_eq!(successors.len(), labels.len());
648 match successors.len() {
651 1 => write!(fmt, " -> {:?}", successors[0]),
654 write!(fmt, " -> [")?;
655 for (i, target) in successors.iter().enumerate() {
659 write!(fmt, "{}: {:?}", labels[i], target)?;
668 impl<'tcx> TerminatorKind<'tcx> {
669 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
670 /// successor basic block, if any. The only information not inlcuded is the list of possible
671 /// successors, which may be rendered differently between the text and the graphviz format.
672 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
673 use self::TerminatorKind::*;
675 Goto { .. } => write!(fmt, "goto"),
676 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
677 Return => write!(fmt, "return"),
678 Resume => write!(fmt, "resume"),
679 Unreachable => write!(fmt, "unreachable"),
680 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
681 DropAndReplace { ref location, ref value, .. } =>
682 write!(fmt, "replace({:?} <- {:?})", location, value),
683 Call { ref func, ref args, ref destination, .. } => {
684 if let Some((ref destination, _)) = *destination {
685 write!(fmt, "{:?} = ", destination)?;
687 write!(fmt, "{:?}(", func)?;
688 for (index, arg) in args.iter().enumerate() {
692 write!(fmt, "{:?}", arg)?;
696 Assert { ref cond, expected, ref msg, .. } => {
697 write!(fmt, "assert(")?;
701 write!(fmt, "{:?}, ", cond)?;
704 AssertMessage::BoundsCheck { ref len, ref index } => {
705 write!(fmt, "{:?}, {:?}, {:?}",
706 "index out of bounds: the len is {} but the index is {}",
709 AssertMessage::Math(ref err) => {
710 write!(fmt, "{:?}", err.description())?;
719 /// Return the list of labels for the edges to the successor basic blocks.
720 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
721 use self::TerminatorKind::*;
723 Return | Resume | Unreachable => vec![],
724 Goto { .. } => vec!["".into()],
725 SwitchInt { ref values, .. } => {
728 let mut buf = String::new();
729 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
732 .chain(iter::once(String::from("otherwise").into()))
735 Call { destination: Some(_), cleanup: Some(_), .. } =>
736 vec!["return".into_cow(), "unwind".into_cow()],
737 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
738 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
739 Call { destination: None, cleanup: None, .. } => vec![],
740 DropAndReplace { unwind: None, .. } |
741 Drop { unwind: None, .. } => vec!["return".into_cow()],
742 DropAndReplace { unwind: Some(_), .. } |
743 Drop { unwind: Some(_), .. } => {
744 vec!["return".into_cow(), "unwind".into_cow()]
746 Assert { cleanup: None, .. } => vec!["".into()],
748 vec!["success".into_cow(), "unwind".into_cow()]
753 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
754 pub enum AssertMessage<'tcx> {
762 ///////////////////////////////////////////////////////////////////////////
765 #[derive(Clone, RustcEncodable, RustcDecodable)]
766 pub struct Statement<'tcx> {
767 pub source_info: SourceInfo,
768 pub kind: StatementKind<'tcx>,
771 impl<'tcx> Statement<'tcx> {
772 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
773 /// invalidating statement indices in `Location`s.
774 pub fn make_nop(&mut self) {
775 self.kind = StatementKind::Nop
779 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
780 pub enum StatementKind<'tcx> {
781 /// Write the RHS Rvalue to the LHS Lvalue.
782 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
784 /// Write the discriminant for a variant to the enum Lvalue.
785 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
787 /// Start a live range for the storage of the local.
788 StorageLive(Lvalue<'tcx>),
790 /// End the current live range for the storage of the local.
791 StorageDead(Lvalue<'tcx>),
795 outputs: Vec<Lvalue<'tcx>>,
796 inputs: Vec<Operand<'tcx>>
799 /// No-op. Useful for deleting instructions without affecting statement indices.
803 impl<'tcx> Debug for Statement<'tcx> {
804 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
805 use self::StatementKind::*;
807 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
808 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
809 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
810 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
811 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
813 InlineAsm { ref asm, ref outputs, ref inputs } => {
814 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
816 Nop => write!(fmt, "nop"),
821 ///////////////////////////////////////////////////////////////////////////
824 /// A path to a value; something that can be evaluated without
825 /// changing or disturbing program state.
826 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
827 pub enum Lvalue<'tcx> {
831 /// static or static mut variable
832 Static(Box<Static<'tcx>>),
834 /// projection out of an lvalue (access a field, deref a pointer, etc)
835 Projection(Box<LvalueProjection<'tcx>>),
838 /// The def-id of a static, along with its normalized type (which is
839 /// stored to avoid requiring normalization when reading MIR).
840 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
841 pub struct Static<'tcx> {
846 impl_stable_hash_for!(struct Static<'tcx> {
851 /// The `Projection` data structure defines things of the form `B.x`
852 /// or `*B` or `B[index]`. Note that it is parameterized because it is
853 /// shared between `Constant` and `Lvalue`. See the aliases
854 /// `LvalueProjection` etc below.
855 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
856 pub struct Projection<'tcx, B, V> {
858 pub elem: ProjectionElem<'tcx, V>,
861 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
862 pub enum ProjectionElem<'tcx, V> {
864 Field(Field, Ty<'tcx>),
867 /// These indices are generated by slice patterns. Easiest to explain
871 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
872 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
873 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
874 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
877 /// index or -index (in Python terms), depending on from_end
879 /// thing being indexed must be at least this long
881 /// counting backwards from end?
885 /// These indices are generated by slice patterns.
887 /// slice[from:-to] in Python terms.
893 /// "Downcast" to a variant of an ADT. Currently, we only introduce
894 /// this for ADTs with more than one variant. It may be better to
895 /// just introduce it always, or always for enums.
896 Downcast(&'tcx AdtDef, usize),
899 /// Alias for projections as they appear in lvalues, where the base is an lvalue
900 /// and the index is an operand.
901 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
903 /// Alias for projections as they appear in lvalues, where the base is an lvalue
904 /// and the index is an operand.
905 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
907 newtype_index!(Field, "field");
909 impl<'tcx> Lvalue<'tcx> {
910 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
911 self.elem(ProjectionElem::Field(f, ty))
914 pub fn deref(self) -> Lvalue<'tcx> {
915 self.elem(ProjectionElem::Deref)
918 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
919 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
922 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
923 self.elem(ProjectionElem::Index(index))
926 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
927 Lvalue::Projection(Box::new(LvalueProjection {
934 impl<'tcx> Debug for Lvalue<'tcx> {
935 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
939 Local(id) => write!(fmt, "{:?}", id),
940 Static(box self::Static { def_id, ty }) =>
941 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
942 Projection(ref data) =>
944 ProjectionElem::Downcast(ref adt_def, index) =>
945 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
946 ProjectionElem::Deref =>
947 write!(fmt, "(*{:?})", data.base),
948 ProjectionElem::Field(field, ty) =>
949 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
950 ProjectionElem::Index(ref index) =>
951 write!(fmt, "{:?}[{:?}]", data.base, index),
952 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
953 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
954 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
955 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
956 ProjectionElem::Subslice { from, to } if to == 0 =>
957 write!(fmt, "{:?}[{:?}:]", data.base, from),
958 ProjectionElem::Subslice { from, to } if from == 0 =>
959 write!(fmt, "{:?}[:-{:?}]", data.base, to),
960 ProjectionElem::Subslice { from, to } =>
961 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
969 ///////////////////////////////////////////////////////////////////////////
972 newtype_index!(VisibilityScope, "scope");
973 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
975 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
976 pub struct VisibilityScopeData {
978 pub parent_scope: Option<VisibilityScope>,
981 ///////////////////////////////////////////////////////////////////////////
984 /// These are values that can appear inside an rvalue (or an index
985 /// lvalue). They are intentionally limited to prevent rvalues from
986 /// being nested in one another.
987 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
988 pub enum Operand<'tcx> {
989 Consume(Lvalue<'tcx>),
990 Constant(Constant<'tcx>),
993 impl<'tcx> Debug for Operand<'tcx> {
994 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
995 use self::Operand::*;
997 Constant(ref a) => write!(fmt, "{:?}", a),
998 Consume(ref lv) => write!(fmt, "{:?}", lv),
1003 impl<'tcx> Operand<'tcx> {
1004 pub fn function_handle<'a>(
1005 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1007 substs: &'tcx Substs<'tcx>,
1010 Operand::Constant(Constant {
1012 ty: tcx.item_type(def_id).subst(tcx, substs),
1013 literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1019 ///////////////////////////////////////////////////////////////////////////
1022 #[derive(Clone, RustcEncodable, RustcDecodable)]
1023 pub enum Rvalue<'tcx> {
1024 /// x (either a move or copy, depending on type of x)
1028 Repeat(Operand<'tcx>, ConstUsize),
1031 Ref(&'tcx Region, BorrowKind, Lvalue<'tcx>),
1033 /// length of a [X] or [X;n] value
1036 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1038 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1039 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1041 UnaryOp(UnOp, Operand<'tcx>),
1043 /// Read the discriminant of an ADT.
1045 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1046 /// be defined to return, say, a 0) if ADT is not an enum.
1047 Discriminant(Lvalue<'tcx>),
1049 /// Creates an *uninitialized* Box
1052 /// Create an aggregate value, like a tuple or struct. This is
1053 /// only needed because we want to distinguish `dest = Foo { x:
1054 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1055 /// that `Foo` has a destructor. These rvalues can be optimized
1056 /// away after type-checking and before lowering.
1057 Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
1060 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1064 /// Convert unique, zero-sized type for a fn to fn()
1067 /// Convert non capturing closure to fn()
1070 /// Convert safe fn() to unsafe fn()
1073 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1074 /// trans must figure out the details once full monomorphization
1075 /// is known. For example, this could be used to cast from a
1076 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1077 /// (presuming `T: Trait`).
1081 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1082 pub enum AggregateKind<'tcx> {
1083 /// The type is of the element
1086 /// The second field is variant number (discriminant), it's equal to 0
1087 /// for struct and union expressions. The fourth field is active field
1088 /// number and is present only for union expressions.
1089 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1090 Closure(DefId, ClosureSubsts<'tcx>),
1093 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1095 /// The `+` operator (addition)
1097 /// The `-` operator (subtraction)
1099 /// The `*` operator (multiplication)
1101 /// The `/` operator (division)
1103 /// The `%` operator (modulus)
1105 /// The `^` operator (bitwise xor)
1107 /// The `&` operator (bitwise and)
1109 /// The `|` operator (bitwise or)
1111 /// The `<<` operator (shift left)
1113 /// The `>>` operator (shift right)
1115 /// The `==` operator (equality)
1117 /// The `<` operator (less than)
1119 /// The `<=` operator (less than or equal to)
1121 /// The `!=` operator (not equal to)
1123 /// The `>=` operator (greater than or equal to)
1125 /// The `>` operator (greater than)
1130 pub fn is_checkable(self) -> bool {
1133 Add | Sub | Mul | Shl | Shr => true,
1139 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1141 /// The `!` operator for logical inversion
1143 /// The `-` operator for negation
1147 impl<'tcx> Debug for Rvalue<'tcx> {
1148 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1149 use self::Rvalue::*;
1152 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1153 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1154 Len(ref a) => write!(fmt, "Len({:?})", a),
1155 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1156 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1157 CheckedBinaryOp(ref op, ref a, ref b) => {
1158 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1160 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1161 Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1162 Box(ref t) => write!(fmt, "Box({:?})", t),
1163 Ref(_, borrow_kind, ref lv) => {
1164 let kind_str = match borrow_kind {
1165 BorrowKind::Shared => "",
1166 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1168 write!(fmt, "&{}{:?}", kind_str, lv)
1171 Aggregate(ref kind, ref lvs) => {
1172 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1173 let mut tuple_fmt = fmt.debug_tuple("");
1175 tuple_fmt.field(lv);
1181 AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1183 AggregateKind::Tuple => {
1185 0 => write!(fmt, "()"),
1186 1 => write!(fmt, "({:?},)", lvs[0]),
1187 _ => fmt_tuple(fmt, lvs),
1191 AggregateKind::Adt(adt_def, variant, substs, _) => {
1192 let variant_def = &adt_def.variants[variant];
1194 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1196 match variant_def.ctor_kind {
1197 CtorKind::Const => Ok(()),
1198 CtorKind::Fn => fmt_tuple(fmt, lvs),
1199 CtorKind::Fictive => {
1200 let mut struct_fmt = fmt.debug_struct("");
1201 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1202 struct_fmt.field(&field.name.as_str(), lv);
1209 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1210 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1211 let name = format!("[closure@{:?}]", tcx.hir.span(node_id));
1212 let mut struct_fmt = fmt.debug_struct(&name);
1214 tcx.with_freevars(node_id, |freevars| {
1215 for (freevar, lv) in freevars.iter().zip(lvs) {
1216 let def_id = freevar.def.def_id();
1217 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1218 let var_name = tcx.local_var_name_str(var_id);
1219 struct_fmt.field(&var_name, lv);
1225 write!(fmt, "[closure]")
1234 ///////////////////////////////////////////////////////////////////////////
1237 /// Two constants are equal if they are the same constant. Note that
1238 /// this does not necessarily mean that they are "==" in Rust -- in
1239 /// particular one must be wary of `NaN`!
1241 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1242 pub struct Constant<'tcx> {
1245 pub literal: Literal<'tcx>,
1248 newtype_index!(Promoted, "promoted");
1250 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1251 pub enum Literal<'tcx> {
1254 substs: &'tcx Substs<'tcx>,
1257 value: ConstVal<'tcx>,
1260 // Index into the `promoted` vector of `Mir`.
1265 impl<'tcx> Debug for Constant<'tcx> {
1266 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1267 write!(fmt, "{:?}", self.literal)
1271 impl<'tcx> Debug for Literal<'tcx> {
1272 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1273 use self::Literal::*;
1275 Item { def_id, substs } => {
1276 ppaux::parameterized(fmt, substs, def_id, &[])
1278 Value { ref value } => {
1279 write!(fmt, "const ")?;
1280 fmt_const_val(fmt, value)
1282 Promoted { index } => {
1283 write!(fmt, "{:?}", index)
1289 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1290 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1291 use middle::const_val::ConstVal::*;
1293 Float(f) => write!(fmt, "{:?}", f),
1294 Integral(n) => write!(fmt, "{}", n),
1295 Str(ref s) => write!(fmt, "{:?}", s),
1296 ByteStr(ref bytes) => {
1297 let escaped: String = bytes
1299 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1301 write!(fmt, "b\"{}\"", escaped)
1303 Bool(b) => write!(fmt, "{:?}", b),
1304 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1305 Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1306 bug!("ConstVal `{:?}` should not be in MIR", const_val),
1307 Char(c) => write!(fmt, "{:?}", c),
1311 fn item_path_str(def_id: DefId) -> String {
1312 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1315 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1317 type Node = BasicBlock;
1319 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1321 fn start_node(&self) -> Self::Node { START_BLOCK }
1323 fn predecessors<'graph>(&'graph self, node: Self::Node)
1324 -> <Self as GraphPredecessors<'graph>>::Iter
1326 self.predecessors_for(node).clone().into_iter()
1328 fn successors<'graph>(&'graph self, node: Self::Node)
1329 -> <Self as GraphSuccessors<'graph>>::Iter
1331 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1335 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1336 type Item = BasicBlock;
1337 type Iter = IntoIter<BasicBlock>;
1340 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1341 type Item = BasicBlock;
1342 type Iter = IntoIter<BasicBlock>;
1345 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1346 pub struct Location {
1347 /// the location is within this block
1348 pub block: BasicBlock,
1350 /// the location is the start of the this statement; or, if `statement_index`
1351 /// == num-statements, then the start of the terminator.
1352 pub statement_index: usize,
1355 impl fmt::Debug for Location {
1356 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1357 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1362 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1363 if self.block == other.block {
1364 self.statement_index <= other.statement_index
1366 dominators.is_dominated_by(other.block, self.block)
1373 * TypeFoldable implementations for MIR types
1376 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1377 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1379 basic_blocks: self.basic_blocks.fold_with(folder),
1380 visibility_scopes: self.visibility_scopes.clone(),
1381 promoted: self.promoted.fold_with(folder),
1382 return_ty: self.return_ty.fold_with(folder),
1383 local_decls: self.local_decls.fold_with(folder),
1384 arg_count: self.arg_count,
1385 upvar_decls: self.upvar_decls.clone(),
1386 spread_arg: self.spread_arg,
1388 cache: cache::Cache::new()
1392 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1393 self.basic_blocks.visit_with(visitor) ||
1394 self.promoted.visit_with(visitor) ||
1395 self.return_ty.visit_with(visitor) ||
1396 self.local_decls.visit_with(visitor)
1400 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1401 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1403 ty: self.ty.fold_with(folder),
1408 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1409 self.ty.visit_with(visitor)
1413 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1414 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1416 statements: self.statements.fold_with(folder),
1417 terminator: self.terminator.fold_with(folder),
1418 is_cleanup: self.is_cleanup
1422 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1423 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1427 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1428 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1429 use mir::StatementKind::*;
1431 let kind = match self.kind {
1432 Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1433 SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1434 lvalue: lvalue.fold_with(folder),
1435 variant_index: variant_index
1437 StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1438 StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1439 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1441 outputs: outputs.fold_with(folder),
1442 inputs: inputs.fold_with(folder)
1447 source_info: self.source_info,
1452 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1453 use mir::StatementKind::*;
1456 Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1457 SetDiscriminant { ref lvalue, .. } |
1458 StorageLive(ref lvalue) |
1459 StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1460 InlineAsm { ref outputs, ref inputs, .. } =>
1461 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1467 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1468 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1469 use mir::TerminatorKind::*;
1471 let kind = match self.kind {
1472 Goto { target } => Goto { target: target },
1473 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1474 discr: discr.fold_with(folder),
1475 switch_ty: switch_ty.fold_with(folder),
1476 values: values.clone(),
1477 targets: targets.clone()
1479 Drop { ref location, target, unwind } => Drop {
1480 location: location.fold_with(folder),
1484 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1485 location: location.fold_with(folder),
1486 value: value.fold_with(folder),
1490 Call { ref func, ref args, ref destination, cleanup } => {
1491 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1492 (loc.fold_with(folder), dest)
1496 func: func.fold_with(folder),
1497 args: args.fold_with(folder),
1502 Assert { ref cond, expected, ref msg, target, cleanup } => {
1503 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1504 AssertMessage::BoundsCheck {
1505 len: len.fold_with(folder),
1506 index: index.fold_with(folder),
1512 cond: cond.fold_with(folder),
1521 Unreachable => Unreachable,
1524 source_info: self.source_info,
1529 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1530 use mir::TerminatorKind::*;
1533 SwitchInt { ref discr, switch_ty, .. } =>
1534 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1535 Drop { ref location, ..} => location.visit_with(visitor),
1536 DropAndReplace { ref location, ref value, ..} =>
1537 location.visit_with(visitor) || value.visit_with(visitor),
1538 Call { ref func, ref args, ref destination, .. } => {
1539 let dest = if let Some((ref loc, _)) = *destination {
1540 loc.visit_with(visitor)
1542 dest || func.visit_with(visitor) || args.visit_with(visitor)
1544 Assert { ref cond, ref msg, .. } => {
1545 if cond.visit_with(visitor) {
1546 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1547 len.visit_with(visitor) || index.visit_with(visitor)
1558 Unreachable => false
1563 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1564 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1566 &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1571 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1572 if let &Lvalue::Projection(ref p) = self {
1573 p.visit_with(visitor)
1580 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1581 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1584 Use(ref op) => Use(op.fold_with(folder)),
1585 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1586 Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1587 Len(ref lval) => Len(lval.fold_with(folder)),
1588 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1589 BinaryOp(op, ref rhs, ref lhs) =>
1590 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1591 CheckedBinaryOp(op, ref rhs, ref lhs) =>
1592 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1593 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1594 Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1595 Box(ty) => Box(ty.fold_with(folder)),
1596 Aggregate(ref kind, ref fields) => {
1597 let kind = match *kind {
1598 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1599 AggregateKind::Tuple => AggregateKind::Tuple,
1600 AggregateKind::Adt(def, v, substs, n) =>
1601 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1602 AggregateKind::Closure(id, substs) =>
1603 AggregateKind::Closure(id, substs.fold_with(folder))
1605 Aggregate(kind, fields.fold_with(folder))
1610 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1613 Use(ref op) => op.visit_with(visitor),
1614 Repeat(ref op, _) => op.visit_with(visitor),
1615 Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1616 Len(ref lval) => lval.visit_with(visitor),
1617 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1618 BinaryOp(_, ref rhs, ref lhs) |
1619 CheckedBinaryOp(_, ref rhs, ref lhs) =>
1620 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1621 UnaryOp(_, ref val) => val.visit_with(visitor),
1622 Discriminant(ref lval) => lval.visit_with(visitor),
1623 Box(ty) => ty.visit_with(visitor),
1624 Aggregate(ref kind, ref fields) => {
1626 AggregateKind::Array(ty) => ty.visit_with(visitor),
1627 AggregateKind::Tuple => false,
1628 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1629 AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1630 }) || fields.visit_with(visitor)
1636 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1637 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1639 Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1640 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1644 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1646 Operand::Consume(ref lval) => lval.visit_with(visitor),
1647 Operand::Constant(ref c) => c.visit_with(visitor)
1652 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1653 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1655 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1656 use mir::ProjectionElem::*;
1658 let base = self.base.fold_with(folder);
1659 let elem = match self.elem {
1661 Field(f, ty) => Field(f, ty.fold_with(folder)),
1662 Index(ref v) => Index(v.fold_with(folder)),
1663 ref elem => elem.clone()
1672 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1673 use mir::ProjectionElem::*;
1675 self.base.visit_with(visitor) ||
1677 Field(_, ty) => ty.visit_with(visitor),
1678 Index(ref v) => v.visit_with(visitor),
1684 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1685 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1687 span: self.span.clone(),
1688 ty: self.ty.fold_with(folder),
1689 literal: self.literal.fold_with(folder)
1692 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1693 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1697 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1698 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1700 Literal::Item { def_id, substs } => Literal::Item {
1702 substs: substs.fold_with(folder)
1707 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1709 Literal::Item { substs, .. } => substs.visit_with(visitor),