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