1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use graphviz
::IntoCow
;
12 use middle
::const_val
::ConstVal
;
13 use rustc_const_math
::{ConstUsize, ConstInt, ConstMathErr}
;
14 use rustc_data_structures
::indexed_vec
::{IndexVec, Idx}
;
15 use rustc_data_structures
::control_flow_graph
::dominators
::{Dominators, dominators}
;
16 use rustc_data_structures
::control_flow_graph
::{GraphPredecessors, GraphSuccessors}
;
17 use rustc_data_structures
::control_flow_graph
::ControlFlowGraph
;
18 use hir
::def_id
::DefId
;
19 use ty
::subst
::Substs
;
20 use ty
::{self, AdtDef, ClosureSubsts, FnOutput, Region, Ty}
;
22 use rustc_back
::slice
;
25 use std
::borrow
::{Cow}
;
27 use std
::fmt
::{self, Debug, Formatter, Write}
;
29 use std
::ops
::{Index, IndexMut}
;
30 use std
::vec
::IntoIter
;
31 use syntax
::ast
::{self, Name}
;
34 use super::cache
::Cache
;
36 macro_rules
! newtype_index
{
37 ($name
:ident
, $debug_name
:expr
) => (
38 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
39 RustcEncodable
, RustcDecodable
)]
40 pub struct $
name(u32);
43 fn new(value
: usize) -> Self {
44 assert
!(value
< (u32::MAX
) as usize);
47 fn index(self) -> usize {
52 impl Debug
for $name
{
53 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
54 write
!(fmt
, "{}{}", $debug_name
, self.0)
60 /// Lowered representation of a single function.
61 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
62 pub struct Mir
<'tcx
> {
63 /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
64 /// that indexes into this vector.
65 basic_blocks
: IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>>,
67 /// List of visibility (lexical) scopes; these are referenced by statements
68 /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
69 pub visibility_scopes
: IndexVec
<VisibilityScope
, VisibilityScopeData
>,
71 /// Rvalues promoted from this function, such as borrows of constants.
72 /// Each of them is the Mir of a constant with the fn's type parameters
73 /// in scope, but no vars or args and a separate set of temps.
74 pub promoted
: IndexVec
<Promoted
, Mir
<'tcx
>>,
76 /// Return type of the function.
77 pub return_ty
: FnOutput
<'tcx
>,
79 /// Variables: these are stack slots corresponding to user variables. They may be
80 /// assigned many times.
81 pub var_decls
: IndexVec
<Var
, VarDecl
<'tcx
>>,
83 /// Args: these are stack slots corresponding to the input arguments.
84 pub arg_decls
: IndexVec
<Arg
, ArgDecl
<'tcx
>>,
86 /// Temp declarations: stack slots that for temporaries created by
87 /// the compiler. These are assigned once, but they are not SSA
88 /// values in that it is possible to borrow them and mutate them
89 /// through the resulting reference.
90 pub temp_decls
: IndexVec
<Temp
, TempDecl
<'tcx
>>,
92 /// Names and capture modes of all the closure upvars, assuming
93 /// the first argument is either the closure or a reference to it.
94 pub upvar_decls
: Vec
<UpvarDecl
>,
96 /// A span representing this MIR, for error reporting
99 /// A cache for various calculations
103 /// where execution begins
104 pub const START_BLOCK
: BasicBlock
= BasicBlock(0);
106 impl<'tcx
> Mir
<'tcx
> {
107 pub fn new(basic_blocks
: IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>>,
108 visibility_scopes
: IndexVec
<VisibilityScope
, VisibilityScopeData
>,
109 promoted
: IndexVec
<Promoted
, Mir
<'tcx
>>,
110 return_ty
: FnOutput
<'tcx
>,
111 var_decls
: IndexVec
<Var
, VarDecl
<'tcx
>>,
112 arg_decls
: IndexVec
<Arg
, ArgDecl
<'tcx
>>,
113 temp_decls
: IndexVec
<Temp
, TempDecl
<'tcx
>>,
114 upvar_decls
: Vec
<UpvarDecl
>,
118 basic_blocks
: basic_blocks
,
119 visibility_scopes
: visibility_scopes
,
121 return_ty
: return_ty
,
122 var_decls
: var_decls
,
123 arg_decls
: arg_decls
,
124 temp_decls
: temp_decls
,
125 upvar_decls
: upvar_decls
,
132 pub fn basic_blocks(&self) -> &IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>> {
137 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec
<BasicBlock
, BasicBlockData
<'tcx
>> {
138 self.cache
.invalidate();
139 &mut self.basic_blocks
143 pub fn predecessors(&self) -> Ref
<IndexVec
<BasicBlock
, Vec
<BasicBlock
>>> {
144 self.cache
.predecessors(self)
148 pub fn predecessors_for(&self, bb
: BasicBlock
) -> Ref
<Vec
<BasicBlock
>> {
149 Ref
::map(self.predecessors(), |p
| &p
[bb
])
153 pub fn dominators(&self) -> Dominators
<BasicBlock
> {
157 /// Maps locals (Arg's, Var's, Temp's and ReturnPointer, in that order)
158 /// to their index in the whole list of locals. This is useful if you
159 /// want to treat all locals the same instead of repeating yourself.
160 pub fn local_index(&self, lvalue
: &Lvalue
<'tcx
>) -> Option
<Local
> {
161 let idx
= match *lvalue
{
162 Lvalue
::Arg(arg
) => arg
.index(),
163 Lvalue
::Var(var
) => {
164 self.arg_decls
.len() +
167 Lvalue
::Temp(temp
) => {
168 self.arg_decls
.len() +
169 self.var_decls
.len() +
172 Lvalue
::ReturnPointer
=> {
173 self.arg_decls
.len() +
174 self.var_decls
.len() +
175 self.temp_decls
.len()
178 Lvalue
::Projection(_
) => return None
180 Some(Local
::new(idx
))
183 /// Counts the number of locals, such that that local_index
184 /// will always return an index smaller than this count.
185 pub fn count_locals(&self) -> usize {
186 self.arg_decls
.len() +
187 self.var_decls
.len() +
188 self.temp_decls
.len() + 1
192 impl<'tcx
> Index
<BasicBlock
> for Mir
<'tcx
> {
193 type Output
= BasicBlockData
<'tcx
>;
196 fn index(&self, index
: BasicBlock
) -> &BasicBlockData
<'tcx
> {
197 &self.basic_blocks()[index
]
201 impl<'tcx
> IndexMut
<BasicBlock
> for Mir
<'tcx
> {
203 fn index_mut(&mut self, index
: BasicBlock
) -> &mut BasicBlockData
<'tcx
> {
204 &mut self.basic_blocks_mut()[index
]
208 /// Grouped information about the source code origin of a MIR entity.
209 /// Intended to be inspected by diagnostics and debuginfo.
210 /// Most passes can work with it as a whole, within a single function.
211 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
212 pub struct SourceInfo
{
213 /// Source span for the AST pertaining to this MIR entity.
216 /// The lexical visibility scope, i.e. which bindings can be seen.
217 pub scope
: VisibilityScope
220 ///////////////////////////////////////////////////////////////////////////
221 // Mutability and borrow kinds
223 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
224 pub enum Mutability
{
229 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
230 pub enum BorrowKind
{
231 /// Data must be immutable and is aliasable.
234 /// Data must be immutable but not aliasable. This kind of borrow
235 /// cannot currently be expressed by the user and is used only in
236 /// implicit closure bindings. It is needed when you the closure
237 /// is borrowing or mutating a mutable referent, e.g.:
239 /// let x: &mut isize = ...;
240 /// let y = || *x += 5;
242 /// If we were to try to translate this closure into a more explicit
243 /// form, we'd encounter an error with the code as written:
245 /// struct Env { x: & &mut isize }
246 /// let x: &mut isize = ...;
247 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
248 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
250 /// This is then illegal because you cannot mutate a `&mut` found
251 /// in an aliasable location. To solve, you'd have to translate with
252 /// an `&mut` borrow:
254 /// struct Env { x: & &mut isize }
255 /// let x: &mut isize = ...;
256 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
257 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
259 /// Now the assignment to `**env.x` is legal, but creating a
260 /// mutable pointer to `x` is not because `x` is not mutable. We
261 /// could fix this by declaring `x` as `let mut x`. This is ok in
262 /// user code, if awkward, but extra weird for closures, since the
263 /// borrow is hidden.
265 /// So we introduce a "unique imm" borrow -- the referent is
266 /// immutable, but not aliasable. This solves the problem. For
267 /// simplicity, we don't give users the way to express this
268 /// borrow, it's just used when translating closures.
271 /// Data is mutable and not aliasable.
275 ///////////////////////////////////////////////////////////////////////////
276 // Variables and temps
278 /// A "variable" is a binding declared by the user as part of the fn
279 /// decl, a let, etc.
280 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
281 pub struct VarDecl
<'tcx
> {
282 /// `let mut x` vs `let x`
283 pub mutability
: Mutability
,
285 /// name that user gave the variable; not that, internally,
286 /// mir references variables by index
289 /// type inferred for this variable (`let x: ty = ...`)
292 /// source information (span, scope, etc.) for the declaration
293 pub source_info
: SourceInfo
,
296 /// A "temp" is a temporary that we place on the stack. They are
297 /// anonymous, always mutable, and have only a type.
298 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
299 pub struct TempDecl
<'tcx
> {
303 /// A "arg" is one of the function's formal arguments. These are
304 /// anonymous and distinct from the bindings that the user declares.
306 /// For example, in this function:
309 /// fn foo((x, y): (i32, u32)) { ... }
312 /// there is only one argument, of type `(i32, u32)`, but two bindings
314 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
315 pub struct ArgDecl
<'tcx
> {
318 /// If true, this argument is a tuple after monomorphization,
319 /// and has to be collected from multiple actual arguments.
322 /// Either keywords::Invalid or the name of a single-binding
323 /// pattern associated with this argument. Useful for debuginfo.
327 /// A closure capture, with its name and mode.
328 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
329 pub struct UpvarDecl
{
330 pub debug_name
: Name
,
332 /// If true, the capture is behind a reference.
336 ///////////////////////////////////////////////////////////////////////////
339 newtype_index
!(BasicBlock
, "bb");
341 ///////////////////////////////////////////////////////////////////////////
342 // BasicBlockData and Terminator
344 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
345 pub struct BasicBlockData
<'tcx
> {
346 /// List of statements in this block.
347 pub statements
: Vec
<Statement
<'tcx
>>,
349 /// Terminator for this block.
351 /// NB. This should generally ONLY be `None` during construction.
352 /// Therefore, you should generally access it via the
353 /// `terminator()` or `terminator_mut()` methods. The only
354 /// exception is that certain passes, such as `simplify_cfg`, swap
355 /// out the terminator temporarily with `None` while they continue
356 /// to recurse over the set of basic blocks.
357 pub terminator
: Option
<Terminator
<'tcx
>>,
359 /// If true, this block lies on an unwind path. This is used
360 /// during trans where distinct kinds of basic blocks may be
361 /// generated (particularly for MSVC cleanup). Unwind blocks must
362 /// only branch to other unwind blocks.
363 pub is_cleanup
: bool
,
366 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
367 pub struct Terminator
<'tcx
> {
368 pub source_info
: SourceInfo
,
369 pub kind
: TerminatorKind
<'tcx
>
372 #[derive(Clone, RustcEncodable, RustcDecodable)]
373 pub enum TerminatorKind
<'tcx
> {
374 /// block should have one successor in the graph; we jump there
379 /// jump to branch 0 if this lvalue evaluates to true
382 targets
: (BasicBlock
, BasicBlock
),
385 /// lvalue evaluates to some enum; jump depending on the branch
388 adt_def
: AdtDef
<'tcx
>,
389 targets
: Vec
<BasicBlock
>,
392 /// operand evaluates to an integer; jump depending on its value
393 /// to one of the targets, and otherwise fallback to `otherwise`
395 /// discriminant value being tested
398 /// type of value being tested
401 /// Possible values. The locations to branch to in each case
402 /// are found in the corresponding indices from the `targets` vector.
403 values
: Vec
<ConstVal
>,
405 /// Possible branch sites. The length of this vector should be
406 /// equal to the length of the `values` vector plus 1 -- the
407 /// extra item is the block to branch to if none of the values
409 targets
: Vec
<BasicBlock
>,
412 /// Indicates that the landing pad is finished and unwinding should
413 /// continue. Emitted by build::scope::diverge_cleanup.
416 /// Indicates a normal return. The ReturnPointer lvalue should
417 /// have been filled in by now. This should occur at most once.
420 /// Indicates a terminator that can never be reached.
425 location
: Lvalue
<'tcx
>,
427 unwind
: Option
<BasicBlock
>
430 /// Drop the Lvalue and assign the new value over it
432 location
: Lvalue
<'tcx
>,
433 value
: Operand
<'tcx
>,
435 unwind
: Option
<BasicBlock
>,
438 /// Block ends with a call of a converging function
440 /// The function that’s being called
442 /// Arguments the function is called with
443 args
: Vec
<Operand
<'tcx
>>,
444 /// Destination for the return value. If some, the call is converging.
445 destination
: Option
<(Lvalue
<'tcx
>, BasicBlock
)>,
446 /// Cleanups to be done if the call unwinds.
447 cleanup
: Option
<BasicBlock
>
450 /// Jump to the target if the condition has the expected value,
451 /// otherwise panic with a message and a cleanup target.
455 msg
: AssertMessage
<'tcx
>,
457 cleanup
: Option
<BasicBlock
>
461 impl<'tcx
> Terminator
<'tcx
> {
462 pub fn successors(&self) -> Cow
<[BasicBlock
]> {
463 self.kind
.successors()
466 pub fn successors_mut(&mut self) -> Vec
<&mut BasicBlock
> {
467 self.kind
.successors_mut()
471 impl<'tcx
> TerminatorKind
<'tcx
> {
472 pub fn successors(&self) -> Cow
<[BasicBlock
]> {
473 use self::TerminatorKind
::*;
475 Goto { target: ref b }
=> slice
::ref_slice(b
).into_cow(),
476 If { targets: (b1, b2), .. }
=> vec
![b1
, b2
].into_cow(),
477 Switch { targets: ref b, .. }
=> b
[..].into_cow(),
478 SwitchInt { targets: ref b, .. }
=> b
[..].into_cow(),
479 Resume
=> (&[]).into_cow(),
480 Return
=> (&[]).into_cow(),
481 Unreachable
=> (&[]).into_cow(),
482 Call { destination: Some((_, t)), cleanup: Some(c), .. }
=> vec
![t
, c
].into_cow(),
483 Call { destination: Some((_, ref t)), cleanup: None, .. }
=>
484 slice
::ref_slice(t
).into_cow(),
485 Call { destination: None, cleanup: Some(ref c), .. }
=> slice
::ref_slice(c
).into_cow(),
486 Call { destination: None, cleanup: None, .. }
=> (&[]).into_cow(),
487 DropAndReplace { target, unwind: Some(unwind), .. }
|
488 Drop { target, unwind: Some(unwind), .. }
=> {
489 vec
![target
, unwind
].into_cow()
491 DropAndReplace { ref target, unwind: None, .. }
|
492 Drop { ref target, unwind: None, .. }
=> {
493 slice
::ref_slice(target
).into_cow()
495 Assert { target, cleanup: Some(unwind), .. }
=> vec
![target
, unwind
].into_cow(),
496 Assert { ref target, .. }
=> slice
::ref_slice(target
).into_cow(),
500 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
501 // `Vec<&mut BasicBlock>` would look like in the first place.
502 pub fn successors_mut(&mut self) -> Vec
<&mut BasicBlock
> {
503 use self::TerminatorKind
::*;
505 Goto { target: ref mut b }
=> vec
![b
],
506 If { targets: (ref mut b1, ref mut b2), .. }
=> vec
![b1
, b2
],
507 Switch { targets: ref mut b, .. }
=> b
.iter_mut().collect(),
508 SwitchInt { targets: ref mut b, .. }
=> b
.iter_mut().collect(),
509 Resume
=> Vec
::new(),
510 Return
=> Vec
::new(),
511 Unreachable
=> Vec
::new(),
512 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. }
=> vec
![t
, c
],
513 Call { destination: Some((_, ref mut t)), cleanup: None, .. }
=> vec
![t
],
514 Call { destination: None, cleanup: Some(ref mut c), .. }
=> vec
![c
],
515 Call { destination: None, cleanup: None, .. }
=> vec
![],
516 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. }
|
517 Drop { ref mut target, unwind: Some(ref mut unwind), .. }
=> vec
![target
, unwind
],
518 DropAndReplace { ref mut target, unwind: None, .. }
|
519 Drop { ref mut target, unwind: None, .. }
=> {
522 Assert { ref mut target, cleanup: Some(ref mut unwind), .. }
=> vec
![target
, unwind
],
523 Assert { ref mut target, .. }
=> vec
![target
]
528 impl<'tcx
> BasicBlockData
<'tcx
> {
529 pub fn new(terminator
: Option
<Terminator
<'tcx
>>) -> BasicBlockData
<'tcx
> {
532 terminator
: terminator
,
537 /// Accessor for terminator.
539 /// Terminator may not be None after construction of the basic block is complete. This accessor
540 /// provides a convenience way to reach the terminator.
541 pub fn terminator(&self) -> &Terminator
<'tcx
> {
542 self.terminator
.as_ref().expect("invalid terminator state")
545 pub fn terminator_mut(&mut self) -> &mut Terminator
<'tcx
> {
546 self.terminator
.as_mut().expect("invalid terminator state")
550 impl<'tcx
> Debug
for TerminatorKind
<'tcx
> {
551 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
553 let successors
= self.successors();
554 let labels
= self.fmt_successor_labels();
555 assert_eq
!(successors
.len(), labels
.len());
557 match successors
.len() {
560 1 => write
!(fmt
, " -> {:?}", successors
[0]),
563 write
!(fmt
, " -> [")?
;
564 for (i
, target
) in successors
.iter().enumerate() {
568 write
!(fmt
, "{}: {:?}", labels
[i
], target
)?
;
577 impl<'tcx
> TerminatorKind
<'tcx
> {
578 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
579 /// successor basic block, if any. The only information not inlcuded is the list of possible
580 /// successors, which may be rendered differently between the text and the graphviz format.
581 pub fn fmt_head
<W
: Write
>(&self, fmt
: &mut W
) -> fmt
::Result
{
582 use self::TerminatorKind
::*;
584 Goto { .. }
=> write
!(fmt
, "goto"),
585 If { cond: ref lv, .. }
=> write
!(fmt
, "if({:?})", lv
),
586 Switch { discr: ref lv, .. }
=> write
!(fmt
, "switch({:?})", lv
),
587 SwitchInt { discr: ref lv, .. }
=> write
!(fmt
, "switchInt({:?})", lv
),
588 Return
=> write
!(fmt
, "return"),
589 Resume
=> write
!(fmt
, "resume"),
590 Unreachable
=> write
!(fmt
, "unreachable"),
591 Drop { ref location, .. }
=> write
!(fmt
, "drop({:?})", location
),
592 DropAndReplace { ref location, ref value, .. }
=>
593 write
!(fmt
, "replace({:?} <- {:?})", location
, value
),
594 Call { ref func, ref args, ref destination, .. }
=> {
595 if let Some((ref destination
, _
)) = *destination
{
596 write
!(fmt
, "{:?} = ", destination
)?
;
598 write
!(fmt
, "{:?}(", func
)?
;
599 for (index
, arg
) in args
.iter().enumerate() {
603 write
!(fmt
, "{:?}", arg
)?
;
607 Assert { ref cond, expected, ref msg, .. }
=> {
608 write
!(fmt
, "assert(")?
;
612 write
!(fmt
, "{:?}, ", cond
)?
;
615 AssertMessage
::BoundsCheck { ref len, ref index }
=> {
616 write
!(fmt
, "{:?}, {:?}, {:?}",
617 "index out of bounds: the len is {} but the index is {}",
620 AssertMessage
::Math(ref err
) => {
621 write
!(fmt
, "{:?}", err
.description())?
;
630 /// Return the list of labels for the edges to the successor basic blocks.
631 pub fn fmt_successor_labels(&self) -> Vec
<Cow
<'
static, str>> {
632 use self::TerminatorKind
::*;
634 Return
| Resume
| Unreachable
=> vec
![],
635 Goto { .. }
=> vec
!["".into()],
636 If { .. }
=> vec
!["true".into(), "false".into()],
637 Switch { ref adt_def, .. }
=> {
640 .map(|variant
| variant
.name
.to_string().into())
643 SwitchInt { ref values, .. }
=> {
646 let mut buf
= String
::new();
647 fmt_const_val(&mut buf
, const_val
).unwrap();
650 .chain(iter
::once(String
::from("otherwise").into()))
653 Call { destination: Some(_), cleanup: Some(_), .. }
=>
654 vec
!["return".into_cow(), "unwind".into_cow()],
655 Call { destination: Some(_), cleanup: None, .. }
=> vec
!["return".into_cow()],
656 Call { destination: None, cleanup: Some(_), .. }
=> vec
!["unwind".into_cow()],
657 Call { destination: None, cleanup: None, .. }
=> vec
![],
658 DropAndReplace { unwind: None, .. }
|
659 Drop { unwind: None, .. }
=> vec
!["return".into_cow()],
660 DropAndReplace { unwind: Some(_), .. }
|
661 Drop { unwind: Some(_), .. }
=> {
662 vec
!["return".into_cow(), "unwind".into_cow()]
664 Assert { cleanup: None, .. }
=> vec
!["".into()],
666 vec
!["success".into_cow(), "unwind".into_cow()]
671 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
672 pub enum AssertMessage
<'tcx
> {
680 ///////////////////////////////////////////////////////////////////////////
683 #[derive(Clone, RustcEncodable, RustcDecodable)]
684 pub struct Statement
<'tcx
> {
685 pub source_info
: SourceInfo
,
686 pub kind
: StatementKind
<'tcx
>,
689 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
690 pub enum StatementKind
<'tcx
> {
691 Assign(Lvalue
<'tcx
>, Rvalue
<'tcx
>),
694 impl<'tcx
> Debug
for Statement
<'tcx
> {
695 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
696 use self::StatementKind
::*;
698 Assign(ref lv
, ref rv
) => write
!(fmt
, "{:?} = {:?}", lv
, rv
)
703 ///////////////////////////////////////////////////////////////////////////
706 newtype_index
!(Var
, "var");
707 newtype_index
!(Temp
, "tmp");
708 newtype_index
!(Arg
, "arg");
709 newtype_index
!(Local
, "local");
711 /// A path to a value; something that can be evaluated without
712 /// changing or disturbing program state.
713 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
714 pub enum Lvalue
<'tcx
> {
715 /// local variable declared by the user
718 /// temporary introduced during lowering into MIR
721 /// formal parameter of the function; note that these are NOT the
722 /// bindings that the user declares, which are vars
725 /// static or static mut variable
728 /// the return pointer of the fn
731 /// projection out of an lvalue (access a field, deref a pointer, etc)
732 Projection(Box
<LvalueProjection
<'tcx
>>),
735 /// The `Projection` data structure defines things of the form `B.x`
736 /// or `*B` or `B[index]`. Note that it is parameterized because it is
737 /// shared between `Constant` and `Lvalue`. See the aliases
738 /// `LvalueProjection` etc below.
739 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
740 pub struct Projection
<'tcx
, B
, V
> {
742 pub elem
: ProjectionElem
<'tcx
, V
>,
745 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
746 pub enum ProjectionElem
<'tcx
, V
> {
748 Field(Field
, Ty
<'tcx
>),
751 /// These indices are generated by slice patterns. Easiest to explain
755 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
756 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
757 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
758 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
761 /// index or -index (in Python terms), depending on from_end
763 /// thing being indexed must be at least this long
765 /// counting backwards from end?
769 /// These indices are generated by slice patterns.
771 /// slice[from:-to] in Python terms.
777 /// "Downcast" to a variant of an ADT. Currently, we only introduce
778 /// this for ADTs with more than one variant. It may be better to
779 /// just introduce it always, or always for enums.
780 Downcast(AdtDef
<'tcx
>, usize),
783 /// Alias for projections as they appear in lvalues, where the base is an lvalue
784 /// and the index is an operand.
785 pub type LvalueProjection
<'tcx
> = Projection
<'tcx
, Lvalue
<'tcx
>, Operand
<'tcx
>>;
787 /// Alias for projections as they appear in lvalues, where the base is an lvalue
788 /// and the index is an operand.
789 pub type LvalueElem
<'tcx
> = ProjectionElem
<'tcx
, Operand
<'tcx
>>;
791 newtype_index
!(Field
, "field");
793 impl<'tcx
> Lvalue
<'tcx
> {
794 pub fn field(self, f
: Field
, ty
: Ty
<'tcx
>) -> Lvalue
<'tcx
> {
795 self.elem(ProjectionElem
::Field(f
, ty
))
798 pub fn deref(self) -> Lvalue
<'tcx
> {
799 self.elem(ProjectionElem
::Deref
)
802 pub fn index(self, index
: Operand
<'tcx
>) -> Lvalue
<'tcx
> {
803 self.elem(ProjectionElem
::Index(index
))
806 pub fn elem(self, elem
: LvalueElem
<'tcx
>) -> Lvalue
<'tcx
> {
807 Lvalue
::Projection(Box
::new(LvalueProjection
{
814 impl<'tcx
> Debug
for Lvalue
<'tcx
> {
815 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
819 Var(id
) => write
!(fmt
, "{:?}", id
),
820 Arg(id
) => write
!(fmt
, "{:?}", id
),
821 Temp(id
) => write
!(fmt
, "{:?}", id
),
823 write
!(fmt
, "{}", ty
::tls
::with(|tcx
| tcx
.item_path_str(def_id
))),
825 write
!(fmt
, "return"),
826 Projection(ref data
) =>
828 ProjectionElem
::Downcast(ref adt_def
, index
) =>
829 write
!(fmt
, "({:?} as {})", data
.base
, adt_def
.variants
[index
].name
),
830 ProjectionElem
::Deref
=>
831 write
!(fmt
, "(*{:?})", data
.base
),
832 ProjectionElem
::Field(field
, ty
) =>
833 write
!(fmt
, "({:?}.{:?}: {:?})", data
.base
, field
.index(), ty
),
834 ProjectionElem
::Index(ref index
) =>
835 write
!(fmt
, "{:?}[{:?}]", data
.base
, index
),
836 ProjectionElem
::ConstantIndex { offset, min_length, from_end: false }
=>
837 write
!(fmt
, "{:?}[{:?} of {:?}]", data
.base
, offset
, min_length
),
838 ProjectionElem
::ConstantIndex { offset, min_length, from_end: true }
=>
839 write
!(fmt
, "{:?}[-{:?} of {:?}]", data
.base
, offset
, min_length
),
840 ProjectionElem
::Subslice { from, to }
if to
== 0 =>
841 write
!(fmt
, "{:?}[{:?}:", data
.base
, from
),
842 ProjectionElem
::Subslice { from, to }
if from
== 0 =>
843 write
!(fmt
, "{:?}[:-{:?}]", data
.base
, to
),
844 ProjectionElem
::Subslice { from, to }
=>
845 write
!(fmt
, "{:?}[{:?}:-{:?}]", data
.base
,
853 ///////////////////////////////////////////////////////////////////////////
856 newtype_index
!(VisibilityScope
, "scope");
857 pub const ARGUMENT_VISIBILITY_SCOPE
: VisibilityScope
= VisibilityScope(0);
859 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
860 pub struct VisibilityScopeData
{
862 pub parent_scope
: Option
<VisibilityScope
>,
865 ///////////////////////////////////////////////////////////////////////////
868 /// These are values that can appear inside an rvalue (or an index
869 /// lvalue). They are intentionally limited to prevent rvalues from
870 /// being nested in one another.
871 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
872 pub enum Operand
<'tcx
> {
873 Consume(Lvalue
<'tcx
>),
874 Constant(Constant
<'tcx
>),
877 impl<'tcx
> Debug
for Operand
<'tcx
> {
878 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
879 use self::Operand
::*;
881 Constant(ref a
) => write
!(fmt
, "{:?}", a
),
882 Consume(ref lv
) => write
!(fmt
, "{:?}", lv
),
887 ///////////////////////////////////////////////////////////////////////////
890 #[derive(Clone, RustcEncodable, RustcDecodable)]
891 pub enum Rvalue
<'tcx
> {
892 /// x (either a move or copy, depending on type of x)
896 Repeat(Operand
<'tcx
>, TypedConstVal
<'tcx
>),
899 Ref(Region
, BorrowKind
, Lvalue
<'tcx
>),
901 /// length of a [X] or [X;n] value
904 Cast(CastKind
, Operand
<'tcx
>, Ty
<'tcx
>),
906 BinaryOp(BinOp
, Operand
<'tcx
>, Operand
<'tcx
>),
907 CheckedBinaryOp(BinOp
, Operand
<'tcx
>, Operand
<'tcx
>),
909 UnaryOp(UnOp
, Operand
<'tcx
>),
911 /// Creates an *uninitialized* Box
914 /// Create an aggregate value, like a tuple or struct. This is
915 /// only needed because we want to distinguish `dest = Foo { x:
916 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
917 /// that `Foo` has a destructor. These rvalues can be optimized
918 /// away after type-checking and before lowering.
919 Aggregate(AggregateKind
<'tcx
>, Vec
<Operand
<'tcx
>>),
923 outputs
: Vec
<Lvalue
<'tcx
>>,
924 inputs
: Vec
<Operand
<'tcx
>>
928 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
932 /// Convert unique, zero-sized type for a fn to fn()
935 /// Convert safe fn() to unsafe fn()
938 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
939 /// trans must figure out the details once full monomorphization
940 /// is known. For example, this could be used to cast from a
941 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
942 /// (presuming `T: Trait`).
946 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
947 pub enum AggregateKind
<'tcx
> {
950 Adt(AdtDef
<'tcx
>, usize, &'tcx Substs
<'tcx
>),
951 Closure(DefId
, ClosureSubsts
<'tcx
>),
954 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
956 /// The `+` operator (addition)
958 /// The `-` operator (subtraction)
960 /// The `*` operator (multiplication)
962 /// The `/` operator (division)
964 /// The `%` operator (modulus)
966 /// The `^` operator (bitwise xor)
968 /// The `&` operator (bitwise and)
970 /// The `|` operator (bitwise or)
972 /// The `<<` operator (shift left)
974 /// The `>>` operator (shift right)
976 /// The `==` operator (equality)
978 /// The `<` operator (less than)
980 /// The `<=` operator (less than or equal to)
982 /// The `!=` operator (not equal to)
984 /// The `>=` operator (greater than or equal to)
986 /// The `>` operator (greater than)
991 pub fn is_checkable(self) -> bool
{
994 Add
| Sub
| Mul
| Shl
| Shr
=> true,
1000 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1002 /// The `!` operator for logical inversion
1004 /// The `-` operator for negation
1008 impl<'tcx
> Debug
for Rvalue
<'tcx
> {
1009 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
1010 use self::Rvalue
::*;
1013 Use(ref lvalue
) => write
!(fmt
, "{:?}", lvalue
),
1014 Repeat(ref a
, ref b
) => write
!(fmt
, "[{:?}; {:?}]", a
, b
),
1015 Len(ref a
) => write
!(fmt
, "Len({:?})", a
),
1016 Cast(ref kind
, ref lv
, ref ty
) => write
!(fmt
, "{:?} as {:?} ({:?})", lv
, ty
, kind
),
1017 BinaryOp(ref op
, ref a
, ref b
) => write
!(fmt
, "{:?}({:?}, {:?})", op
, a
, b
),
1018 CheckedBinaryOp(ref op
, ref a
, ref b
) => {
1019 write
!(fmt
, "Checked{:?}({:?}, {:?})", op
, a
, b
)
1021 UnaryOp(ref op
, ref a
) => write
!(fmt
, "{:?}({:?})", op
, a
),
1022 Box(ref t
) => write
!(fmt
, "Box({:?})", t
),
1023 InlineAsm { ref asm, ref outputs, ref inputs }
=> {
1024 write
!(fmt
, "asm!({:?} : {:?} : {:?})", asm
, outputs
, inputs
)
1027 Ref(_
, borrow_kind
, ref lv
) => {
1028 let kind_str
= match borrow_kind
{
1029 BorrowKind
::Shared
=> "",
1030 BorrowKind
::Mut
| BorrowKind
::Unique
=> "mut ",
1032 write
!(fmt
, "&{}{:?}", kind_str
, lv
)
1035 Aggregate(ref kind
, ref lvs
) => {
1036 use self::AggregateKind
::*;
1038 fn fmt_tuple(fmt
: &mut Formatter
, lvs
: &[Operand
]) -> fmt
::Result
{
1039 let mut tuple_fmt
= fmt
.debug_tuple("");
1041 tuple_fmt
.field(lv
);
1047 Vec
=> write
!(fmt
, "{:?}", lvs
),
1051 0 => write
!(fmt
, "()"),
1052 1 => write
!(fmt
, "({:?},)", lvs
[0]),
1053 _
=> fmt_tuple(fmt
, lvs
),
1057 Adt(adt_def
, variant
, substs
) => {
1058 let variant_def
= &adt_def
.variants
[variant
];
1060 ppaux
::parameterized(fmt
, substs
, variant_def
.did
,
1061 ppaux
::Ns
::Value
, &[],
1063 Some(tcx
.lookup_item_type(variant_def
.did
).generics
)
1066 match variant_def
.kind() {
1067 ty
::VariantKind
::Unit
=> Ok(()),
1068 ty
::VariantKind
::Tuple
=> fmt_tuple(fmt
, lvs
),
1069 ty
::VariantKind
::Struct
=> {
1070 let mut struct_fmt
= fmt
.debug_struct("");
1071 for (field
, lv
) in variant_def
.fields
.iter().zip(lvs
) {
1072 struct_fmt
.field(&field
.name
.as_str(), lv
);
1079 Closure(def_id
, _
) => ty
::tls
::with(|tcx
| {
1080 if let Some(node_id
) = tcx
.map
.as_local_node_id(def_id
) {
1081 let name
= format
!("[closure@{:?}]", tcx
.map
.span(node_id
));
1082 let mut struct_fmt
= fmt
.debug_struct(&name
);
1084 tcx
.with_freevars(node_id
, |freevars
| {
1085 for (freevar
, lv
) in freevars
.iter().zip(lvs
) {
1086 let var_name
= tcx
.local_var_name_str(freevar
.def
.var_id());
1087 struct_fmt
.field(&var_name
, lv
);
1093 write
!(fmt
, "[closure]")
1102 ///////////////////////////////////////////////////////////////////////////
1105 /// Two constants are equal if they are the same constant. Note that
1106 /// this does not necessarily mean that they are "==" in Rust -- in
1107 /// particular one must be wary of `NaN`!
1109 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1110 pub struct Constant
<'tcx
> {
1113 pub literal
: Literal
<'tcx
>,
1116 #[derive(Clone, RustcEncodable, RustcDecodable)]
1117 pub struct TypedConstVal
<'tcx
> {
1120 pub value
: ConstUsize
,
1123 impl<'tcx
> Debug
for TypedConstVal
<'tcx
> {
1124 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
1125 write
!(fmt
, "const {}", ConstInt
::Usize(self.value
))
1129 newtype_index
!(Promoted
, "promoted");
1131 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1132 pub enum Literal
<'tcx
> {
1135 substs
: &'tcx Substs
<'tcx
>,
1141 // Index into the `promoted` vector of `Mir`.
1146 impl<'tcx
> Debug
for Constant
<'tcx
> {
1147 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
1148 write
!(fmt
, "{:?}", self.literal
)
1152 impl<'tcx
> Debug
for Literal
<'tcx
> {
1153 fn fmt(&self, fmt
: &mut Formatter
) -> fmt
::Result
{
1154 use self::Literal
::*;
1156 Item { def_id, substs }
=> {
1157 ppaux
::parameterized(
1158 fmt
, substs
, def_id
, ppaux
::Ns
::Value
, &[],
1159 |tcx
| Some(tcx
.lookup_item_type(def_id
).generics
))
1161 Value { ref value }
=> {
1162 write
!(fmt
, "const ")?
;
1163 fmt_const_val(fmt
, value
)
1165 Promoted { index }
=> {
1166 write
!(fmt
, "{:?}", index
)
1172 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1173 fn fmt_const_val
<W
: Write
>(fmt
: &mut W
, const_val
: &ConstVal
) -> fmt
::Result
{
1174 use middle
::const_val
::ConstVal
::*;
1176 Float(f
) => write
!(fmt
, "{:?}", f
),
1177 Integral(n
) => write
!(fmt
, "{}", n
),
1178 Str(ref s
) => write
!(fmt
, "{:?}", s
),
1179 ByteStr(ref bytes
) => {
1180 let escaped
: String
= bytes
1182 .flat_map(|&ch
| ascii
::escape_default(ch
).map(|c
| c
as char))
1184 write
!(fmt
, "b\"{}\"", escaped
)
1186 Bool(b
) => write
!(fmt
, "{:?}", b
),
1187 Function(def_id
) => write
!(fmt
, "{}", item_path_str(def_id
)),
1188 Struct(node_id
) | Tuple(node_id
) | Array(node_id
, _
) | Repeat(node_id
, _
) =>
1189 write
!(fmt
, "{}", node_to_string(node_id
)),
1190 Char(c
) => write
!(fmt
, "{:?}", c
),
1195 fn node_to_string(node_id
: ast
::NodeId
) -> String
{
1196 ty
::tls
::with(|tcx
| tcx
.map
.node_to_user_string(node_id
))
1199 fn item_path_str(def_id
: DefId
) -> String
{
1200 ty
::tls
::with(|tcx
| tcx
.item_path_str(def_id
))
1203 impl<'tcx
> ControlFlowGraph
for Mir
<'tcx
> {
1205 type Node
= BasicBlock
;
1207 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1209 fn start_node(&self) -> Self::Node { START_BLOCK }
1211 fn predecessors
<'graph
>(&'graph
self, node
: Self::Node
)
1212 -> <Self as GraphPredecessors
<'graph
>>::Iter
1214 self.predecessors_for(node
).clone().into_iter()
1216 fn successors
<'graph
>(&'graph
self, node
: Self::Node
)
1217 -> <Self as GraphSuccessors
<'graph
>>::Iter
1219 self.basic_blocks
[node
].terminator().successors().into_owned().into_iter()
1223 impl<'a
, 'b
> GraphPredecessors
<'b
> for Mir
<'a
> {
1224 type Item
= BasicBlock
;
1225 type Iter
= IntoIter
<BasicBlock
>;
1228 impl<'a
, 'b
> GraphSuccessors
<'b
> for Mir
<'a
> {
1229 type Item
= BasicBlock
;
1230 type Iter
= IntoIter
<BasicBlock
>;