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, 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: Ty<'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>>,
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 /// Write the RHS Rvalue to the LHS Lvalue.
692 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
694 /// Write the discriminant for a variant to the enum Lvalue.
695 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
697 /// Start a live range for the storage of the local.
698 StorageLive(Lvalue<'tcx>),
700 /// End the current live range for the storage of the local.
701 StorageDead(Lvalue<'tcx>),
704 impl<'tcx> Debug for Statement<'tcx> {
705 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
706 use self::StatementKind::*;
708 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
709 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
710 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
711 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
712 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
718 ///////////////////////////////////////////////////////////////////////////
721 newtype_index!(Var, "var");
722 newtype_index!(Temp, "tmp");
723 newtype_index!(Arg, "arg");
724 newtype_index!(Local, "local");
726 /// A path to a value; something that can be evaluated without
727 /// changing or disturbing program state.
728 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
729 pub enum Lvalue<'tcx> {
730 /// local variable declared by the user
733 /// temporary introduced during lowering into MIR
736 /// formal parameter of the function; note that these are NOT the
737 /// bindings that the user declares, which are vars
740 /// static or static mut variable
743 /// the return pointer of the fn
746 /// projection out of an lvalue (access a field, deref a pointer, etc)
747 Projection(Box<LvalueProjection<'tcx>>),
750 /// The `Projection` data structure defines things of the form `B.x`
751 /// or `*B` or `B[index]`. Note that it is parameterized because it is
752 /// shared between `Constant` and `Lvalue`. See the aliases
753 /// `LvalueProjection` etc below.
754 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
755 pub struct Projection<'tcx, B, V> {
757 pub elem: ProjectionElem<'tcx, V>,
760 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
761 pub enum ProjectionElem<'tcx, V> {
763 Field(Field, Ty<'tcx>),
766 /// These indices are generated by slice patterns. Easiest to explain
770 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
771 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
772 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
773 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
776 /// index or -index (in Python terms), depending on from_end
778 /// thing being indexed must be at least this long
780 /// counting backwards from end?
784 /// These indices are generated by slice patterns.
786 /// slice[from:-to] in Python terms.
792 /// "Downcast" to a variant of an ADT. Currently, we only introduce
793 /// this for ADTs with more than one variant. It may be better to
794 /// just introduce it always, or always for enums.
795 Downcast(AdtDef<'tcx>, usize),
798 /// Alias for projections as they appear in lvalues, where the base is an lvalue
799 /// and the index is an operand.
800 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
802 /// Alias for projections as they appear in lvalues, where the base is an lvalue
803 /// and the index is an operand.
804 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
806 newtype_index!(Field, "field");
808 impl<'tcx> Lvalue<'tcx> {
809 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
810 self.elem(ProjectionElem::Field(f, ty))
813 pub fn deref(self) -> Lvalue<'tcx> {
814 self.elem(ProjectionElem::Deref)
817 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
818 self.elem(ProjectionElem::Index(index))
821 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
822 Lvalue::Projection(Box::new(LvalueProjection {
829 impl<'tcx> Debug for Lvalue<'tcx> {
830 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
834 Var(id) => write!(fmt, "{:?}", id),
835 Arg(id) => write!(fmt, "{:?}", id),
836 Temp(id) => write!(fmt, "{:?}", id),
838 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
840 write!(fmt, "return"),
841 Projection(ref data) =>
843 ProjectionElem::Downcast(ref adt_def, index) =>
844 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
845 ProjectionElem::Deref =>
846 write!(fmt, "(*{:?})", data.base),
847 ProjectionElem::Field(field, ty) =>
848 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
849 ProjectionElem::Index(ref index) =>
850 write!(fmt, "{:?}[{:?}]", data.base, index),
851 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
852 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
853 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
854 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
855 ProjectionElem::Subslice { from, to } if to == 0 =>
856 write!(fmt, "{:?}[{:?}:", data.base, from),
857 ProjectionElem::Subslice { from, to } if from == 0 =>
858 write!(fmt, "{:?}[:-{:?}]", data.base, to),
859 ProjectionElem::Subslice { from, to } =>
860 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
868 ///////////////////////////////////////////////////////////////////////////
871 newtype_index!(VisibilityScope, "scope");
872 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
874 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
875 pub struct VisibilityScopeData {
877 pub parent_scope: Option<VisibilityScope>,
880 ///////////////////////////////////////////////////////////////////////////
883 /// These are values that can appear inside an rvalue (or an index
884 /// lvalue). They are intentionally limited to prevent rvalues from
885 /// being nested in one another.
886 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
887 pub enum Operand<'tcx> {
888 Consume(Lvalue<'tcx>),
889 Constant(Constant<'tcx>),
892 impl<'tcx> Debug for Operand<'tcx> {
893 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
894 use self::Operand::*;
896 Constant(ref a) => write!(fmt, "{:?}", a),
897 Consume(ref lv) => write!(fmt, "{:?}", lv),
902 ///////////////////////////////////////////////////////////////////////////
905 #[derive(Clone, RustcEncodable, RustcDecodable)]
906 pub enum Rvalue<'tcx> {
907 /// x (either a move or copy, depending on type of x)
911 Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
914 Ref(Region, BorrowKind, Lvalue<'tcx>),
916 /// length of a [X] or [X;n] value
919 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
921 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
922 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
924 UnaryOp(UnOp, Operand<'tcx>),
926 /// Creates an *uninitialized* Box
929 /// Create an aggregate value, like a tuple or struct. This is
930 /// only needed because we want to distinguish `dest = Foo { x:
931 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
932 /// that `Foo` has a destructor. These rvalues can be optimized
933 /// away after type-checking and before lowering.
934 Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
938 outputs: Vec<Lvalue<'tcx>>,
939 inputs: Vec<Operand<'tcx>>
943 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
947 /// Convert unique, zero-sized type for a fn to fn()
950 /// Convert safe fn() to unsafe fn()
953 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
954 /// trans must figure out the details once full monomorphization
955 /// is known. For example, this could be used to cast from a
956 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
957 /// (presuming `T: Trait`).
961 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
962 pub enum AggregateKind<'tcx> {
965 Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>),
966 Closure(DefId, ClosureSubsts<'tcx>),
969 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
971 /// The `+` operator (addition)
973 /// The `-` operator (subtraction)
975 /// The `*` operator (multiplication)
977 /// The `/` operator (division)
979 /// The `%` operator (modulus)
981 /// The `^` operator (bitwise xor)
983 /// The `&` operator (bitwise and)
985 /// The `|` operator (bitwise or)
987 /// The `<<` operator (shift left)
989 /// The `>>` operator (shift right)
991 /// The `==` operator (equality)
993 /// The `<` operator (less than)
995 /// The `<=` operator (less than or equal to)
997 /// The `!=` operator (not equal to)
999 /// The `>=` operator (greater than or equal to)
1001 /// The `>` operator (greater than)
1006 pub fn is_checkable(self) -> bool {
1009 Add | Sub | Mul | Shl | Shr => true,
1015 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1017 /// The `!` operator for logical inversion
1019 /// The `-` operator for negation
1023 impl<'tcx> Debug for Rvalue<'tcx> {
1024 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1025 use self::Rvalue::*;
1028 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1029 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1030 Len(ref a) => write!(fmt, "Len({:?})", a),
1031 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1032 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1033 CheckedBinaryOp(ref op, ref a, ref b) => {
1034 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1036 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1037 Box(ref t) => write!(fmt, "Box({:?})", t),
1038 InlineAsm { ref asm, ref outputs, ref inputs } => {
1039 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1042 Ref(_, borrow_kind, ref lv) => {
1043 let kind_str = match borrow_kind {
1044 BorrowKind::Shared => "",
1045 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1047 write!(fmt, "&{}{:?}", kind_str, lv)
1050 Aggregate(ref kind, ref lvs) => {
1051 use self::AggregateKind::*;
1053 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1054 let mut tuple_fmt = fmt.debug_tuple("");
1056 tuple_fmt.field(lv);
1062 Vec => write!(fmt, "{:?}", lvs),
1066 0 => write!(fmt, "()"),
1067 1 => write!(fmt, "({:?},)", lvs[0]),
1068 _ => fmt_tuple(fmt, lvs),
1072 Adt(adt_def, variant, substs) => {
1073 let variant_def = &adt_def.variants[variant];
1075 ppaux::parameterized(fmt, substs, variant_def.did,
1076 ppaux::Ns::Value, &[])?;
1078 match variant_def.kind {
1079 ty::VariantKind::Unit => Ok(()),
1080 ty::VariantKind::Tuple => fmt_tuple(fmt, lvs),
1081 ty::VariantKind::Struct => {
1082 let mut struct_fmt = fmt.debug_struct("");
1083 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1084 struct_fmt.field(&field.name.as_str(), lv);
1091 Closure(def_id, _) => ty::tls::with(|tcx| {
1092 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
1093 let name = format!("[closure@{:?}]", tcx.map.span(node_id));
1094 let mut struct_fmt = fmt.debug_struct(&name);
1096 tcx.with_freevars(node_id, |freevars| {
1097 for (freevar, lv) in freevars.iter().zip(lvs) {
1098 let var_name = tcx.local_var_name_str(freevar.def.var_id());
1099 struct_fmt.field(&var_name, lv);
1105 write!(fmt, "[closure]")
1114 ///////////////////////////////////////////////////////////////////////////
1117 /// Two constants are equal if they are the same constant. Note that
1118 /// this does not necessarily mean that they are "==" in Rust -- in
1119 /// particular one must be wary of `NaN`!
1121 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1122 pub struct Constant<'tcx> {
1125 pub literal: Literal<'tcx>,
1128 #[derive(Clone, RustcEncodable, RustcDecodable)]
1129 pub struct TypedConstVal<'tcx> {
1132 pub value: ConstUsize,
1135 impl<'tcx> Debug for TypedConstVal<'tcx> {
1136 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1137 write!(fmt, "const {}", ConstInt::Usize(self.value))
1141 newtype_index!(Promoted, "promoted");
1143 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1144 pub enum Literal<'tcx> {
1147 substs: &'tcx Substs<'tcx>,
1153 // Index into the `promoted` vector of `Mir`.
1158 impl<'tcx> Debug for Constant<'tcx> {
1159 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1160 write!(fmt, "{:?}", self.literal)
1164 impl<'tcx> Debug for Literal<'tcx> {
1165 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1166 use self::Literal::*;
1168 Item { def_id, substs } => {
1169 ppaux::parameterized(fmt, substs, def_id, ppaux::Ns::Value, &[])
1171 Value { ref value } => {
1172 write!(fmt, "const ")?;
1173 fmt_const_val(fmt, value)
1175 Promoted { index } => {
1176 write!(fmt, "{:?}", index)
1182 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1183 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1184 use middle::const_val::ConstVal::*;
1186 Float(f) => write!(fmt, "{:?}", f),
1187 Integral(n) => write!(fmt, "{}", n),
1188 Str(ref s) => write!(fmt, "{:?}", s),
1189 ByteStr(ref bytes) => {
1190 let escaped: String = bytes
1192 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1194 write!(fmt, "b\"{}\"", escaped)
1196 Bool(b) => write!(fmt, "{:?}", b),
1197 Function(def_id) => write!(fmt, "{}", item_path_str(def_id)),
1198 Struct(node_id) | Tuple(node_id) | Array(node_id, _) | Repeat(node_id, _) =>
1199 write!(fmt, "{}", node_to_string(node_id)),
1200 Char(c) => write!(fmt, "{:?}", c),
1205 fn node_to_string(node_id: ast::NodeId) -> String {
1206 ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1209 fn item_path_str(def_id: DefId) -> String {
1210 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1213 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1215 type Node = BasicBlock;
1217 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1219 fn start_node(&self) -> Self::Node { START_BLOCK }
1221 fn predecessors<'graph>(&'graph self, node: Self::Node)
1222 -> <Self as GraphPredecessors<'graph>>::Iter
1224 self.predecessors_for(node).clone().into_iter()
1226 fn successors<'graph>(&'graph self, node: Self::Node)
1227 -> <Self as GraphSuccessors<'graph>>::Iter
1229 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1233 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1234 type Item = BasicBlock;
1235 type Iter = IntoIter<BasicBlock>;
1238 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1239 type Item = BasicBlock;
1240 type Iter = IntoIter<BasicBlock>;