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 middle::region::CodeExtent;
16 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
17 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
18 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
19 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
20 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
21 use hir::def::CtorKind;
22 use hir::def_id::DefId;
23 use ty::subst::{Subst, Substs};
24 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
25 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
27 use rustc_back::slice;
30 use std::borrow::{Cow};
32 use std::fmt::{self, Debug, Formatter, Write};
34 use std::ops::{Index, IndexMut};
35 use std::vec::IntoIter;
36 use syntax::ast::Name;
45 macro_rules! newtype_index {
46 ($name:ident, $debug_name:expr) => (
47 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
48 RustcEncodable, RustcDecodable)]
49 pub struct $name(u32);
52 fn new(value: usize) -> Self {
53 assert!(value < (u32::MAX) as usize);
56 fn index(self) -> usize {
61 impl Debug for $name {
62 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
63 write!(fmt, "{}{}", $debug_name, self.0)
70 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
72 /// Lowered representation of a single function.
73 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
74 pub struct Mir<'tcx> {
75 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
76 /// that indexes into this vector.
77 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
79 /// List of visibility (lexical) scopes; these are referenced by statements
80 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
81 pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
83 /// Rvalues promoted from this function, such as borrows of constants.
84 /// Each of them is the Mir of a constant with the fn's type parameters
85 /// in scope, but a separate set of locals.
86 pub promoted: IndexVec<Promoted, Mir<'tcx>>,
88 /// Return type of the function.
89 pub return_ty: Ty<'tcx>,
91 /// Declarations of locals.
93 /// The first local is the return value pointer, followed by `arg_count`
94 /// locals for the function arguments, followed by any user-declared
95 /// variables and temporaries.
96 pub local_decls: LocalDecls<'tcx>,
98 /// Number of arguments this function takes.
100 /// Starting at local 1, `arg_count` locals will be provided by the caller
101 /// and can be assumed to be initialized.
103 /// If this MIR was built for a constant, this will be 0.
104 pub arg_count: usize,
106 /// Names and capture modes of all the closure upvars, assuming
107 /// the first argument is either the closure or a reference to it.
108 pub upvar_decls: Vec<UpvarDecl>,
110 /// Mark an argument local (which must be a tuple) as getting passed as
111 /// its individual components at the LLVM level.
113 /// This is used for the "rust-call" ABI.
114 pub spread_arg: Option<Local>,
116 /// A span representing this MIR, for error reporting
119 /// A cache for various calculations
123 /// where execution begins
124 pub const START_BLOCK: BasicBlock = BasicBlock(0);
126 impl<'tcx> Mir<'tcx> {
127 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
128 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
129 promoted: IndexVec<Promoted, Mir<'tcx>>,
131 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
133 upvar_decls: Vec<UpvarDecl>,
136 // We need `arg_count` locals, and one for the return pointer
137 assert!(local_decls.len() >= arg_count + 1,
138 "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
139 assert_eq!(local_decls[RETURN_POINTER].ty, return_ty);
151 cache: cache::Cache::new()
156 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
161 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
162 self.cache.invalidate();
163 &mut self.basic_blocks
167 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
168 self.cache.predecessors(self)
172 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
173 Ref::map(self.predecessors(), |p| &p[bb])
177 pub fn dominators(&self) -> Dominators<BasicBlock> {
182 pub fn local_kind(&self, local: Local) -> LocalKind {
183 let index = local.0 as usize;
185 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
186 "return pointer should be mutable");
188 LocalKind::ReturnPointer
189 } else if index < self.arg_count + 1 {
191 } else if self.local_decls[local].name.is_some() {
194 debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
195 "temp should be mutable");
201 /// Returns an iterator over all temporaries.
203 pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
204 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
205 let local = Local::new(index);
206 if self.local_decls[local].is_user_variable {
214 /// Returns an iterator over all user-declared locals.
216 pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
217 (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
218 let local = Local::new(index);
219 if self.local_decls[local].is_user_variable {
227 /// Returns an iterator over all function arguments.
229 pub fn args_iter(&self) -> impl Iterator<Item=Local> {
230 let arg_count = self.arg_count;
231 (1..arg_count+1).map(Local::new)
234 /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
235 /// locals that are neither arguments nor the return pointer).
237 pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
238 let arg_count = self.arg_count;
239 let local_count = self.local_decls.len();
240 (arg_count+1..local_count).map(Local::new)
243 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
244 /// invalidating statement indices in `Location`s.
245 pub fn make_statement_nop(&mut self, location: Location) {
246 let block = &mut self[location.block];
247 debug_assert!(location.statement_index < block.statements.len());
248 block.statements[location.statement_index].make_nop()
252 impl_stable_hash_for!(struct Mir<'tcx> {
265 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
266 type Output = BasicBlockData<'tcx>;
269 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
270 &self.basic_blocks()[index]
274 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
276 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
277 &mut self.basic_blocks_mut()[index]
281 /// Grouped information about the source code origin of a MIR entity.
282 /// Intended to be inspected by diagnostics and debuginfo.
283 /// Most passes can work with it as a whole, within a single function.
284 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
285 pub struct SourceInfo {
286 /// Source span for the AST pertaining to this MIR entity.
289 /// The lexical visibility scope, i.e. which bindings can be seen.
290 pub scope: VisibilityScope
293 ///////////////////////////////////////////////////////////////////////////
294 // Mutability and borrow kinds
296 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
297 pub enum Mutability {
302 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
303 pub enum BorrowKind {
304 /// Data must be immutable and is aliasable.
307 /// Data must be immutable but not aliasable. This kind of borrow
308 /// cannot currently be expressed by the user and is used only in
309 /// implicit closure bindings. It is needed when you the closure
310 /// is borrowing or mutating a mutable referent, e.g.:
312 /// let x: &mut isize = ...;
313 /// let y = || *x += 5;
315 /// If we were to try to translate this closure into a more explicit
316 /// form, we'd encounter an error with the code as written:
318 /// struct Env { x: & &mut isize }
319 /// let x: &mut isize = ...;
320 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
321 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
323 /// This is then illegal because you cannot mutate a `&mut` found
324 /// in an aliasable location. To solve, you'd have to translate with
325 /// an `&mut` borrow:
327 /// struct Env { x: & &mut isize }
328 /// let x: &mut isize = ...;
329 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
330 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
332 /// Now the assignment to `**env.x` is legal, but creating a
333 /// mutable pointer to `x` is not because `x` is not mutable. We
334 /// could fix this by declaring `x` as `let mut x`. This is ok in
335 /// user code, if awkward, but extra weird for closures, since the
336 /// borrow is hidden.
338 /// So we introduce a "unique imm" borrow -- the referent is
339 /// immutable, but not aliasable. This solves the problem. For
340 /// simplicity, we don't give users the way to express this
341 /// borrow, it's just used when translating closures.
344 /// Data is mutable and not aliasable.
348 ///////////////////////////////////////////////////////////////////////////
349 // Variables and temps
351 newtype_index!(Local, "_");
353 pub const RETURN_POINTER: Local = Local(0);
355 /// Classifies locals into categories. See `Mir::local_kind`.
356 #[derive(PartialEq, Eq, Debug)]
358 /// User-declared variable binding
360 /// Compiler-introduced temporary
362 /// Function argument
364 /// Location of function's return value
370 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
371 /// argument, or the return pointer.
372 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
373 pub struct LocalDecl<'tcx> {
374 /// `let mut x` vs `let x`.
376 /// Temporaries and the return pointer are always mutable.
377 pub mutability: Mutability,
379 /// True if this corresponds to a user-declared local variable.
380 pub is_user_variable: bool,
382 /// Type of this local.
385 /// Name of the local, used in debuginfo and pretty-printing.
387 /// Note that function arguments can also have this set to `Some(_)`
388 /// to generate better debuginfo.
389 pub name: Option<Name>,
391 /// Source info of the local.
392 pub source_info: SourceInfo,
395 impl<'tcx> LocalDecl<'tcx> {
396 /// Create a new `LocalDecl` for a temporary.
398 pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
400 mutability: Mutability::Mut,
403 source_info: SourceInfo {
405 scope: ARGUMENT_VISIBILITY_SCOPE
407 is_user_variable: false
411 /// Builds a `LocalDecl` for the return pointer.
413 /// This must be inserted into the `local_decls` list as the first local.
415 pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
417 mutability: Mutability::Mut,
419 source_info: SourceInfo {
421 scope: ARGUMENT_VISIBILITY_SCOPE
423 name: None, // FIXME maybe we do want some name here?
424 is_user_variable: false
429 /// A closure capture, with its name and mode.
430 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
431 pub struct UpvarDecl {
432 pub debug_name: Name,
434 /// If true, the capture is behind a reference.
438 ///////////////////////////////////////////////////////////////////////////
441 newtype_index!(BasicBlock, "bb");
443 ///////////////////////////////////////////////////////////////////////////
444 // BasicBlockData and Terminator
446 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
447 pub struct BasicBlockData<'tcx> {
448 /// List of statements in this block.
449 pub statements: Vec<Statement<'tcx>>,
451 /// Terminator for this block.
453 /// NB. This should generally ONLY be `None` during construction.
454 /// Therefore, you should generally access it via the
455 /// `terminator()` or `terminator_mut()` methods. The only
456 /// exception is that certain passes, such as `simplify_cfg`, swap
457 /// out the terminator temporarily with `None` while they continue
458 /// to recurse over the set of basic blocks.
459 pub terminator: Option<Terminator<'tcx>>,
461 /// If true, this block lies on an unwind path. This is used
462 /// during trans where distinct kinds of basic blocks may be
463 /// generated (particularly for MSVC cleanup). Unwind blocks must
464 /// only branch to other unwind blocks.
465 pub is_cleanup: bool,
468 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
469 pub struct Terminator<'tcx> {
470 pub source_info: SourceInfo,
471 pub kind: TerminatorKind<'tcx>
474 #[derive(Clone, RustcEncodable, RustcDecodable)]
475 pub enum TerminatorKind<'tcx> {
476 /// block should have one successor in the graph; we jump there
481 /// operand evaluates to an integer; jump depending on its value
482 /// to one of the targets, and otherwise fallback to `otherwise`
484 /// discriminant value being tested
485 discr: Operand<'tcx>,
487 /// type of value being tested
490 /// Possible values. The locations to branch to in each case
491 /// are found in the corresponding indices from the `targets` vector.
492 values: Cow<'tcx, [ConstInt]>,
494 /// Possible branch sites. The last element of this vector is used
495 /// for the otherwise branch, so targets.len() == values.len() + 1
497 // This invariant is quite non-obvious and also could be improved.
498 // One way to make this invariant is to have something like this instead:
500 // branches: Vec<(ConstInt, BasicBlock)>,
501 // otherwise: Option<BasicBlock> // exhaustive if None
503 // However we’ve decided to keep this as-is until we figure a case
504 // where some other approach seems to be strictly better than other.
505 targets: Vec<BasicBlock>,
508 /// Indicates that the landing pad is finished and unwinding should
509 /// continue. Emitted by build::scope::diverge_cleanup.
512 /// Indicates a normal return. The return pointer lvalue should
513 /// have been filled in by now. This should occur at most once.
516 /// Indicates a terminator that can never be reached.
521 location: Lvalue<'tcx>,
523 unwind: Option<BasicBlock>
526 /// Drop the Lvalue and assign the new value over it
528 location: Lvalue<'tcx>,
529 value: Operand<'tcx>,
531 unwind: Option<BasicBlock>,
534 /// Block ends with a call of a converging function
536 /// The function that’s being called
538 /// Arguments the function is called with
539 args: Vec<Operand<'tcx>>,
540 /// Destination for the return value. If some, the call is converging.
541 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
542 /// Cleanups to be done if the call unwinds.
543 cleanup: Option<BasicBlock>
546 /// Jump to the target if the condition has the expected value,
547 /// otherwise panic with a message and a cleanup target.
551 msg: AssertMessage<'tcx>,
553 cleanup: Option<BasicBlock>
557 impl<'tcx> Terminator<'tcx> {
558 pub fn successors(&self) -> Cow<[BasicBlock]> {
559 self.kind.successors()
562 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
563 self.kind.successors_mut()
567 impl<'tcx> TerminatorKind<'tcx> {
568 pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
569 t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
570 static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
571 TerminatorKind::SwitchInt {
573 switch_ty: tcx.types.bool,
574 values: From::from(BOOL_SWITCH_FALSE),
579 pub fn successors(&self) -> Cow<[BasicBlock]> {
580 use self::TerminatorKind::*;
582 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
583 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
584 Resume => (&[]).into_cow(),
585 Return => (&[]).into_cow(),
586 Unreachable => (&[]).into_cow(),
587 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
588 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
589 slice::ref_slice(t).into_cow(),
590 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
591 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
592 DropAndReplace { target, unwind: Some(unwind), .. } |
593 Drop { target, unwind: Some(unwind), .. } => {
594 vec![target, unwind].into_cow()
596 DropAndReplace { ref target, unwind: None, .. } |
597 Drop { ref target, unwind: None, .. } => {
598 slice::ref_slice(target).into_cow()
600 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
601 Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
605 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
606 // `Vec<&mut BasicBlock>` would look like in the first place.
607 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
608 use self::TerminatorKind::*;
610 Goto { target: ref mut b } => vec![b],
611 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
612 Resume => Vec::new(),
613 Return => Vec::new(),
614 Unreachable => Vec::new(),
615 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
616 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
617 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
618 Call { destination: None, cleanup: None, .. } => vec![],
619 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
620 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
621 DropAndReplace { ref mut target, unwind: None, .. } |
622 Drop { ref mut target, unwind: None, .. } => {
625 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
626 Assert { ref mut target, .. } => vec![target]
631 impl<'tcx> BasicBlockData<'tcx> {
632 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
640 /// Accessor for terminator.
642 /// Terminator may not be None after construction of the basic block is complete. This accessor
643 /// provides a convenience way to reach the terminator.
644 pub fn terminator(&self) -> &Terminator<'tcx> {
645 self.terminator.as_ref().expect("invalid terminator state")
648 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
649 self.terminator.as_mut().expect("invalid terminator state")
653 impl<'tcx> Debug for TerminatorKind<'tcx> {
654 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
656 let successors = self.successors();
657 let labels = self.fmt_successor_labels();
658 assert_eq!(successors.len(), labels.len());
660 match successors.len() {
663 1 => write!(fmt, " -> {:?}", successors[0]),
666 write!(fmt, " -> [")?;
667 for (i, target) in successors.iter().enumerate() {
671 write!(fmt, "{}: {:?}", labels[i], target)?;
680 impl<'tcx> TerminatorKind<'tcx> {
681 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
682 /// successor basic block, if any. The only information not inlcuded is the list of possible
683 /// successors, which may be rendered differently between the text and the graphviz format.
684 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
685 use self::TerminatorKind::*;
687 Goto { .. } => write!(fmt, "goto"),
688 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
689 Return => write!(fmt, "return"),
690 Resume => write!(fmt, "resume"),
691 Unreachable => write!(fmt, "unreachable"),
692 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
693 DropAndReplace { ref location, ref value, .. } =>
694 write!(fmt, "replace({:?} <- {:?})", location, value),
695 Call { ref func, ref args, ref destination, .. } => {
696 if let Some((ref destination, _)) = *destination {
697 write!(fmt, "{:?} = ", destination)?;
699 write!(fmt, "{:?}(", func)?;
700 for (index, arg) in args.iter().enumerate() {
704 write!(fmt, "{:?}", arg)?;
708 Assert { ref cond, expected, ref msg, .. } => {
709 write!(fmt, "assert(")?;
713 write!(fmt, "{:?}, ", cond)?;
716 AssertMessage::BoundsCheck { ref len, ref index } => {
717 write!(fmt, "{:?}, {:?}, {:?}",
718 "index out of bounds: the len is {} but the index is {}",
721 AssertMessage::Math(ref err) => {
722 write!(fmt, "{:?}", err.description())?;
731 /// Return the list of labels for the edges to the successor basic blocks.
732 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
733 use self::TerminatorKind::*;
735 Return | Resume | Unreachable => vec![],
736 Goto { .. } => vec!["".into()],
737 SwitchInt { ref values, .. } => {
740 let mut buf = String::new();
741 fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
744 .chain(iter::once(String::from("otherwise").into()))
747 Call { destination: Some(_), cleanup: Some(_), .. } =>
748 vec!["return".into_cow(), "unwind".into_cow()],
749 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
750 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
751 Call { destination: None, cleanup: None, .. } => vec![],
752 DropAndReplace { unwind: None, .. } |
753 Drop { unwind: None, .. } => vec!["return".into_cow()],
754 DropAndReplace { unwind: Some(_), .. } |
755 Drop { unwind: Some(_), .. } => {
756 vec!["return".into_cow(), "unwind".into_cow()]
758 Assert { cleanup: None, .. } => vec!["".into()],
760 vec!["success".into_cow(), "unwind".into_cow()]
765 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
766 pub enum AssertMessage<'tcx> {
774 ///////////////////////////////////////////////////////////////////////////
777 #[derive(Clone, RustcEncodable, RustcDecodable)]
778 pub struct Statement<'tcx> {
779 pub source_info: SourceInfo,
780 pub kind: StatementKind<'tcx>,
783 impl<'tcx> Statement<'tcx> {
784 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
785 /// invalidating statement indices in `Location`s.
786 pub fn make_nop(&mut self) {
787 self.kind = StatementKind::Nop
791 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
792 pub enum StatementKind<'tcx> {
793 /// Write the RHS Rvalue to the LHS Lvalue.
794 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
796 /// Write the discriminant for a variant to the enum Lvalue.
797 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
799 /// Start a live range for the storage of the local.
800 StorageLive(Lvalue<'tcx>),
802 /// End the current live range for the storage of the local.
803 StorageDead(Lvalue<'tcx>),
807 outputs: Vec<Lvalue<'tcx>>,
808 inputs: Vec<Operand<'tcx>>
811 /// Mark one terminating point of an extent (i.e. static region).
812 /// (The starting point(s) arise implicitly from borrows.)
813 EndRegion(CodeExtent),
815 /// No-op. Useful for deleting instructions without affecting statement indices.
819 impl<'tcx> Debug for Statement<'tcx> {
820 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
821 use self::StatementKind::*;
823 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
824 // (reuse lifetime rendering policy from ppaux.)
825 EndRegion(ref ce) => write!(fmt, "EndRegion({})", ty::ReScope(*ce)),
826 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
827 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
828 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
829 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
831 InlineAsm { ref asm, ref outputs, ref inputs } => {
832 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
834 Nop => write!(fmt, "nop"),
839 ///////////////////////////////////////////////////////////////////////////
842 /// A path to a value; something that can be evaluated without
843 /// changing or disturbing program state.
844 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
845 pub enum Lvalue<'tcx> {
849 /// static or static mut variable
850 Static(Box<Static<'tcx>>),
852 /// projection out of an lvalue (access a field, deref a pointer, etc)
853 Projection(Box<LvalueProjection<'tcx>>),
856 /// The def-id of a static, along with its normalized type (which is
857 /// stored to avoid requiring normalization when reading MIR).
858 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
859 pub struct Static<'tcx> {
864 impl_stable_hash_for!(struct Static<'tcx> {
869 /// The `Projection` data structure defines things of the form `B.x`
870 /// or `*B` or `B[index]`. Note that it is parameterized because it is
871 /// shared between `Constant` and `Lvalue`. See the aliases
872 /// `LvalueProjection` etc below.
873 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
874 pub struct Projection<'tcx, B, V> {
876 pub elem: ProjectionElem<'tcx, V>,
879 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
880 pub enum ProjectionElem<'tcx, V> {
882 Field(Field, Ty<'tcx>),
885 /// These indices are generated by slice patterns. Easiest to explain
889 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
890 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
891 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
892 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
895 /// index or -index (in Python terms), depending on from_end
897 /// thing being indexed must be at least this long
899 /// counting backwards from end?
903 /// These indices are generated by slice patterns.
905 /// slice[from:-to] in Python terms.
911 /// "Downcast" to a variant of an ADT. Currently, we only introduce
912 /// this for ADTs with more than one variant. It may be better to
913 /// just introduce it always, or always for enums.
914 Downcast(&'tcx AdtDef, usize),
917 /// Alias for projections as they appear in lvalues, where the base is an lvalue
918 /// and the index is an operand.
919 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
921 /// Alias for projections as they appear in lvalues, where the base is an lvalue
922 /// and the index is an operand.
923 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
925 newtype_index!(Field, "field");
927 impl<'tcx> Lvalue<'tcx> {
928 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
929 self.elem(ProjectionElem::Field(f, ty))
932 pub fn deref(self) -> Lvalue<'tcx> {
933 self.elem(ProjectionElem::Deref)
936 pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
937 self.elem(ProjectionElem::Downcast(adt_def, variant_index))
940 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
941 self.elem(ProjectionElem::Index(index))
944 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
945 Lvalue::Projection(Box::new(LvalueProjection {
952 impl<'tcx> Debug for Lvalue<'tcx> {
953 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
957 Local(id) => write!(fmt, "{:?}", id),
958 Static(box self::Static { def_id, ty }) =>
959 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
960 Projection(ref data) =>
962 ProjectionElem::Downcast(ref adt_def, index) =>
963 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
964 ProjectionElem::Deref =>
965 write!(fmt, "(*{:?})", data.base),
966 ProjectionElem::Field(field, ty) =>
967 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
968 ProjectionElem::Index(ref index) =>
969 write!(fmt, "{:?}[{:?}]", data.base, index),
970 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
971 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
972 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
973 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
974 ProjectionElem::Subslice { from, to } if to == 0 =>
975 write!(fmt, "{:?}[{:?}:]", data.base, from),
976 ProjectionElem::Subslice { from, to } if from == 0 =>
977 write!(fmt, "{:?}[:-{:?}]", data.base, to),
978 ProjectionElem::Subslice { from, to } =>
979 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
987 ///////////////////////////////////////////////////////////////////////////
990 newtype_index!(VisibilityScope, "scope");
991 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
993 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
994 pub struct VisibilityScopeData {
996 pub parent_scope: Option<VisibilityScope>,
999 ///////////////////////////////////////////////////////////////////////////
1002 /// These are values that can appear inside an rvalue (or an index
1003 /// lvalue). They are intentionally limited to prevent rvalues from
1004 /// being nested in one another.
1005 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
1006 pub enum Operand<'tcx> {
1007 Consume(Lvalue<'tcx>),
1008 Constant(Box<Constant<'tcx>>),
1011 impl<'tcx> Debug for Operand<'tcx> {
1012 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1013 use self::Operand::*;
1015 Constant(ref a) => write!(fmt, "{:?}", a),
1016 Consume(ref lv) => write!(fmt, "{:?}", lv),
1021 impl<'tcx> Operand<'tcx> {
1022 pub fn function_handle<'a>(
1023 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1025 substs: &'tcx Substs<'tcx>,
1028 Operand::Constant(box Constant {
1030 ty: tcx.type_of(def_id).subst(tcx, substs),
1031 literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1037 ///////////////////////////////////////////////////////////////////////////
1040 #[derive(Clone, RustcEncodable, RustcDecodable)]
1041 pub enum Rvalue<'tcx> {
1042 /// x (either a move or copy, depending on type of x)
1046 Repeat(Operand<'tcx>, ConstUsize),
1049 Ref(Region<'tcx>, BorrowKind, Lvalue<'tcx>),
1051 /// length of a [X] or [X;n] value
1054 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1056 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1057 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1059 NullaryOp(NullOp, Ty<'tcx>),
1060 UnaryOp(UnOp, Operand<'tcx>),
1062 /// Read the discriminant of an ADT.
1064 /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1065 /// be defined to return, say, a 0) if ADT is not an enum.
1066 Discriminant(Lvalue<'tcx>),
1068 /// Create an aggregate value, like a tuple or struct. This is
1069 /// only needed because we want to distinguish `dest = Foo { x:
1070 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1071 /// that `Foo` has a destructor. These rvalues can be optimized
1072 /// away after type-checking and before lowering.
1073 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1076 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1080 /// Convert unique, zero-sized type for a fn to fn()
1083 /// Convert non capturing closure to fn()
1086 /// Convert safe fn() to unsafe fn()
1089 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1090 /// trans must figure out the details once full monomorphization
1091 /// is known. For example, this could be used to cast from a
1092 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1093 /// (presuming `T: Trait`).
1097 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1098 pub enum AggregateKind<'tcx> {
1099 /// The type is of the element
1102 /// The second field is variant number (discriminant), it's equal to 0
1103 /// for struct and union expressions. The fourth field is active field
1104 /// number and is present only for union expressions.
1105 Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1106 Closure(DefId, ClosureSubsts<'tcx>),
1109 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1111 /// The `+` operator (addition)
1113 /// The `-` operator (subtraction)
1115 /// The `*` operator (multiplication)
1117 /// The `/` operator (division)
1119 /// The `%` operator (modulus)
1121 /// The `^` operator (bitwise xor)
1123 /// The `&` operator (bitwise and)
1125 /// The `|` operator (bitwise or)
1127 /// The `<<` operator (shift left)
1129 /// The `>>` operator (shift right)
1131 /// The `==` operator (equality)
1133 /// The `<` operator (less than)
1135 /// The `<=` operator (less than or equal to)
1137 /// The `!=` operator (not equal to)
1139 /// The `>=` operator (greater than or equal to)
1141 /// The `>` operator (greater than)
1143 /// The `ptr.offset` operator
1148 pub fn is_checkable(self) -> bool {
1151 Add | Sub | Mul | Shl | Shr => true,
1157 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1159 /// Return the size of a value of that type
1161 /// Create a new uninitialized box for a value of that type
1165 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1167 /// The `!` operator for logical inversion
1169 /// The `-` operator for negation
1173 impl<'tcx> Debug for Rvalue<'tcx> {
1174 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1175 use self::Rvalue::*;
1178 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1179 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1180 Len(ref a) => write!(fmt, "Len({:?})", a),
1181 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1182 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1183 CheckedBinaryOp(ref op, ref a, ref b) => {
1184 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1186 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1187 Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1188 NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
1189 Ref(region, borrow_kind, ref lv) => {
1190 let kind_str = match borrow_kind {
1191 BorrowKind::Shared => "",
1192 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1195 // When identifying regions, add trailing space if
1197 let region = if ppaux::identify_regions() {
1198 let mut region = format!("{}", region);
1199 if region.len() > 0 { region.push(' '); }
1204 write!(fmt, "&{}{}{:?}", region, kind_str, lv)
1207 Aggregate(ref kind, ref lvs) => {
1208 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1209 let mut tuple_fmt = fmt.debug_tuple("");
1211 tuple_fmt.field(lv);
1217 AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1219 AggregateKind::Tuple => {
1221 0 => write!(fmt, "()"),
1222 1 => write!(fmt, "({:?},)", lvs[0]),
1223 _ => fmt_tuple(fmt, lvs),
1227 AggregateKind::Adt(adt_def, variant, substs, _) => {
1228 let variant_def = &adt_def.variants[variant];
1230 ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1232 match variant_def.ctor_kind {
1233 CtorKind::Const => Ok(()),
1234 CtorKind::Fn => fmt_tuple(fmt, lvs),
1235 CtorKind::Fictive => {
1236 let mut struct_fmt = fmt.debug_struct("");
1237 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1238 struct_fmt.field(&field.name.as_str(), lv);
1245 AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1246 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1247 let name = if tcx.sess.opts.debugging_opts.span_free_formats {
1248 format!("[closure@{:?}]", node_id)
1250 format!("[closure@{:?}]", tcx.hir.span(node_id))
1252 let mut struct_fmt = fmt.debug_struct(&name);
1254 tcx.with_freevars(node_id, |freevars| {
1255 for (freevar, lv) in freevars.iter().zip(lvs) {
1256 let def_id = freevar.def.def_id();
1257 let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1258 let var_name = tcx.local_var_name_str(var_id);
1259 struct_fmt.field(&var_name, lv);
1265 write!(fmt, "[closure]")
1274 ///////////////////////////////////////////////////////////////////////////
1277 /// Two constants are equal if they are the same constant. Note that
1278 /// this does not necessarily mean that they are "==" in Rust -- in
1279 /// particular one must be wary of `NaN`!
1281 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1282 pub struct Constant<'tcx> {
1285 pub literal: Literal<'tcx>,
1288 newtype_index!(Promoted, "promoted");
1290 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1291 pub enum Literal<'tcx> {
1294 substs: &'tcx Substs<'tcx>,
1297 value: ConstVal<'tcx>,
1300 // Index into the `promoted` vector of `Mir`.
1305 impl<'tcx> Debug for Constant<'tcx> {
1306 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1307 write!(fmt, "{:?}", self.literal)
1311 impl<'tcx> Debug for Literal<'tcx> {
1312 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1313 use self::Literal::*;
1315 Item { def_id, substs } => {
1316 ppaux::parameterized(fmt, substs, def_id, &[])
1318 Value { ref value } => {
1319 write!(fmt, "const ")?;
1320 fmt_const_val(fmt, value)
1322 Promoted { index } => {
1323 write!(fmt, "{:?}", index)
1329 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1330 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1331 use middle::const_val::ConstVal::*;
1333 Float(f) => write!(fmt, "{:?}", f),
1334 Integral(n) => write!(fmt, "{}", n),
1335 Str(ref s) => write!(fmt, "{:?}", s),
1336 ByteStr(ref bytes) => {
1337 let escaped: String = bytes
1339 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1341 write!(fmt, "b\"{}\"", escaped)
1343 Bool(b) => write!(fmt, "{:?}", b),
1344 Char(c) => write!(fmt, "{:?}", c),
1346 Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1347 Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1348 bug!("ConstVal `{:?}` should not be in MIR", const_val),
1352 fn item_path_str(def_id: DefId) -> String {
1353 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1356 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1358 type Node = BasicBlock;
1360 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1362 fn start_node(&self) -> Self::Node { START_BLOCK }
1364 fn predecessors<'graph>(&'graph self, node: Self::Node)
1365 -> <Self as GraphPredecessors<'graph>>::Iter
1367 self.predecessors_for(node).clone().into_iter()
1369 fn successors<'graph>(&'graph self, node: Self::Node)
1370 -> <Self as GraphSuccessors<'graph>>::Iter
1372 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1376 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1377 type Item = BasicBlock;
1378 type Iter = IntoIter<BasicBlock>;
1381 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1382 type Item = BasicBlock;
1383 type Iter = IntoIter<BasicBlock>;
1386 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1387 pub struct Location {
1388 /// the location is within this block
1389 pub block: BasicBlock,
1391 /// the location is the start of the this statement; or, if `statement_index`
1392 /// == num-statements, then the start of the terminator.
1393 pub statement_index: usize,
1396 impl fmt::Debug for Location {
1397 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1398 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1403 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1404 if self.block == other.block {
1405 self.statement_index <= other.statement_index
1407 dominators.is_dominated_by(other.block, self.block)
1414 * TypeFoldable implementations for MIR types
1417 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1418 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1420 basic_blocks: self.basic_blocks.fold_with(folder),
1421 visibility_scopes: self.visibility_scopes.clone(),
1422 promoted: self.promoted.fold_with(folder),
1423 return_ty: self.return_ty.fold_with(folder),
1424 local_decls: self.local_decls.fold_with(folder),
1425 arg_count: self.arg_count,
1426 upvar_decls: self.upvar_decls.clone(),
1427 spread_arg: self.spread_arg,
1429 cache: cache::Cache::new()
1433 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1434 self.basic_blocks.visit_with(visitor) ||
1435 self.promoted.visit_with(visitor) ||
1436 self.return_ty.visit_with(visitor) ||
1437 self.local_decls.visit_with(visitor)
1441 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1442 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1444 ty: self.ty.fold_with(folder),
1449 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1450 self.ty.visit_with(visitor)
1454 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1455 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1457 statements: self.statements.fold_with(folder),
1458 terminator: self.terminator.fold_with(folder),
1459 is_cleanup: self.is_cleanup
1463 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1464 self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1468 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1469 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1470 use mir::StatementKind::*;
1472 let kind = match self.kind {
1473 Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1474 SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1475 lvalue: lvalue.fold_with(folder),
1478 StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1479 StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1480 InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1482 outputs: outputs.fold_with(folder),
1483 inputs: inputs.fold_with(folder)
1486 // Note for future: If we want to expose the extents
1487 // during the fold, we need to either generalize EndRegion
1488 // to carry `[ty::Region]`, or extend the `TypeFolder`
1489 // trait with a `fn fold_extent`.
1490 EndRegion(ref extent) => EndRegion(extent.clone()),
1495 source_info: self.source_info,
1500 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1501 use mir::StatementKind::*;
1504 Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1505 SetDiscriminant { ref lvalue, .. } |
1506 StorageLive(ref lvalue) |
1507 StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1508 InlineAsm { ref outputs, ref inputs, .. } =>
1509 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1511 // Note for future: If we want to expose the extents
1512 // during the visit, we need to either generalize EndRegion
1513 // to carry `[ty::Region]`, or extend the `TypeVisitor`
1514 // trait with a `fn visit_extent`.
1515 EndRegion(ref _extent) => false,
1522 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1523 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1524 use mir::TerminatorKind::*;
1526 let kind = match self.kind {
1527 Goto { target } => Goto { target: target },
1528 SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1529 discr: discr.fold_with(folder),
1530 switch_ty: switch_ty.fold_with(folder),
1531 values: values.clone(),
1532 targets: targets.clone()
1534 Drop { ref location, target, unwind } => Drop {
1535 location: location.fold_with(folder),
1539 DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1540 location: location.fold_with(folder),
1541 value: value.fold_with(folder),
1545 Call { ref func, ref args, ref destination, cleanup } => {
1546 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1547 (loc.fold_with(folder), dest)
1551 func: func.fold_with(folder),
1552 args: args.fold_with(folder),
1557 Assert { ref cond, expected, ref msg, target, cleanup } => {
1558 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1559 AssertMessage::BoundsCheck {
1560 len: len.fold_with(folder),
1561 index: index.fold_with(folder),
1567 cond: cond.fold_with(folder),
1576 Unreachable => Unreachable,
1579 source_info: self.source_info,
1584 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1585 use mir::TerminatorKind::*;
1588 SwitchInt { ref discr, switch_ty, .. } =>
1589 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1590 Drop { ref location, ..} => location.visit_with(visitor),
1591 DropAndReplace { ref location, ref value, ..} =>
1592 location.visit_with(visitor) || value.visit_with(visitor),
1593 Call { ref func, ref args, ref destination, .. } => {
1594 let dest = if let Some((ref loc, _)) = *destination {
1595 loc.visit_with(visitor)
1597 dest || func.visit_with(visitor) || args.visit_with(visitor)
1599 Assert { ref cond, ref msg, .. } => {
1600 if cond.visit_with(visitor) {
1601 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1602 len.visit_with(visitor) || index.visit_with(visitor)
1613 Unreachable => false
1618 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1619 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1621 &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1626 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1627 if let &Lvalue::Projection(ref p) = self {
1628 p.visit_with(visitor)
1635 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1636 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1639 Use(ref op) => Use(op.fold_with(folder)),
1640 Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1641 Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1642 Len(ref lval) => Len(lval.fold_with(folder)),
1643 Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1644 BinaryOp(op, ref rhs, ref lhs) =>
1645 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1646 CheckedBinaryOp(op, ref rhs, ref lhs) =>
1647 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1648 UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1649 Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1650 NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
1651 Aggregate(ref kind, ref fields) => {
1652 let kind = box match **kind {
1653 AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1654 AggregateKind::Tuple => AggregateKind::Tuple,
1655 AggregateKind::Adt(def, v, substs, n) =>
1656 AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1657 AggregateKind::Closure(id, substs) =>
1658 AggregateKind::Closure(id, substs.fold_with(folder))
1660 Aggregate(kind, fields.fold_with(folder))
1665 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1668 Use(ref op) => op.visit_with(visitor),
1669 Repeat(ref op, _) => op.visit_with(visitor),
1670 Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1671 Len(ref lval) => lval.visit_with(visitor),
1672 Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1673 BinaryOp(_, ref rhs, ref lhs) |
1674 CheckedBinaryOp(_, ref rhs, ref lhs) =>
1675 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1676 UnaryOp(_, ref val) => val.visit_with(visitor),
1677 Discriminant(ref lval) => lval.visit_with(visitor),
1678 NullaryOp(_, ty) => ty.visit_with(visitor),
1679 Aggregate(ref kind, ref fields) => {
1681 AggregateKind::Array(ty) => ty.visit_with(visitor),
1682 AggregateKind::Tuple => false,
1683 AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1684 AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1685 }) || fields.visit_with(visitor)
1691 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1692 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1694 Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1695 Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1699 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1701 Operand::Consume(ref lval) => lval.visit_with(visitor),
1702 Operand::Constant(ref c) => c.visit_with(visitor)
1707 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1708 where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1710 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1711 use mir::ProjectionElem::*;
1713 let base = self.base.fold_with(folder);
1714 let elem = match self.elem {
1716 Field(f, ty) => Field(f, ty.fold_with(folder)),
1717 Index(ref v) => Index(v.fold_with(folder)),
1718 ref elem => elem.clone()
1727 fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1728 use mir::ProjectionElem::*;
1730 self.base.visit_with(visitor) ||
1732 Field(_, ty) => ty.visit_with(visitor),
1733 Index(ref v) => v.visit_with(visitor),
1739 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1740 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1742 span: self.span.clone(),
1743 ty: self.ty.fold_with(folder),
1744 literal: self.literal.fold_with(folder)
1747 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1748 self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1752 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1753 fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1755 Literal::Item { def_id, substs } => Literal::Item {
1757 substs: substs.fold_with(folder)
1762 fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1764 Literal::Item { substs, .. } => substs.visit_with(visitor),