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 boolean indicating whether the last argument (which must be a tuple)
97 /// is passed as its individual components at the LLVM level.
99 /// This is used for the "rust-call" ABI.
100 pub spread_last_arg: bool,
102 /// A span representing this MIR, for error reporting
105 /// A cache for various calculations
109 /// where execution begins
110 pub const START_BLOCK: BasicBlock = BasicBlock(0);
112 impl<'tcx> Mir<'tcx> {
113 pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
114 visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
115 promoted: IndexVec<Promoted, Mir<'tcx>>,
117 var_decls: IndexVec<Var, VarDecl<'tcx>>,
118 arg_decls: IndexVec<Arg, ArgDecl<'tcx>>,
119 temp_decls: IndexVec<Temp, TempDecl<'tcx>>,
120 upvar_decls: Vec<UpvarDecl>,
124 basic_blocks: basic_blocks,
125 visibility_scopes: visibility_scopes,
127 return_ty: return_ty,
128 var_decls: var_decls,
129 arg_decls: arg_decls,
130 temp_decls: temp_decls,
131 upvar_decls: upvar_decls,
132 spread_last_arg: false,
139 pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
144 pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
145 self.cache.invalidate();
146 &mut self.basic_blocks
150 pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
151 self.cache.predecessors(self)
155 pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
156 Ref::map(self.predecessors(), |p| &p[bb])
160 pub fn dominators(&self) -> Dominators<BasicBlock> {
164 /// Maps locals (Arg's, Var's, Temp's and ReturnPointer, in that order)
165 /// to their index in the whole list of locals. This is useful if you
166 /// want to treat all locals the same instead of repeating yourself.
167 pub fn local_index(&self, lvalue: &Lvalue<'tcx>) -> Option<Local> {
168 let idx = match *lvalue {
169 Lvalue::Arg(arg) => arg.index(),
170 Lvalue::Var(var) => {
171 self.arg_decls.len() +
174 Lvalue::Temp(temp) => {
175 self.arg_decls.len() +
176 self.var_decls.len() +
179 Lvalue::ReturnPointer => {
180 self.arg_decls.len() +
181 self.var_decls.len() +
182 self.temp_decls.len()
185 Lvalue::Projection(_) => return None
187 Some(Local::new(idx))
190 /// Counts the number of locals, such that local_index
191 /// will always return an index smaller than this count.
192 pub fn count_locals(&self) -> usize {
193 self.arg_decls.len() +
194 self.var_decls.len() +
195 self.temp_decls.len() + 1
198 pub fn format_local(&self, local: Local) -> String {
199 let mut index = local.index();
200 index = match index.checked_sub(self.arg_decls.len()) {
201 None => return format!("{:?}", Arg::new(index)),
202 Some(index) => index,
204 index = match index.checked_sub(self.var_decls.len()) {
205 None => return format!("{:?}", Var::new(index)),
206 Some(index) => index,
208 index = match index.checked_sub(self.temp_decls.len()) {
209 None => return format!("{:?}", Temp::new(index)),
210 Some(index) => index,
212 debug_assert!(index == 0);
213 return "ReturnPointer".to_string()
216 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
217 /// invalidating statement indices in `Location`s.
218 pub fn make_statement_nop(&mut self, location: Location) {
219 let block = &mut self[location.block];
220 debug_assert!(location.statement_index < block.statements.len());
221 block.statements[location.statement_index].make_nop()
225 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
226 type Output = BasicBlockData<'tcx>;
229 fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
230 &self.basic_blocks()[index]
234 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
236 fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
237 &mut self.basic_blocks_mut()[index]
241 /// Grouped information about the source code origin of a MIR entity.
242 /// Intended to be inspected by diagnostics and debuginfo.
243 /// Most passes can work with it as a whole, within a single function.
244 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
245 pub struct SourceInfo {
246 /// Source span for the AST pertaining to this MIR entity.
249 /// The lexical visibility scope, i.e. which bindings can be seen.
250 pub scope: VisibilityScope
253 ///////////////////////////////////////////////////////////////////////////
254 // Mutability and borrow kinds
256 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
257 pub enum Mutability {
262 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
263 pub enum BorrowKind {
264 /// Data must be immutable and is aliasable.
267 /// Data must be immutable but not aliasable. This kind of borrow
268 /// cannot currently be expressed by the user and is used only in
269 /// implicit closure bindings. It is needed when you the closure
270 /// is borrowing or mutating a mutable referent, e.g.:
272 /// let x: &mut isize = ...;
273 /// let y = || *x += 5;
275 /// If we were to try to translate this closure into a more explicit
276 /// form, we'd encounter an error with the code as written:
278 /// struct Env { x: & &mut isize }
279 /// let x: &mut isize = ...;
280 /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn
281 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
283 /// This is then illegal because you cannot mutate a `&mut` found
284 /// in an aliasable location. To solve, you'd have to translate with
285 /// an `&mut` borrow:
287 /// struct Env { x: & &mut isize }
288 /// let x: &mut isize = ...;
289 /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
290 /// fn fn_ptr(env: &mut Env) { **env.x += 5; }
292 /// Now the assignment to `**env.x` is legal, but creating a
293 /// mutable pointer to `x` is not because `x` is not mutable. We
294 /// could fix this by declaring `x` as `let mut x`. This is ok in
295 /// user code, if awkward, but extra weird for closures, since the
296 /// borrow is hidden.
298 /// So we introduce a "unique imm" borrow -- the referent is
299 /// immutable, but not aliasable. This solves the problem. For
300 /// simplicity, we don't give users the way to express this
301 /// borrow, it's just used when translating closures.
304 /// Data is mutable and not aliasable.
308 ///////////////////////////////////////////////////////////////////////////
309 // Variables and temps
311 /// A "variable" is a binding declared by the user as part of the fn
312 /// decl, a let, etc.
313 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
314 pub struct VarDecl<'tcx> {
315 /// `let mut x` vs `let x`
316 pub mutability: Mutability,
318 /// name that user gave the variable; not that, internally,
319 /// mir references variables by index
322 /// type inferred for this variable (`let x: ty = ...`)
325 /// source information (span, scope, etc.) for the declaration
326 pub source_info: SourceInfo,
329 /// A "temp" is a temporary that we place on the stack. They are
330 /// anonymous, always mutable, and have only a type.
331 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
332 pub struct TempDecl<'tcx> {
336 /// A "arg" is one of the function's formal arguments. These are
337 /// anonymous and distinct from the bindings that the user declares.
339 /// For example, in this function:
342 /// fn foo((x, y): (i32, u32)) { ... }
345 /// there is only one argument, of type `(i32, u32)`, but two bindings
347 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
348 pub struct ArgDecl<'tcx> {
351 /// Either keywords::Invalid or the name of a single-binding
352 /// pattern associated with this argument. Useful for debuginfo.
356 /// A closure capture, with its name and mode.
357 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
358 pub struct UpvarDecl {
359 pub debug_name: Name,
361 /// If true, the capture is behind a reference.
365 ///////////////////////////////////////////////////////////////////////////
368 newtype_index!(BasicBlock, "bb");
370 ///////////////////////////////////////////////////////////////////////////
371 // BasicBlockData and Terminator
373 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
374 pub struct BasicBlockData<'tcx> {
375 /// List of statements in this block.
376 pub statements: Vec<Statement<'tcx>>,
378 /// Terminator for this block.
380 /// NB. This should generally ONLY be `None` during construction.
381 /// Therefore, you should generally access it via the
382 /// `terminator()` or `terminator_mut()` methods. The only
383 /// exception is that certain passes, such as `simplify_cfg`, swap
384 /// out the terminator temporarily with `None` while they continue
385 /// to recurse over the set of basic blocks.
386 pub terminator: Option<Terminator<'tcx>>,
388 /// If true, this block lies on an unwind path. This is used
389 /// during trans where distinct kinds of basic blocks may be
390 /// generated (particularly for MSVC cleanup). Unwind blocks must
391 /// only branch to other unwind blocks.
392 pub is_cleanup: bool,
395 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
396 pub struct Terminator<'tcx> {
397 pub source_info: SourceInfo,
398 pub kind: TerminatorKind<'tcx>
401 #[derive(Clone, RustcEncodable, RustcDecodable)]
402 pub enum TerminatorKind<'tcx> {
403 /// block should have one successor in the graph; we jump there
408 /// jump to branch 0 if this lvalue evaluates to true
411 targets: (BasicBlock, BasicBlock),
414 /// lvalue evaluates to some enum; jump depending on the branch
417 adt_def: AdtDef<'tcx>,
418 targets: Vec<BasicBlock>,
421 /// operand evaluates to an integer; jump depending on its value
422 /// to one of the targets, and otherwise fallback to `otherwise`
424 /// discriminant value being tested
427 /// type of value being tested
430 /// Possible values. The locations to branch to in each case
431 /// are found in the corresponding indices from the `targets` vector.
432 values: Vec<ConstVal>,
434 /// Possible branch sites. The length of this vector should be
435 /// equal to the length of the `values` vector plus 1 -- the
436 /// extra item is the block to branch to if none of the values
438 targets: Vec<BasicBlock>,
441 /// Indicates that the landing pad is finished and unwinding should
442 /// continue. Emitted by build::scope::diverge_cleanup.
445 /// Indicates a normal return. The ReturnPointer lvalue should
446 /// have been filled in by now. This should occur at most once.
449 /// Indicates a terminator that can never be reached.
454 location: Lvalue<'tcx>,
456 unwind: Option<BasicBlock>
459 /// Drop the Lvalue and assign the new value over it
461 location: Lvalue<'tcx>,
462 value: Operand<'tcx>,
464 unwind: Option<BasicBlock>,
467 /// Block ends with a call of a converging function
469 /// The function that’s being called
471 /// Arguments the function is called with
472 args: Vec<Operand<'tcx>>,
473 /// Destination for the return value. If some, the call is converging.
474 destination: Option<(Lvalue<'tcx>, BasicBlock)>,
475 /// Cleanups to be done if the call unwinds.
476 cleanup: Option<BasicBlock>
479 /// Jump to the target if the condition has the expected value,
480 /// otherwise panic with a message and a cleanup target.
484 msg: AssertMessage<'tcx>,
486 cleanup: Option<BasicBlock>
490 impl<'tcx> Terminator<'tcx> {
491 pub fn successors(&self) -> Cow<[BasicBlock]> {
492 self.kind.successors()
495 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
496 self.kind.successors_mut()
500 impl<'tcx> TerminatorKind<'tcx> {
501 pub fn successors(&self) -> Cow<[BasicBlock]> {
502 use self::TerminatorKind::*;
504 Goto { target: ref b } => slice::ref_slice(b).into_cow(),
505 If { targets: (b1, b2), .. } => vec![b1, b2].into_cow(),
506 Switch { targets: ref b, .. } => b[..].into_cow(),
507 SwitchInt { targets: ref b, .. } => b[..].into_cow(),
508 Resume => (&[]).into_cow(),
509 Return => (&[]).into_cow(),
510 Unreachable => (&[]).into_cow(),
511 Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
512 Call { destination: Some((_, ref t)), cleanup: None, .. } =>
513 slice::ref_slice(t).into_cow(),
514 Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
515 Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
516 DropAndReplace { target, unwind: Some(unwind), .. } |
517 Drop { target, unwind: Some(unwind), .. } => {
518 vec![target, unwind].into_cow()
520 DropAndReplace { ref target, unwind: None, .. } |
521 Drop { ref target, unwind: None, .. } => {
522 slice::ref_slice(target).into_cow()
524 Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
525 Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
529 // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
530 // `Vec<&mut BasicBlock>` would look like in the first place.
531 pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
532 use self::TerminatorKind::*;
534 Goto { target: ref mut b } => vec![b],
535 If { targets: (ref mut b1, ref mut b2), .. } => vec![b1, b2],
536 Switch { targets: ref mut b, .. } => b.iter_mut().collect(),
537 SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
538 Resume => Vec::new(),
539 Return => Vec::new(),
540 Unreachable => Vec::new(),
541 Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
542 Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
543 Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
544 Call { destination: None, cleanup: None, .. } => vec![],
545 DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
546 Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
547 DropAndReplace { ref mut target, unwind: None, .. } |
548 Drop { ref mut target, unwind: None, .. } => {
551 Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
552 Assert { ref mut target, .. } => vec![target]
557 impl<'tcx> BasicBlockData<'tcx> {
558 pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
561 terminator: terminator,
566 /// Accessor for terminator.
568 /// Terminator may not be None after construction of the basic block is complete. This accessor
569 /// provides a convenience way to reach the terminator.
570 pub fn terminator(&self) -> &Terminator<'tcx> {
571 self.terminator.as_ref().expect("invalid terminator state")
574 pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
575 self.terminator.as_mut().expect("invalid terminator state")
579 impl<'tcx> Debug for TerminatorKind<'tcx> {
580 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
582 let successors = self.successors();
583 let labels = self.fmt_successor_labels();
584 assert_eq!(successors.len(), labels.len());
586 match successors.len() {
589 1 => write!(fmt, " -> {:?}", successors[0]),
592 write!(fmt, " -> [")?;
593 for (i, target) in successors.iter().enumerate() {
597 write!(fmt, "{}: {:?}", labels[i], target)?;
606 impl<'tcx> TerminatorKind<'tcx> {
607 /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
608 /// successor basic block, if any. The only information not inlcuded is the list of possible
609 /// successors, which may be rendered differently between the text and the graphviz format.
610 pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
611 use self::TerminatorKind::*;
613 Goto { .. } => write!(fmt, "goto"),
614 If { cond: ref lv, .. } => write!(fmt, "if({:?})", lv),
615 Switch { discr: ref lv, .. } => write!(fmt, "switch({:?})", lv),
616 SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
617 Return => write!(fmt, "return"),
618 Resume => write!(fmt, "resume"),
619 Unreachable => write!(fmt, "unreachable"),
620 Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
621 DropAndReplace { ref location, ref value, .. } =>
622 write!(fmt, "replace({:?} <- {:?})", location, value),
623 Call { ref func, ref args, ref destination, .. } => {
624 if let Some((ref destination, _)) = *destination {
625 write!(fmt, "{:?} = ", destination)?;
627 write!(fmt, "{:?}(", func)?;
628 for (index, arg) in args.iter().enumerate() {
632 write!(fmt, "{:?}", arg)?;
636 Assert { ref cond, expected, ref msg, .. } => {
637 write!(fmt, "assert(")?;
641 write!(fmt, "{:?}, ", cond)?;
644 AssertMessage::BoundsCheck { ref len, ref index } => {
645 write!(fmt, "{:?}, {:?}, {:?}",
646 "index out of bounds: the len is {} but the index is {}",
649 AssertMessage::Math(ref err) => {
650 write!(fmt, "{:?}", err.description())?;
659 /// Return the list of labels for the edges to the successor basic blocks.
660 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
661 use self::TerminatorKind::*;
663 Return | Resume | Unreachable => vec![],
664 Goto { .. } => vec!["".into()],
665 If { .. } => vec!["true".into(), "false".into()],
666 Switch { ref adt_def, .. } => {
669 .map(|variant| variant.name.to_string().into())
672 SwitchInt { ref values, .. } => {
675 let mut buf = String::new();
676 fmt_const_val(&mut buf, const_val).unwrap();
679 .chain(iter::once(String::from("otherwise").into()))
682 Call { destination: Some(_), cleanup: Some(_), .. } =>
683 vec!["return".into_cow(), "unwind".into_cow()],
684 Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
685 Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
686 Call { destination: None, cleanup: None, .. } => vec![],
687 DropAndReplace { unwind: None, .. } |
688 Drop { unwind: None, .. } => vec!["return".into_cow()],
689 DropAndReplace { unwind: Some(_), .. } |
690 Drop { unwind: Some(_), .. } => {
691 vec!["return".into_cow(), "unwind".into_cow()]
693 Assert { cleanup: None, .. } => vec!["".into()],
695 vec!["success".into_cow(), "unwind".into_cow()]
700 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
701 pub enum AssertMessage<'tcx> {
709 ///////////////////////////////////////////////////////////////////////////
712 #[derive(Clone, RustcEncodable, RustcDecodable)]
713 pub struct Statement<'tcx> {
714 pub source_info: SourceInfo,
715 pub kind: StatementKind<'tcx>,
718 impl<'tcx> Statement<'tcx> {
719 /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
720 /// invalidating statement indices in `Location`s.
721 pub fn make_nop(&mut self) {
722 self.kind = StatementKind::Nop
726 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
727 pub enum StatementKind<'tcx> {
728 /// Write the RHS Rvalue to the LHS Lvalue.
729 Assign(Lvalue<'tcx>, Rvalue<'tcx>),
731 /// Write the discriminant for a variant to the enum Lvalue.
732 SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
734 /// Start a live range for the storage of the local.
735 StorageLive(Lvalue<'tcx>),
737 /// End the current live range for the storage of the local.
738 StorageDead(Lvalue<'tcx>),
740 /// No-op. Useful for deleting instructions without affecting statement indices.
744 impl<'tcx> Debug for Statement<'tcx> {
745 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
746 use self::StatementKind::*;
748 Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
749 StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
750 StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
751 SetDiscriminant{lvalue: ref lv, variant_index: index} => {
752 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
754 Nop => write!(fmt, "nop"),
759 ///////////////////////////////////////////////////////////////////////////
762 newtype_index!(Var, "var");
763 newtype_index!(Temp, "tmp");
764 newtype_index!(Arg, "arg");
765 newtype_index!(Local, "local");
767 /// A path to a value; something that can be evaluated without
768 /// changing or disturbing program state.
769 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
770 pub enum Lvalue<'tcx> {
771 /// local variable declared by the user
774 /// temporary introduced during lowering into MIR
777 /// formal parameter of the function; note that these are NOT the
778 /// bindings that the user declares, which are vars
781 /// static or static mut variable
784 /// the return pointer of the fn
787 /// projection out of an lvalue (access a field, deref a pointer, etc)
788 Projection(Box<LvalueProjection<'tcx>>),
791 /// The `Projection` data structure defines things of the form `B.x`
792 /// or `*B` or `B[index]`. Note that it is parameterized because it is
793 /// shared between `Constant` and `Lvalue`. See the aliases
794 /// `LvalueProjection` etc below.
795 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
796 pub struct Projection<'tcx, B, V> {
798 pub elem: ProjectionElem<'tcx, V>,
801 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
802 pub enum ProjectionElem<'tcx, V> {
804 Field(Field, Ty<'tcx>),
807 /// These indices are generated by slice patterns. Easiest to explain
811 /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
812 /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
813 /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
814 /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
817 /// index or -index (in Python terms), depending on from_end
819 /// thing being indexed must be at least this long
821 /// counting backwards from end?
825 /// These indices are generated by slice patterns.
827 /// slice[from:-to] in Python terms.
833 /// "Downcast" to a variant of an ADT. Currently, we only introduce
834 /// this for ADTs with more than one variant. It may be better to
835 /// just introduce it always, or always for enums.
836 Downcast(AdtDef<'tcx>, usize),
839 /// Alias for projections as they appear in lvalues, where the base is an lvalue
840 /// and the index is an operand.
841 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
843 /// Alias for projections as they appear in lvalues, where the base is an lvalue
844 /// and the index is an operand.
845 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
847 newtype_index!(Field, "field");
849 impl<'tcx> Lvalue<'tcx> {
850 pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
851 self.elem(ProjectionElem::Field(f, ty))
854 pub fn deref(self) -> Lvalue<'tcx> {
855 self.elem(ProjectionElem::Deref)
858 pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
859 self.elem(ProjectionElem::Index(index))
862 pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
863 Lvalue::Projection(Box::new(LvalueProjection {
869 pub fn from_local(mir: &Mir<'tcx>, local: Local) -> Lvalue<'tcx> {
870 let mut index = local.index();
871 index = match index.checked_sub(mir.arg_decls.len()) {
872 None => return Lvalue::Arg(Arg(index as u32)),
873 Some(index) => index,
875 index = match index.checked_sub(mir.var_decls.len()) {
876 None => return Lvalue::Var(Var(index as u32)),
877 Some(index) => index,
879 index = match index.checked_sub(mir.temp_decls.len()) {
880 None => return Lvalue::Temp(Temp(index as u32)),
881 Some(index) => index,
883 debug_assert!(index == 0);
884 Lvalue::ReturnPointer
888 impl<'tcx> Debug for Lvalue<'tcx> {
889 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
893 Var(id) => write!(fmt, "{:?}", id),
894 Arg(id) => write!(fmt, "{:?}", id),
895 Temp(id) => write!(fmt, "{:?}", id),
897 write!(fmt, "{}", ty::tls::with(|tcx| tcx.item_path_str(def_id))),
899 write!(fmt, "return"),
900 Projection(ref data) =>
902 ProjectionElem::Downcast(ref adt_def, index) =>
903 write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
904 ProjectionElem::Deref =>
905 write!(fmt, "(*{:?})", data.base),
906 ProjectionElem::Field(field, ty) =>
907 write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
908 ProjectionElem::Index(ref index) =>
909 write!(fmt, "{:?}[{:?}]", data.base, index),
910 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
911 write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
912 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
913 write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
914 ProjectionElem::Subslice { from, to } if to == 0 =>
915 write!(fmt, "{:?}[{:?}:", data.base, from),
916 ProjectionElem::Subslice { from, to } if from == 0 =>
917 write!(fmt, "{:?}[:-{:?}]", data.base, to),
918 ProjectionElem::Subslice { from, to } =>
919 write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
927 ///////////////////////////////////////////////////////////////////////////
930 newtype_index!(VisibilityScope, "scope");
931 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
933 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
934 pub struct VisibilityScopeData {
936 pub parent_scope: Option<VisibilityScope>,
939 ///////////////////////////////////////////////////////////////////////////
942 /// These are values that can appear inside an rvalue (or an index
943 /// lvalue). They are intentionally limited to prevent rvalues from
944 /// being nested in one another.
945 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
946 pub enum Operand<'tcx> {
947 Consume(Lvalue<'tcx>),
948 Constant(Constant<'tcx>),
951 impl<'tcx> Debug for Operand<'tcx> {
952 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
953 use self::Operand::*;
955 Constant(ref a) => write!(fmt, "{:?}", a),
956 Consume(ref lv) => write!(fmt, "{:?}", lv),
961 ///////////////////////////////////////////////////////////////////////////
964 #[derive(Clone, RustcEncodable, RustcDecodable)]
965 pub enum Rvalue<'tcx> {
966 /// x (either a move or copy, depending on type of x)
970 Repeat(Operand<'tcx>, TypedConstVal<'tcx>),
973 Ref(&'tcx Region, BorrowKind, Lvalue<'tcx>),
975 /// length of a [X] or [X;n] value
978 Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
980 BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
981 CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
983 UnaryOp(UnOp, Operand<'tcx>),
985 /// Creates an *uninitialized* Box
988 /// Create an aggregate value, like a tuple or struct. This is
989 /// only needed because we want to distinguish `dest = Foo { x:
990 /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
991 /// that `Foo` has a destructor. These rvalues can be optimized
992 /// away after type-checking and before lowering.
993 Aggregate(AggregateKind<'tcx>, Vec<Operand<'tcx>>),
997 outputs: Vec<Lvalue<'tcx>>,
998 inputs: Vec<Operand<'tcx>>
1002 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1006 /// Convert unique, zero-sized type for a fn to fn()
1009 /// Convert safe fn() to unsafe fn()
1012 /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1013 /// trans must figure out the details once full monomorphization
1014 /// is known. For example, this could be used to cast from a
1015 /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1016 /// (presuming `T: Trait`).
1020 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1021 pub enum AggregateKind<'tcx> {
1024 /// The second field is variant number (discriminant), it's equal to 0
1025 /// for struct and union expressions. The fourth field is active field
1026 /// number and is present only for union expressions.
1027 Adt(AdtDef<'tcx>, usize, &'tcx Substs<'tcx>, Option<usize>),
1028 Closure(DefId, ClosureSubsts<'tcx>),
1031 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1033 /// The `+` operator (addition)
1035 /// The `-` operator (subtraction)
1037 /// The `*` operator (multiplication)
1039 /// The `/` operator (division)
1041 /// The `%` operator (modulus)
1043 /// The `^` operator (bitwise xor)
1045 /// The `&` operator (bitwise and)
1047 /// The `|` operator (bitwise or)
1049 /// The `<<` operator (shift left)
1051 /// The `>>` operator (shift right)
1053 /// The `==` operator (equality)
1055 /// The `<` operator (less than)
1057 /// The `<=` operator (less than or equal to)
1059 /// The `!=` operator (not equal to)
1061 /// The `>=` operator (greater than or equal to)
1063 /// The `>` operator (greater than)
1068 pub fn is_checkable(self) -> bool {
1071 Add | Sub | Mul | Shl | Shr => true,
1077 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1079 /// The `!` operator for logical inversion
1081 /// The `-` operator for negation
1085 impl<'tcx> Debug for Rvalue<'tcx> {
1086 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1087 use self::Rvalue::*;
1090 Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1091 Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1092 Len(ref a) => write!(fmt, "Len({:?})", a),
1093 Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1094 BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1095 CheckedBinaryOp(ref op, ref a, ref b) => {
1096 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1098 UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1099 Box(ref t) => write!(fmt, "Box({:?})", t),
1100 InlineAsm { ref asm, ref outputs, ref inputs } => {
1101 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
1104 Ref(_, borrow_kind, ref lv) => {
1105 let kind_str = match borrow_kind {
1106 BorrowKind::Shared => "",
1107 BorrowKind::Mut | BorrowKind::Unique => "mut ",
1109 write!(fmt, "&{}{:?}", kind_str, lv)
1112 Aggregate(ref kind, ref lvs) => {
1113 use self::AggregateKind::*;
1115 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1116 let mut tuple_fmt = fmt.debug_tuple("");
1118 tuple_fmt.field(lv);
1124 Vec => write!(fmt, "{:?}", lvs),
1128 0 => write!(fmt, "()"),
1129 1 => write!(fmt, "({:?},)", lvs[0]),
1130 _ => fmt_tuple(fmt, lvs),
1134 Adt(adt_def, variant, substs, _) => {
1135 let variant_def = &adt_def.variants[variant];
1137 ppaux::parameterized(fmt, substs, variant_def.did,
1138 ppaux::Ns::Value, &[])?;
1140 match variant_def.kind {
1141 ty::VariantKind::Unit => Ok(()),
1142 ty::VariantKind::Tuple => fmt_tuple(fmt, lvs),
1143 ty::VariantKind::Struct => {
1144 let mut struct_fmt = fmt.debug_struct("");
1145 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1146 struct_fmt.field(&field.name.as_str(), lv);
1153 Closure(def_id, _) => ty::tls::with(|tcx| {
1154 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
1155 let name = format!("[closure@{:?}]", tcx.map.span(node_id));
1156 let mut struct_fmt = fmt.debug_struct(&name);
1158 tcx.with_freevars(node_id, |freevars| {
1159 for (freevar, lv) in freevars.iter().zip(lvs) {
1160 let def_id = freevar.def.def_id();
1161 let var_id = tcx.map.as_local_node_id(def_id).unwrap();
1162 let var_name = tcx.local_var_name_str(var_id);
1163 struct_fmt.field(&var_name, lv);
1169 write!(fmt, "[closure]")
1178 ///////////////////////////////////////////////////////////////////////////
1181 /// Two constants are equal if they are the same constant. Note that
1182 /// this does not necessarily mean that they are "==" in Rust -- in
1183 /// particular one must be wary of `NaN`!
1185 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1186 pub struct Constant<'tcx> {
1189 pub literal: Literal<'tcx>,
1192 #[derive(Clone, RustcEncodable, RustcDecodable)]
1193 pub struct TypedConstVal<'tcx> {
1196 pub value: ConstUsize,
1199 impl<'tcx> Debug for TypedConstVal<'tcx> {
1200 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1201 write!(fmt, "const {}", ConstInt::Usize(self.value))
1205 newtype_index!(Promoted, "promoted");
1207 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1208 pub enum Literal<'tcx> {
1211 substs: &'tcx Substs<'tcx>,
1217 // Index into the `promoted` vector of `Mir`.
1222 impl<'tcx> Debug for Constant<'tcx> {
1223 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1224 write!(fmt, "{:?}", self.literal)
1228 impl<'tcx> Debug for Literal<'tcx> {
1229 fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1230 use self::Literal::*;
1232 Item { def_id, substs } => {
1233 ppaux::parameterized(fmt, substs, def_id, ppaux::Ns::Value, &[])
1235 Value { ref value } => {
1236 write!(fmt, "const ")?;
1237 fmt_const_val(fmt, value)
1239 Promoted { index } => {
1240 write!(fmt, "{:?}", index)
1246 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1247 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1248 use middle::const_val::ConstVal::*;
1250 Float(f) => write!(fmt, "{:?}", f),
1251 Integral(n) => write!(fmt, "{}", n),
1252 Str(ref s) => write!(fmt, "{:?}", s),
1253 ByteStr(ref bytes) => {
1254 let escaped: String = bytes
1256 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1258 write!(fmt, "b\"{}\"", escaped)
1260 Bool(b) => write!(fmt, "{:?}", b),
1261 Function(def_id) => write!(fmt, "{}", item_path_str(def_id)),
1262 Struct(node_id) | Tuple(node_id) | Array(node_id, _) | Repeat(node_id, _) =>
1263 write!(fmt, "{}", node_to_string(node_id)),
1264 Char(c) => write!(fmt, "{:?}", c),
1269 fn node_to_string(node_id: ast::NodeId) -> String {
1270 ty::tls::with(|tcx| tcx.map.node_to_user_string(node_id))
1273 fn item_path_str(def_id: DefId) -> String {
1274 ty::tls::with(|tcx| tcx.item_path_str(def_id))
1277 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1279 type Node = BasicBlock;
1281 fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1283 fn start_node(&self) -> Self::Node { START_BLOCK }
1285 fn predecessors<'graph>(&'graph self, node: Self::Node)
1286 -> <Self as GraphPredecessors<'graph>>::Iter
1288 self.predecessors_for(node).clone().into_iter()
1290 fn successors<'graph>(&'graph self, node: Self::Node)
1291 -> <Self as GraphSuccessors<'graph>>::Iter
1293 self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1297 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1298 type Item = BasicBlock;
1299 type Iter = IntoIter<BasicBlock>;
1302 impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
1303 type Item = BasicBlock;
1304 type Iter = IntoIter<BasicBlock>;
1307 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1308 pub struct Location {
1309 /// the location is within this block
1310 pub block: BasicBlock,
1312 /// the location is the start of the this statement; or, if `statement_index`
1313 /// == num-statements, then the start of the terminator.
1314 pub statement_index: usize,
1317 impl fmt::Debug for Location {
1318 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1319 write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1324 pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1325 if self.block == other.block {
1326 self.statement_index <= other.statement_index
1328 dominators.is_dominated_by(other.block, self.block)