]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mod.rs
Rollup merge of #41910 - mersinvald:master, r=Mark-Simulacrum
[rust.git] / src / librustc / mir / mod.rs
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.
4 //
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.
10
11 //! MIR datatypes and passes. See [the README](README.md) for details.
12
13 use graphviz::IntoCow;
14 use middle::const_val::ConstVal;
15 use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr};
16 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
17 use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
18 use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
19 use rustc_data_structures::control_flow_graph::ControlFlowGraph;
20 use hir::def::CtorKind;
21 use hir::def_id::DefId;
22 use ty::subst::{Subst, Substs};
23 use ty::{self, AdtDef, ClosureSubsts, Region, Ty};
24 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
25 use util::ppaux;
26 use rustc_back::slice;
27 use hir::InlineAsm;
28 use std::ascii;
29 use std::borrow::{Cow};
30 use std::cell::Ref;
31 use std::fmt::{self, Debug, Formatter, Write};
32 use std::{iter, u32};
33 use std::ops::{Index, IndexMut};
34 use std::vec::IntoIter;
35 use syntax::ast::Name;
36 use syntax_pos::Span;
37
38 mod cache;
39 pub mod tcx;
40 pub mod visit;
41 pub mod transform;
42 pub mod traversal;
43
44 macro_rules! newtype_index {
45     ($name:ident, $debug_name:expr) => (
46         #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord,
47          RustcEncodable, RustcDecodable)]
48         pub struct $name(u32);
49
50         impl Idx for $name {
51             fn new(value: usize) -> Self {
52                 assert!(value < (u32::MAX) as usize);
53                 $name(value as u32)
54             }
55             fn index(self) -> usize {
56                 self.0 as usize
57             }
58         }
59
60         impl Debug for $name {
61             fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
62                 write!(fmt, "{}{}", $debug_name, self.0)
63             }
64         }
65     )
66 }
67
68 /// Lowered representation of a single function.
69 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
70 pub struct Mir<'tcx> {
71     /// List of basic blocks. References to basic block use a newtyped index type `BasicBlock`
72     /// that indexes into this vector.
73     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
74
75     /// List of visibility (lexical) scopes; these are referenced by statements
76     /// and used (eventually) for debuginfo. Indexed by a `VisibilityScope`.
77     pub visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
78
79     /// Rvalues promoted from this function, such as borrows of constants.
80     /// Each of them is the Mir of a constant with the fn's type parameters
81     /// in scope, but a separate set of locals.
82     pub promoted: IndexVec<Promoted, Mir<'tcx>>,
83
84     /// Return type of the function.
85     pub return_ty: Ty<'tcx>,
86
87     /// Declarations of locals.
88     ///
89     /// The first local is the return value pointer, followed by `arg_count`
90     /// locals for the function arguments, followed by any user-declared
91     /// variables and temporaries.
92     pub local_decls: IndexVec<Local, LocalDecl<'tcx>>,
93
94     /// Number of arguments this function takes.
95     ///
96     /// Starting at local 1, `arg_count` locals will be provided by the caller
97     /// and can be assumed to be initialized.
98     ///
99     /// If this MIR was built for a constant, this will be 0.
100     pub arg_count: usize,
101
102     /// Names and capture modes of all the closure upvars, assuming
103     /// the first argument is either the closure or a reference to it.
104     pub upvar_decls: Vec<UpvarDecl>,
105
106     /// Mark an argument local (which must be a tuple) as getting passed as
107     /// its individual components at the LLVM level.
108     ///
109     /// This is used for the "rust-call" ABI.
110     pub spread_arg: Option<Local>,
111
112     /// A span representing this MIR, for error reporting
113     pub span: Span,
114
115     /// A cache for various calculations
116     cache: cache::Cache
117 }
118
119 /// where execution begins
120 pub const START_BLOCK: BasicBlock = BasicBlock(0);
121
122 impl<'tcx> Mir<'tcx> {
123     pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
124                visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
125                promoted: IndexVec<Promoted, Mir<'tcx>>,
126                return_ty: Ty<'tcx>,
127                local_decls: IndexVec<Local, LocalDecl<'tcx>>,
128                arg_count: usize,
129                upvar_decls: Vec<UpvarDecl>,
130                span: Span) -> Self
131     {
132         // We need `arg_count` locals, and one for the return pointer
133         assert!(local_decls.len() >= arg_count + 1,
134             "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
135         assert_eq!(local_decls[RETURN_POINTER].ty, return_ty);
136
137         Mir {
138             basic_blocks: basic_blocks,
139             visibility_scopes: visibility_scopes,
140             promoted: promoted,
141             return_ty: return_ty,
142             local_decls: local_decls,
143             arg_count: arg_count,
144             upvar_decls: upvar_decls,
145             spread_arg: None,
146             span: span,
147             cache: cache::Cache::new()
148         }
149     }
150
151     #[inline]
152     pub fn basic_blocks(&self) -> &IndexVec<BasicBlock, BasicBlockData<'tcx>> {
153         &self.basic_blocks
154     }
155
156     #[inline]
157     pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'tcx>> {
158         self.cache.invalidate();
159         &mut self.basic_blocks
160     }
161
162     #[inline]
163     pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
164         self.cache.predecessors(self)
165     }
166
167     #[inline]
168     pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
169         Ref::map(self.predecessors(), |p| &p[bb])
170     }
171
172     #[inline]
173     pub fn dominators(&self) -> Dominators<BasicBlock> {
174         dominators(self)
175     }
176
177     #[inline]
178     pub fn local_kind(&self, local: Local) -> LocalKind {
179         let index = local.0 as usize;
180         if index == 0 {
181             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
182                           "return pointer should be mutable");
183
184             LocalKind::ReturnPointer
185         } else if index < self.arg_count + 1 {
186             LocalKind::Arg
187         } else if self.local_decls[local].name.is_some() {
188             LocalKind::Var
189         } else {
190             debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
191                           "temp should be mutable");
192
193             LocalKind::Temp
194         }
195     }
196
197     /// Returns an iterator over all temporaries.
198     #[inline]
199     pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
200         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
201             let local = Local::new(index);
202             if self.local_decls[local].is_user_variable {
203                 None
204             } else {
205                 Some(local)
206             }
207         })
208     }
209
210     /// Returns an iterator over all user-declared locals.
211     #[inline]
212     pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
213         (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
214             let local = Local::new(index);
215             if self.local_decls[local].is_user_variable {
216                 Some(local)
217             } else {
218                 None
219             }
220         })
221     }
222
223     /// Returns an iterator over all function arguments.
224     #[inline]
225     pub fn args_iter(&self) -> impl Iterator<Item=Local> {
226         let arg_count = self.arg_count;
227         (1..arg_count+1).map(Local::new)
228     }
229
230     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
231     /// locals that are neither arguments nor the return pointer).
232     #[inline]
233     pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
234         let arg_count = self.arg_count;
235         let local_count = self.local_decls.len();
236         (arg_count+1..local_count).map(Local::new)
237     }
238
239     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
240     /// invalidating statement indices in `Location`s.
241     pub fn make_statement_nop(&mut self, location: Location) {
242         let block = &mut self[location.block];
243         debug_assert!(location.statement_index < block.statements.len());
244         block.statements[location.statement_index].make_nop()
245     }
246 }
247
248 impl_stable_hash_for!(struct Mir<'tcx> {
249     basic_blocks,
250     visibility_scopes,
251     promoted,
252     return_ty,
253     local_decls,
254     arg_count,
255     upvar_decls,
256     spread_arg,
257     span,
258     cache
259 });
260
261 impl<'tcx> Index<BasicBlock> for Mir<'tcx> {
262     type Output = BasicBlockData<'tcx>;
263
264     #[inline]
265     fn index(&self, index: BasicBlock) -> &BasicBlockData<'tcx> {
266         &self.basic_blocks()[index]
267     }
268 }
269
270 impl<'tcx> IndexMut<BasicBlock> for Mir<'tcx> {
271     #[inline]
272     fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
273         &mut self.basic_blocks_mut()[index]
274     }
275 }
276
277 /// Grouped information about the source code origin of a MIR entity.
278 /// Intended to be inspected by diagnostics and debuginfo.
279 /// Most passes can work with it as a whole, within a single function.
280 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
281 pub struct SourceInfo {
282     /// Source span for the AST pertaining to this MIR entity.
283     pub span: Span,
284
285     /// The lexical visibility scope, i.e. which bindings can be seen.
286     pub scope: VisibilityScope
287 }
288
289 ///////////////////////////////////////////////////////////////////////////
290 // Mutability and borrow kinds
291
292 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
293 pub enum Mutability {
294     Mut,
295     Not,
296 }
297
298 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
299 pub enum BorrowKind {
300     /// Data must be immutable and is aliasable.
301     Shared,
302
303     /// Data must be immutable but not aliasable.  This kind of borrow
304     /// cannot currently be expressed by the user and is used only in
305     /// implicit closure bindings. It is needed when you the closure
306     /// is borrowing or mutating a mutable referent, e.g.:
307     ///
308     ///    let x: &mut isize = ...;
309     ///    let y = || *x += 5;
310     ///
311     /// If we were to try to translate this closure into a more explicit
312     /// form, we'd encounter an error with the code as written:
313     ///
314     ///    struct Env { x: & &mut isize }
315     ///    let x: &mut isize = ...;
316     ///    let y = (&mut Env { &x }, fn_ptr);  // Closure is pair of env and fn
317     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
318     ///
319     /// This is then illegal because you cannot mutate a `&mut` found
320     /// in an aliasable location. To solve, you'd have to translate with
321     /// an `&mut` borrow:
322     ///
323     ///    struct Env { x: & &mut isize }
324     ///    let x: &mut isize = ...;
325     ///    let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x
326     ///    fn fn_ptr(env: &mut Env) { **env.x += 5; }
327     ///
328     /// Now the assignment to `**env.x` is legal, but creating a
329     /// mutable pointer to `x` is not because `x` is not mutable. We
330     /// could fix this by declaring `x` as `let mut x`. This is ok in
331     /// user code, if awkward, but extra weird for closures, since the
332     /// borrow is hidden.
333     ///
334     /// So we introduce a "unique imm" borrow -- the referent is
335     /// immutable, but not aliasable. This solves the problem. For
336     /// simplicity, we don't give users the way to express this
337     /// borrow, it's just used when translating closures.
338     Unique,
339
340     /// Data is mutable and not aliasable.
341     Mut,
342 }
343
344 ///////////////////////////////////////////////////////////////////////////
345 // Variables and temps
346
347 newtype_index!(Local, "_");
348
349 pub const RETURN_POINTER: Local = Local(0);
350
351 /// Classifies locals into categories. See `Mir::local_kind`.
352 #[derive(PartialEq, Eq, Debug)]
353 pub enum LocalKind {
354     /// User-declared variable binding
355     Var,
356     /// Compiler-introduced temporary
357     Temp,
358     /// Function argument
359     Arg,
360     /// Location of function's return value
361     ReturnPointer,
362 }
363
364 /// A MIR local.
365 ///
366 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
367 /// argument, or the return pointer.
368 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
369 pub struct LocalDecl<'tcx> {
370     /// `let mut x` vs `let x`.
371     ///
372     /// Temporaries and the return pointer are always mutable.
373     pub mutability: Mutability,
374
375     /// True if this corresponds to a user-declared local variable.
376     pub is_user_variable: bool,
377
378     /// Type of this local.
379     pub ty: Ty<'tcx>,
380
381     /// Name of the local, used in debuginfo and pretty-printing.
382     ///
383     /// Note that function arguments can also have this set to `Some(_)`
384     /// to generate better debuginfo.
385     pub name: Option<Name>,
386
387     /// Source info of the local.
388     pub source_info: SourceInfo,
389 }
390
391 impl<'tcx> LocalDecl<'tcx> {
392     /// Create a new `LocalDecl` for a temporary.
393     #[inline]
394     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
395         LocalDecl {
396             mutability: Mutability::Mut,
397             ty: ty,
398             name: None,
399             source_info: SourceInfo {
400                 span: span,
401                 scope: ARGUMENT_VISIBILITY_SCOPE
402             },
403             is_user_variable: false
404         }
405     }
406
407     /// Builds a `LocalDecl` for the return pointer.
408     ///
409     /// This must be inserted into the `local_decls` list as the first local.
410     #[inline]
411     pub fn new_return_pointer(return_ty: Ty, span: Span) -> LocalDecl {
412         LocalDecl {
413             mutability: Mutability::Mut,
414             ty: return_ty,
415             source_info: SourceInfo {
416                 span: span,
417                 scope: ARGUMENT_VISIBILITY_SCOPE
418             },
419             name: None,     // FIXME maybe we do want some name here?
420             is_user_variable: false
421         }
422     }
423 }
424
425 /// A closure capture, with its name and mode.
426 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
427 pub struct UpvarDecl {
428     pub debug_name: Name,
429
430     /// If true, the capture is behind a reference.
431     pub by_ref: bool
432 }
433
434 ///////////////////////////////////////////////////////////////////////////
435 // BasicBlock
436
437 newtype_index!(BasicBlock, "bb");
438
439 ///////////////////////////////////////////////////////////////////////////
440 // BasicBlockData and Terminator
441
442 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
443 pub struct BasicBlockData<'tcx> {
444     /// List of statements in this block.
445     pub statements: Vec<Statement<'tcx>>,
446
447     /// Terminator for this block.
448     ///
449     /// NB. This should generally ONLY be `None` during construction.
450     /// Therefore, you should generally access it via the
451     /// `terminator()` or `terminator_mut()` methods. The only
452     /// exception is that certain passes, such as `simplify_cfg`, swap
453     /// out the terminator temporarily with `None` while they continue
454     /// to recurse over the set of basic blocks.
455     pub terminator: Option<Terminator<'tcx>>,
456
457     /// If true, this block lies on an unwind path. This is used
458     /// during trans where distinct kinds of basic blocks may be
459     /// generated (particularly for MSVC cleanup). Unwind blocks must
460     /// only branch to other unwind blocks.
461     pub is_cleanup: bool,
462 }
463
464 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
465 pub struct Terminator<'tcx> {
466     pub source_info: SourceInfo,
467     pub kind: TerminatorKind<'tcx>
468 }
469
470 #[derive(Clone, RustcEncodable, RustcDecodable)]
471 pub enum TerminatorKind<'tcx> {
472     /// block should have one successor in the graph; we jump there
473     Goto {
474         target: BasicBlock,
475     },
476
477     /// operand evaluates to an integer; jump depending on its value
478     /// to one of the targets, and otherwise fallback to `otherwise`
479     SwitchInt {
480         /// discriminant value being tested
481         discr: Operand<'tcx>,
482
483         /// type of value being tested
484         switch_ty: Ty<'tcx>,
485
486         /// Possible values. The locations to branch to in each case
487         /// are found in the corresponding indices from the `targets` vector.
488         values: Cow<'tcx, [ConstInt]>,
489
490         /// Possible branch sites. The last element of this vector is used
491         /// for the otherwise branch, so targets.len() == values.len() + 1
492         /// should hold.
493         // This invariant is quite non-obvious and also could be improved.
494         // One way to make this invariant is to have something like this instead:
495         //
496         // branches: Vec<(ConstInt, BasicBlock)>,
497         // otherwise: Option<BasicBlock> // exhaustive if None
498         //
499         // However we’ve decided to keep this as-is until we figure a case
500         // where some other approach seems to be strictly better than other.
501         targets: Vec<BasicBlock>,
502     },
503
504     /// Indicates that the landing pad is finished and unwinding should
505     /// continue. Emitted by build::scope::diverge_cleanup.
506     Resume,
507
508     /// Indicates a normal return. The return pointer lvalue should
509     /// have been filled in by now. This should occur at most once.
510     Return,
511
512     /// Indicates a terminator that can never be reached.
513     Unreachable,
514
515     /// Drop the Lvalue
516     Drop {
517         location: Lvalue<'tcx>,
518         target: BasicBlock,
519         unwind: Option<BasicBlock>
520     },
521
522     /// Drop the Lvalue and assign the new value over it
523     DropAndReplace {
524         location: Lvalue<'tcx>,
525         value: Operand<'tcx>,
526         target: BasicBlock,
527         unwind: Option<BasicBlock>,
528     },
529
530     /// Block ends with a call of a converging function
531     Call {
532         /// The function that’s being called
533         func: Operand<'tcx>,
534         /// Arguments the function is called with
535         args: Vec<Operand<'tcx>>,
536         /// Destination for the return value. If some, the call is converging.
537         destination: Option<(Lvalue<'tcx>, BasicBlock)>,
538         /// Cleanups to be done if the call unwinds.
539         cleanup: Option<BasicBlock>
540     },
541
542     /// Jump to the target if the condition has the expected value,
543     /// otherwise panic with a message and a cleanup target.
544     Assert {
545         cond: Operand<'tcx>,
546         expected: bool,
547         msg: AssertMessage<'tcx>,
548         target: BasicBlock,
549         cleanup: Option<BasicBlock>
550     }
551 }
552
553 impl<'tcx> Terminator<'tcx> {
554     pub fn successors(&self) -> Cow<[BasicBlock]> {
555         self.kind.successors()
556     }
557
558     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
559         self.kind.successors_mut()
560     }
561 }
562
563 impl<'tcx> TerminatorKind<'tcx> {
564     pub fn if_<'a, 'gcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
565                          t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
566         static BOOL_SWITCH_FALSE: &'static [ConstInt] = &[ConstInt::U8(0)];
567         TerminatorKind::SwitchInt {
568             discr: cond,
569             switch_ty: tcx.types.bool,
570             values: From::from(BOOL_SWITCH_FALSE),
571             targets: vec![f, t],
572         }
573     }
574
575     pub fn successors(&self) -> Cow<[BasicBlock]> {
576         use self::TerminatorKind::*;
577         match *self {
578             Goto { target: ref b } => slice::ref_slice(b).into_cow(),
579             SwitchInt { targets: ref b, .. } => b[..].into_cow(),
580             Resume => (&[]).into_cow(),
581             Return => (&[]).into_cow(),
582             Unreachable => (&[]).into_cow(),
583             Call { destination: Some((_, t)), cleanup: Some(c), .. } => vec![t, c].into_cow(),
584             Call { destination: Some((_, ref t)), cleanup: None, .. } =>
585                 slice::ref_slice(t).into_cow(),
586             Call { destination: None, cleanup: Some(ref c), .. } => slice::ref_slice(c).into_cow(),
587             Call { destination: None, cleanup: None, .. } => (&[]).into_cow(),
588             DropAndReplace { target, unwind: Some(unwind), .. } |
589             Drop { target, unwind: Some(unwind), .. } => {
590                 vec![target, unwind].into_cow()
591             }
592             DropAndReplace { ref target, unwind: None, .. } |
593             Drop { ref target, unwind: None, .. } => {
594                 slice::ref_slice(target).into_cow()
595             }
596             Assert { target, cleanup: Some(unwind), .. } => vec![target, unwind].into_cow(),
597             Assert { ref target, .. } => slice::ref_slice(target).into_cow(),
598         }
599     }
600
601     // FIXME: no mootable cow. I’m honestly not sure what a “cow” between `&mut [BasicBlock]` and
602     // `Vec<&mut BasicBlock>` would look like in the first place.
603     pub fn successors_mut(&mut self) -> Vec<&mut BasicBlock> {
604         use self::TerminatorKind::*;
605         match *self {
606             Goto { target: ref mut b } => vec![b],
607             SwitchInt { targets: ref mut b, .. } => b.iter_mut().collect(),
608             Resume => Vec::new(),
609             Return => Vec::new(),
610             Unreachable => Vec::new(),
611             Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut c), .. } => vec![t, c],
612             Call { destination: Some((_, ref mut t)), cleanup: None, .. } => vec![t],
613             Call { destination: None, cleanup: Some(ref mut c), .. } => vec![c],
614             Call { destination: None, cleanup: None, .. } => vec![],
615             DropAndReplace { ref mut target, unwind: Some(ref mut unwind), .. } |
616             Drop { ref mut target, unwind: Some(ref mut unwind), .. } => vec![target, unwind],
617             DropAndReplace { ref mut target, unwind: None, .. } |
618             Drop { ref mut target, unwind: None, .. } => {
619                 vec![target]
620             }
621             Assert { ref mut target, cleanup: Some(ref mut unwind), .. } => vec![target, unwind],
622             Assert { ref mut target, .. } => vec![target]
623         }
624     }
625 }
626
627 impl<'tcx> BasicBlockData<'tcx> {
628     pub fn new(terminator: Option<Terminator<'tcx>>) -> BasicBlockData<'tcx> {
629         BasicBlockData {
630             statements: vec![],
631             terminator: terminator,
632             is_cleanup: false,
633         }
634     }
635
636     /// Accessor for terminator.
637     ///
638     /// Terminator may not be None after construction of the basic block is complete. This accessor
639     /// provides a convenience way to reach the terminator.
640     pub fn terminator(&self) -> &Terminator<'tcx> {
641         self.terminator.as_ref().expect("invalid terminator state")
642     }
643
644     pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
645         self.terminator.as_mut().expect("invalid terminator state")
646     }
647 }
648
649 impl<'tcx> Debug for TerminatorKind<'tcx> {
650     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
651         self.fmt_head(fmt)?;
652         let successors = self.successors();
653         let labels = self.fmt_successor_labels();
654         assert_eq!(successors.len(), labels.len());
655
656         match successors.len() {
657             0 => Ok(()),
658
659             1 => write!(fmt, " -> {:?}", successors[0]),
660
661             _ => {
662                 write!(fmt, " -> [")?;
663                 for (i, target) in successors.iter().enumerate() {
664                     if i > 0 {
665                         write!(fmt, ", ")?;
666                     }
667                     write!(fmt, "{}: {:?}", labels[i], target)?;
668                 }
669                 write!(fmt, "]")
670             }
671
672         }
673     }
674 }
675
676 impl<'tcx> TerminatorKind<'tcx> {
677     /// Write the "head" part of the terminator; that is, its name and the data it uses to pick the
678     /// successor basic block, if any. The only information not inlcuded is the list of possible
679     /// successors, which may be rendered differently between the text and the graphviz format.
680     pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
681         use self::TerminatorKind::*;
682         match *self {
683             Goto { .. } => write!(fmt, "goto"),
684             SwitchInt { discr: ref lv, .. } => write!(fmt, "switchInt({:?})", lv),
685             Return => write!(fmt, "return"),
686             Resume => write!(fmt, "resume"),
687             Unreachable => write!(fmt, "unreachable"),
688             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
689             DropAndReplace { ref location, ref value, .. } =>
690                 write!(fmt, "replace({:?} <- {:?})", location, value),
691             Call { ref func, ref args, ref destination, .. } => {
692                 if let Some((ref destination, _)) = *destination {
693                     write!(fmt, "{:?} = ", destination)?;
694                 }
695                 write!(fmt, "{:?}(", func)?;
696                 for (index, arg) in args.iter().enumerate() {
697                     if index > 0 {
698                         write!(fmt, ", ")?;
699                     }
700                     write!(fmt, "{:?}", arg)?;
701                 }
702                 write!(fmt, ")")
703             }
704             Assert { ref cond, expected, ref msg, .. } => {
705                 write!(fmt, "assert(")?;
706                 if !expected {
707                     write!(fmt, "!")?;
708                 }
709                 write!(fmt, "{:?}, ", cond)?;
710
711                 match *msg {
712                     AssertMessage::BoundsCheck { ref len, ref index } => {
713                         write!(fmt, "{:?}, {:?}, {:?}",
714                                "index out of bounds: the len is {} but the index is {}",
715                                len, index)?;
716                     }
717                     AssertMessage::Math(ref err) => {
718                         write!(fmt, "{:?}", err.description())?;
719                     }
720                 }
721
722                 write!(fmt, ")")
723             }
724         }
725     }
726
727     /// Return the list of labels for the edges to the successor basic blocks.
728     pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
729         use self::TerminatorKind::*;
730         match *self {
731             Return | Resume | Unreachable => vec![],
732             Goto { .. } => vec!["".into()],
733             SwitchInt { ref values, .. } => {
734                 values.iter()
735                       .map(|const_val| {
736                           let mut buf = String::new();
737                           fmt_const_val(&mut buf, &ConstVal::Integral(*const_val)).unwrap();
738                           buf.into()
739                       })
740                       .chain(iter::once(String::from("otherwise").into()))
741                       .collect()
742             }
743             Call { destination: Some(_), cleanup: Some(_), .. } =>
744                 vec!["return".into_cow(), "unwind".into_cow()],
745             Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
746             Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
747             Call { destination: None, cleanup: None, .. } => vec![],
748             DropAndReplace { unwind: None, .. } |
749             Drop { unwind: None, .. } => vec!["return".into_cow()],
750             DropAndReplace { unwind: Some(_), .. } |
751             Drop { unwind: Some(_), .. } => {
752                 vec!["return".into_cow(), "unwind".into_cow()]
753             }
754             Assert { cleanup: None, .. } => vec!["".into()],
755             Assert { .. } =>
756                 vec!["success".into_cow(), "unwind".into_cow()]
757         }
758     }
759 }
760
761 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
762 pub enum AssertMessage<'tcx> {
763     BoundsCheck {
764         len: Operand<'tcx>,
765         index: Operand<'tcx>
766     },
767     Math(ConstMathErr)
768 }
769
770 ///////////////////////////////////////////////////////////////////////////
771 // Statements
772
773 #[derive(Clone, RustcEncodable, RustcDecodable)]
774 pub struct Statement<'tcx> {
775     pub source_info: SourceInfo,
776     pub kind: StatementKind<'tcx>,
777 }
778
779 impl<'tcx> Statement<'tcx> {
780     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
781     /// invalidating statement indices in `Location`s.
782     pub fn make_nop(&mut self) {
783         self.kind = StatementKind::Nop
784     }
785 }
786
787 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
788 pub enum StatementKind<'tcx> {
789     /// Write the RHS Rvalue to the LHS Lvalue.
790     Assign(Lvalue<'tcx>, Rvalue<'tcx>),
791
792     /// Write the discriminant for a variant to the enum Lvalue.
793     SetDiscriminant { lvalue: Lvalue<'tcx>, variant_index: usize },
794
795     /// Start a live range for the storage of the local.
796     StorageLive(Lvalue<'tcx>),
797
798     /// End the current live range for the storage of the local.
799     StorageDead(Lvalue<'tcx>),
800
801     InlineAsm {
802         asm: Box<InlineAsm>,
803         outputs: Vec<Lvalue<'tcx>>,
804         inputs: Vec<Operand<'tcx>>
805     },
806
807     /// No-op. Useful for deleting instructions without affecting statement indices.
808     Nop,
809 }
810
811 impl<'tcx> Debug for Statement<'tcx> {
812     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
813         use self::StatementKind::*;
814         match self.kind {
815             Assign(ref lv, ref rv) => write!(fmt, "{:?} = {:?}", lv, rv),
816             StorageLive(ref lv) => write!(fmt, "StorageLive({:?})", lv),
817             StorageDead(ref lv) => write!(fmt, "StorageDead({:?})", lv),
818             SetDiscriminant{lvalue: ref lv, variant_index: index} => {
819                 write!(fmt, "discriminant({:?}) = {:?}", lv, index)
820             },
821             InlineAsm { ref asm, ref outputs, ref inputs } => {
822                 write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
823             },
824             Nop => write!(fmt, "nop"),
825         }
826     }
827 }
828
829 ///////////////////////////////////////////////////////////////////////////
830 // Lvalues
831
832 /// A path to a value; something that can be evaluated without
833 /// changing or disturbing program state.
834 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
835 pub enum Lvalue<'tcx> {
836     /// local variable
837     Local(Local),
838
839     /// static or static mut variable
840     Static(Box<Static<'tcx>>),
841
842     /// projection out of an lvalue (access a field, deref a pointer, etc)
843     Projection(Box<LvalueProjection<'tcx>>),
844 }
845
846 /// The def-id of a static, along with its normalized type (which is
847 /// stored to avoid requiring normalization when reading MIR).
848 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
849 pub struct Static<'tcx> {
850     pub def_id: DefId,
851     pub ty: Ty<'tcx>,
852 }
853
854 impl_stable_hash_for!(struct Static<'tcx> {
855     def_id,
856     ty
857 });
858
859 /// The `Projection` data structure defines things of the form `B.x`
860 /// or `*B` or `B[index]`. Note that it is parameterized because it is
861 /// shared between `Constant` and `Lvalue`. See the aliases
862 /// `LvalueProjection` etc below.
863 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
864 pub struct Projection<'tcx, B, V> {
865     pub base: B,
866     pub elem: ProjectionElem<'tcx, V>,
867 }
868
869 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
870 pub enum ProjectionElem<'tcx, V> {
871     Deref,
872     Field(Field, Ty<'tcx>),
873     Index(V),
874
875     /// These indices are generated by slice patterns. Easiest to explain
876     /// by example:
877     ///
878     /// ```
879     /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false },
880     /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false },
881     /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true },
882     /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true },
883     /// ```
884     ConstantIndex {
885         /// index or -index (in Python terms), depending on from_end
886         offset: u32,
887         /// thing being indexed must be at least this long
888         min_length: u32,
889         /// counting backwards from end?
890         from_end: bool,
891     },
892
893     /// These indices are generated by slice patterns.
894     ///
895     /// slice[from:-to] in Python terms.
896     Subslice {
897         from: u32,
898         to: u32,
899     },
900
901     /// "Downcast" to a variant of an ADT. Currently, we only introduce
902     /// this for ADTs with more than one variant. It may be better to
903     /// just introduce it always, or always for enums.
904     Downcast(&'tcx AdtDef, usize),
905 }
906
907 /// Alias for projections as they appear in lvalues, where the base is an lvalue
908 /// and the index is an operand.
909 pub type LvalueProjection<'tcx> = Projection<'tcx, Lvalue<'tcx>, Operand<'tcx>>;
910
911 /// Alias for projections as they appear in lvalues, where the base is an lvalue
912 /// and the index is an operand.
913 pub type LvalueElem<'tcx> = ProjectionElem<'tcx, Operand<'tcx>>;
914
915 newtype_index!(Field, "field");
916
917 impl<'tcx> Lvalue<'tcx> {
918     pub fn field(self, f: Field, ty: Ty<'tcx>) -> Lvalue<'tcx> {
919         self.elem(ProjectionElem::Field(f, ty))
920     }
921
922     pub fn deref(self) -> Lvalue<'tcx> {
923         self.elem(ProjectionElem::Deref)
924     }
925
926     pub fn downcast(self, adt_def: &'tcx AdtDef, variant_index: usize) -> Lvalue<'tcx> {
927         self.elem(ProjectionElem::Downcast(adt_def, variant_index))
928     }
929
930     pub fn index(self, index: Operand<'tcx>) -> Lvalue<'tcx> {
931         self.elem(ProjectionElem::Index(index))
932     }
933
934     pub fn elem(self, elem: LvalueElem<'tcx>) -> Lvalue<'tcx> {
935         Lvalue::Projection(Box::new(LvalueProjection {
936             base: self,
937             elem: elem,
938         }))
939     }
940 }
941
942 impl<'tcx> Debug for Lvalue<'tcx> {
943     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
944         use self::Lvalue::*;
945
946         match *self {
947             Local(id) => write!(fmt, "{:?}", id),
948             Static(box self::Static { def_id, ty }) =>
949                 write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
950             Projection(ref data) =>
951                 match data.elem {
952                     ProjectionElem::Downcast(ref adt_def, index) =>
953                         write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
954                     ProjectionElem::Deref =>
955                         write!(fmt, "(*{:?})", data.base),
956                     ProjectionElem::Field(field, ty) =>
957                         write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
958                     ProjectionElem::Index(ref index) =>
959                         write!(fmt, "{:?}[{:?}]", data.base, index),
960                     ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
961                         write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
962                     ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
963                         write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
964                     ProjectionElem::Subslice { from, to } if to == 0 =>
965                         write!(fmt, "{:?}[{:?}:]", data.base, from),
966                     ProjectionElem::Subslice { from, to } if from == 0 =>
967                         write!(fmt, "{:?}[:-{:?}]", data.base, to),
968                     ProjectionElem::Subslice { from, to } =>
969                         write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
970                                from, to),
971
972                 },
973         }
974     }
975 }
976
977 ///////////////////////////////////////////////////////////////////////////
978 // Scopes
979
980 newtype_index!(VisibilityScope, "scope");
981 pub const ARGUMENT_VISIBILITY_SCOPE : VisibilityScope = VisibilityScope(0);
982
983 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
984 pub struct VisibilityScopeData {
985     pub span: Span,
986     pub parent_scope: Option<VisibilityScope>,
987 }
988
989 ///////////////////////////////////////////////////////////////////////////
990 // Operands
991
992 /// These are values that can appear inside an rvalue (or an index
993 /// lvalue). They are intentionally limited to prevent rvalues from
994 /// being nested in one another.
995 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable)]
996 pub enum Operand<'tcx> {
997     Consume(Lvalue<'tcx>),
998     Constant(Box<Constant<'tcx>>),
999 }
1000
1001 impl<'tcx> Debug for Operand<'tcx> {
1002     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1003         use self::Operand::*;
1004         match *self {
1005             Constant(ref a) => write!(fmt, "{:?}", a),
1006             Consume(ref lv) => write!(fmt, "{:?}", lv),
1007         }
1008     }
1009 }
1010
1011 impl<'tcx> Operand<'tcx> {
1012     pub fn function_handle<'a>(
1013         tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
1014         def_id: DefId,
1015         substs: &'tcx Substs<'tcx>,
1016         span: Span,
1017     ) -> Self {
1018         Operand::Constant(box Constant {
1019             span: span,
1020             ty: tcx.type_of(def_id).subst(tcx, substs),
1021             literal: Literal::Value { value: ConstVal::Function(def_id, substs) },
1022         })
1023     }
1024
1025 }
1026
1027 ///////////////////////////////////////////////////////////////////////////
1028 /// Rvalues
1029
1030 #[derive(Clone, RustcEncodable, RustcDecodable)]
1031 pub enum Rvalue<'tcx> {
1032     /// x (either a move or copy, depending on type of x)
1033     Use(Operand<'tcx>),
1034
1035     /// [x; 32]
1036     Repeat(Operand<'tcx>, ConstUsize),
1037
1038     /// &x or &mut x
1039     Ref(Region<'tcx>, BorrowKind, Lvalue<'tcx>),
1040
1041     /// length of a [X] or [X;n] value
1042     Len(Lvalue<'tcx>),
1043
1044     Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
1045
1046     BinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1047     CheckedBinaryOp(BinOp, Operand<'tcx>, Operand<'tcx>),
1048
1049     UnaryOp(UnOp, Operand<'tcx>),
1050
1051     /// Read the discriminant of an ADT.
1052     ///
1053     /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot
1054     /// be defined to return, say, a 0) if ADT is not an enum.
1055     Discriminant(Lvalue<'tcx>),
1056
1057     /// Creates an *uninitialized* Box
1058     Box(Ty<'tcx>),
1059
1060     /// Create an aggregate value, like a tuple or struct.  This is
1061     /// only needed because we want to distinguish `dest = Foo { x:
1062     /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case
1063     /// that `Foo` has a destructor. These rvalues can be optimized
1064     /// away after type-checking and before lowering.
1065     Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1066 }
1067
1068 #[derive(Clone, Copy, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1069 pub enum CastKind {
1070     Misc,
1071
1072     /// Convert unique, zero-sized type for a fn to fn()
1073     ReifyFnPointer,
1074
1075     /// Convert non capturing closure to fn()
1076     ClosureFnPointer,
1077
1078     /// Convert safe fn() to unsafe fn()
1079     UnsafeFnPointer,
1080
1081     /// "Unsize" -- convert a thin-or-fat pointer to a fat pointer.
1082     /// trans must figure out the details once full monomorphization
1083     /// is known. For example, this could be used to cast from a
1084     /// `&[i32;N]` to a `&[i32]`, or a `Box<T>` to a `Box<Trait>`
1085     /// (presuming `T: Trait`).
1086     Unsize,
1087 }
1088
1089 #[derive(Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1090 pub enum AggregateKind<'tcx> {
1091     /// The type is of the element
1092     Array(Ty<'tcx>),
1093     Tuple,
1094     /// The second field is variant number (discriminant), it's equal to 0
1095     /// for struct and union expressions. The fourth field is active field
1096     /// number and is present only for union expressions.
1097     Adt(&'tcx AdtDef, usize, &'tcx Substs<'tcx>, Option<usize>),
1098     Closure(DefId, ClosureSubsts<'tcx>),
1099 }
1100
1101 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1102 pub enum BinOp {
1103     /// The `+` operator (addition)
1104     Add,
1105     /// The `-` operator (subtraction)
1106     Sub,
1107     /// The `*` operator (multiplication)
1108     Mul,
1109     /// The `/` operator (division)
1110     Div,
1111     /// The `%` operator (modulus)
1112     Rem,
1113     /// The `^` operator (bitwise xor)
1114     BitXor,
1115     /// The `&` operator (bitwise and)
1116     BitAnd,
1117     /// The `|` operator (bitwise or)
1118     BitOr,
1119     /// The `<<` operator (shift left)
1120     Shl,
1121     /// The `>>` operator (shift right)
1122     Shr,
1123     /// The `==` operator (equality)
1124     Eq,
1125     /// The `<` operator (less than)
1126     Lt,
1127     /// The `<=` operator (less than or equal to)
1128     Le,
1129     /// The `!=` operator (not equal to)
1130     Ne,
1131     /// The `>=` operator (greater than or equal to)
1132     Ge,
1133     /// The `>` operator (greater than)
1134     Gt,
1135 }
1136
1137 impl BinOp {
1138     pub fn is_checkable(self) -> bool {
1139         use self::BinOp::*;
1140         match self {
1141             Add | Sub | Mul | Shl | Shr => true,
1142             _ => false
1143         }
1144     }
1145 }
1146
1147 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
1148 pub enum UnOp {
1149     /// The `!` operator for logical inversion
1150     Not,
1151     /// The `-` operator for negation
1152     Neg,
1153 }
1154
1155 impl<'tcx> Debug for Rvalue<'tcx> {
1156     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1157         use self::Rvalue::*;
1158
1159         match *self {
1160             Use(ref lvalue) => write!(fmt, "{:?}", lvalue),
1161             Repeat(ref a, ref b) => write!(fmt, "[{:?}; {:?}]", a, b),
1162             Len(ref a) => write!(fmt, "Len({:?})", a),
1163             Cast(ref kind, ref lv, ref ty) => write!(fmt, "{:?} as {:?} ({:?})", lv, ty, kind),
1164             BinaryOp(ref op, ref a, ref b) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
1165             CheckedBinaryOp(ref op, ref a, ref b) => {
1166                 write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
1167             }
1168             UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
1169             Discriminant(ref lval) => write!(fmt, "discriminant({:?})", lval),
1170             Box(ref t) => write!(fmt, "Box({:?})", t),
1171             Ref(_, borrow_kind, ref lv) => {
1172                 let kind_str = match borrow_kind {
1173                     BorrowKind::Shared => "",
1174                     BorrowKind::Mut | BorrowKind::Unique => "mut ",
1175                 };
1176                 write!(fmt, "&{}{:?}", kind_str, lv)
1177             }
1178
1179             Aggregate(ref kind, ref lvs) => {
1180                 fn fmt_tuple(fmt: &mut Formatter, lvs: &[Operand]) -> fmt::Result {
1181                     let mut tuple_fmt = fmt.debug_tuple("");
1182                     for lv in lvs {
1183                         tuple_fmt.field(lv);
1184                     }
1185                     tuple_fmt.finish()
1186                 }
1187
1188                 match **kind {
1189                     AggregateKind::Array(_) => write!(fmt, "{:?}", lvs),
1190
1191                     AggregateKind::Tuple => {
1192                         match lvs.len() {
1193                             0 => write!(fmt, "()"),
1194                             1 => write!(fmt, "({:?},)", lvs[0]),
1195                             _ => fmt_tuple(fmt, lvs),
1196                         }
1197                     }
1198
1199                     AggregateKind::Adt(adt_def, variant, substs, _) => {
1200                         let variant_def = &adt_def.variants[variant];
1201
1202                         ppaux::parameterized(fmt, substs, variant_def.did, &[])?;
1203
1204                         match variant_def.ctor_kind {
1205                             CtorKind::Const => Ok(()),
1206                             CtorKind::Fn => fmt_tuple(fmt, lvs),
1207                             CtorKind::Fictive => {
1208                                 let mut struct_fmt = fmt.debug_struct("");
1209                                 for (field, lv) in variant_def.fields.iter().zip(lvs) {
1210                                     struct_fmt.field(&field.name.as_str(), lv);
1211                                 }
1212                                 struct_fmt.finish()
1213                             }
1214                         }
1215                     }
1216
1217                     AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
1218                         if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
1219                             let name = format!("[closure@{:?}]", tcx.hir.span(node_id));
1220                             let mut struct_fmt = fmt.debug_struct(&name);
1221
1222                             tcx.with_freevars(node_id, |freevars| {
1223                                 for (freevar, lv) in freevars.iter().zip(lvs) {
1224                                     let def_id = freevar.def.def_id();
1225                                     let var_id = tcx.hir.as_local_node_id(def_id).unwrap();
1226                                     let var_name = tcx.local_var_name_str(var_id);
1227                                     struct_fmt.field(&var_name, lv);
1228                                 }
1229                             });
1230
1231                             struct_fmt.finish()
1232                         } else {
1233                             write!(fmt, "[closure]")
1234                         }
1235                     }),
1236                 }
1237             }
1238         }
1239     }
1240 }
1241
1242 ///////////////////////////////////////////////////////////////////////////
1243 /// Constants
1244 ///
1245 /// Two constants are equal if they are the same constant. Note that
1246 /// this does not necessarily mean that they are "==" in Rust -- in
1247 /// particular one must be wary of `NaN`!
1248
1249 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1250 pub struct Constant<'tcx> {
1251     pub span: Span,
1252     pub ty: Ty<'tcx>,
1253     pub literal: Literal<'tcx>,
1254 }
1255
1256 newtype_index!(Promoted, "promoted");
1257
1258 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
1259 pub enum Literal<'tcx> {
1260     Item {
1261         def_id: DefId,
1262         substs: &'tcx Substs<'tcx>,
1263     },
1264     Value {
1265         value: ConstVal<'tcx>,
1266     },
1267     Promoted {
1268         // Index into the `promoted` vector of `Mir`.
1269         index: Promoted
1270     },
1271 }
1272
1273 impl<'tcx> Debug for Constant<'tcx> {
1274     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1275         write!(fmt, "{:?}", self.literal)
1276     }
1277 }
1278
1279 impl<'tcx> Debug for Literal<'tcx> {
1280     fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
1281         use self::Literal::*;
1282         match *self {
1283             Item { def_id, substs } => {
1284                 ppaux::parameterized(fmt, substs, def_id, &[])
1285             }
1286             Value { ref value } => {
1287                 write!(fmt, "const ")?;
1288                 fmt_const_val(fmt, value)
1289             }
1290             Promoted { index } => {
1291                 write!(fmt, "{:?}", index)
1292             }
1293         }
1294     }
1295 }
1296
1297 /// Write a `ConstVal` in a way closer to the original source code than the `Debug` output.
1298 fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ConstVal) -> fmt::Result {
1299     use middle::const_val::ConstVal::*;
1300     match *const_val {
1301         Float(f) => write!(fmt, "{:?}", f),
1302         Integral(n) => write!(fmt, "{}", n),
1303         Str(ref s) => write!(fmt, "{:?}", s),
1304         ByteStr(ref bytes) => {
1305             let escaped: String = bytes
1306                 .iter()
1307                 .flat_map(|&ch| ascii::escape_default(ch).map(|c| c as char))
1308                 .collect();
1309             write!(fmt, "b\"{}\"", escaped)
1310         }
1311         Bool(b) => write!(fmt, "{:?}", b),
1312         Char(c) => write!(fmt, "{:?}", c),
1313         Variant(def_id) |
1314         Function(def_id, _) => write!(fmt, "{}", item_path_str(def_id)),
1315         Struct(_) | Tuple(_) | Array(_) | Repeat(..) =>
1316             bug!("ConstVal `{:?}` should not be in MIR", const_val),
1317     }
1318 }
1319
1320 fn item_path_str(def_id: DefId) -> String {
1321     ty::tls::with(|tcx| tcx.item_path_str(def_id))
1322 }
1323
1324 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
1325
1326     type Node = BasicBlock;
1327
1328     fn num_nodes(&self) -> usize { self.basic_blocks.len() }
1329
1330     fn start_node(&self) -> Self::Node { START_BLOCK }
1331
1332     fn predecessors<'graph>(&'graph self, node: Self::Node)
1333                             -> <Self as GraphPredecessors<'graph>>::Iter
1334     {
1335         self.predecessors_for(node).clone().into_iter()
1336     }
1337     fn successors<'graph>(&'graph self, node: Self::Node)
1338                           -> <Self as GraphSuccessors<'graph>>::Iter
1339     {
1340         self.basic_blocks[node].terminator().successors().into_owned().into_iter()
1341     }
1342 }
1343
1344 impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
1345     type Item = BasicBlock;
1346     type Iter = IntoIter<BasicBlock>;
1347 }
1348
1349 impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
1350     type Item = BasicBlock;
1351     type Iter = IntoIter<BasicBlock>;
1352 }
1353
1354 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
1355 pub struct Location {
1356     /// the location is within this block
1357     pub block: BasicBlock,
1358
1359     /// the location is the start of the this statement; or, if `statement_index`
1360     /// == num-statements, then the start of the terminator.
1361     pub statement_index: usize,
1362 }
1363
1364 impl fmt::Debug for Location {
1365     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1366         write!(fmt, "{:?}[{}]", self.block, self.statement_index)
1367     }
1368 }
1369
1370 impl Location {
1371     pub fn dominates(&self, other: &Location, dominators: &Dominators<BasicBlock>) -> bool {
1372         if self.block == other.block {
1373             self.statement_index <= other.statement_index
1374         } else {
1375             dominators.is_dominated_by(other.block, self.block)
1376         }
1377     }
1378 }
1379
1380
1381 /*
1382  * TypeFoldable implementations for MIR types
1383  */
1384
1385 impl<'tcx> TypeFoldable<'tcx> for Mir<'tcx> {
1386     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1387         Mir {
1388             basic_blocks: self.basic_blocks.fold_with(folder),
1389             visibility_scopes: self.visibility_scopes.clone(),
1390             promoted: self.promoted.fold_with(folder),
1391             return_ty: self.return_ty.fold_with(folder),
1392             local_decls: self.local_decls.fold_with(folder),
1393             arg_count: self.arg_count,
1394             upvar_decls: self.upvar_decls.clone(),
1395             spread_arg: self.spread_arg,
1396             span: self.span,
1397             cache: cache::Cache::new()
1398         }
1399     }
1400
1401     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1402         self.basic_blocks.visit_with(visitor) ||
1403         self.promoted.visit_with(visitor)     ||
1404         self.return_ty.visit_with(visitor)    ||
1405         self.local_decls.visit_with(visitor)
1406     }
1407 }
1408
1409 impl<'tcx> TypeFoldable<'tcx> for LocalDecl<'tcx> {
1410     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1411         LocalDecl {
1412             ty: self.ty.fold_with(folder),
1413             ..self.clone()
1414         }
1415     }
1416
1417     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1418         self.ty.visit_with(visitor)
1419     }
1420 }
1421
1422 impl<'tcx> TypeFoldable<'tcx> for BasicBlockData<'tcx> {
1423     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1424         BasicBlockData {
1425             statements: self.statements.fold_with(folder),
1426             terminator: self.terminator.fold_with(folder),
1427             is_cleanup: self.is_cleanup
1428         }
1429     }
1430
1431     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1432         self.statements.visit_with(visitor) || self.terminator.visit_with(visitor)
1433     }
1434 }
1435
1436 impl<'tcx> TypeFoldable<'tcx> for Statement<'tcx> {
1437     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1438         use mir::StatementKind::*;
1439
1440         let kind = match self.kind {
1441             Assign(ref lval, ref rval) => Assign(lval.fold_with(folder), rval.fold_with(folder)),
1442             SetDiscriminant { ref lvalue, variant_index } => SetDiscriminant {
1443                 lvalue: lvalue.fold_with(folder),
1444                 variant_index: variant_index
1445             },
1446             StorageLive(ref lval) => StorageLive(lval.fold_with(folder)),
1447             StorageDead(ref lval) => StorageDead(lval.fold_with(folder)),
1448             InlineAsm { ref asm, ref outputs, ref inputs } => InlineAsm {
1449                 asm: asm.clone(),
1450                 outputs: outputs.fold_with(folder),
1451                 inputs: inputs.fold_with(folder)
1452             },
1453             Nop => Nop,
1454         };
1455         Statement {
1456             source_info: self.source_info,
1457             kind: kind
1458         }
1459     }
1460
1461     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1462         use mir::StatementKind::*;
1463
1464         match self.kind {
1465             Assign(ref lval, ref rval) => { lval.visit_with(visitor) || rval.visit_with(visitor) }
1466             SetDiscriminant { ref lvalue, .. } |
1467             StorageLive(ref lvalue) |
1468             StorageDead(ref lvalue) => lvalue.visit_with(visitor),
1469             InlineAsm { ref outputs, ref inputs, .. } =>
1470                 outputs.visit_with(visitor) || inputs.visit_with(visitor),
1471             Nop => false,
1472         }
1473     }
1474 }
1475
1476 impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
1477     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1478         use mir::TerminatorKind::*;
1479
1480         let kind = match self.kind {
1481             Goto { target } => Goto { target: target },
1482             SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
1483                 discr: discr.fold_with(folder),
1484                 switch_ty: switch_ty.fold_with(folder),
1485                 values: values.clone(),
1486                 targets: targets.clone()
1487             },
1488             Drop { ref location, target, unwind } => Drop {
1489                 location: location.fold_with(folder),
1490                 target: target,
1491                 unwind: unwind
1492             },
1493             DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
1494                 location: location.fold_with(folder),
1495                 value: value.fold_with(folder),
1496                 target: target,
1497                 unwind: unwind
1498             },
1499             Call { ref func, ref args, ref destination, cleanup } => {
1500                 let dest = destination.as_ref().map(|&(ref loc, dest)| {
1501                     (loc.fold_with(folder), dest)
1502                 });
1503
1504                 Call {
1505                     func: func.fold_with(folder),
1506                     args: args.fold_with(folder),
1507                     destination: dest,
1508                     cleanup: cleanup
1509                 }
1510             },
1511             Assert { ref cond, expected, ref msg, target, cleanup } => {
1512                 let msg = if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1513                     AssertMessage::BoundsCheck {
1514                         len: len.fold_with(folder),
1515                         index: index.fold_with(folder),
1516                     }
1517                 } else {
1518                     msg.clone()
1519                 };
1520                 Assert {
1521                     cond: cond.fold_with(folder),
1522                     expected: expected,
1523                     msg: msg,
1524                     target: target,
1525                     cleanup: cleanup
1526                 }
1527             },
1528             Resume => Resume,
1529             Return => Return,
1530             Unreachable => Unreachable,
1531         };
1532         Terminator {
1533             source_info: self.source_info,
1534             kind: kind
1535         }
1536     }
1537
1538     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1539         use mir::TerminatorKind::*;
1540
1541         match self.kind {
1542             SwitchInt { ref discr, switch_ty, .. } =>
1543                 discr.visit_with(visitor) || switch_ty.visit_with(visitor),
1544             Drop { ref location, ..} => location.visit_with(visitor),
1545             DropAndReplace { ref location, ref value, ..} =>
1546                 location.visit_with(visitor) || value.visit_with(visitor),
1547             Call { ref func, ref args, ref destination, .. } => {
1548                 let dest = if let Some((ref loc, _)) = *destination {
1549                     loc.visit_with(visitor)
1550                 } else { false };
1551                 dest || func.visit_with(visitor) || args.visit_with(visitor)
1552             },
1553             Assert { ref cond, ref msg, .. } => {
1554                 if cond.visit_with(visitor) {
1555                     if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
1556                         len.visit_with(visitor) || index.visit_with(visitor)
1557                     } else {
1558                         false
1559                     }
1560                 } else {
1561                     false
1562                 }
1563             },
1564             Goto { .. } |
1565             Resume |
1566             Return |
1567             Unreachable => false
1568         }
1569     }
1570 }
1571
1572 impl<'tcx> TypeFoldable<'tcx> for Lvalue<'tcx> {
1573     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1574         match self {
1575             &Lvalue::Projection(ref p) => Lvalue::Projection(p.fold_with(folder)),
1576             _ => self.clone()
1577         }
1578     }
1579
1580     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1581         if let &Lvalue::Projection(ref p) = self {
1582             p.visit_with(visitor)
1583         } else {
1584             false
1585         }
1586     }
1587 }
1588
1589 impl<'tcx> TypeFoldable<'tcx> for Rvalue<'tcx> {
1590     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1591         use mir::Rvalue::*;
1592         match *self {
1593             Use(ref op) => Use(op.fold_with(folder)),
1594             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
1595             Ref(region, bk, ref lval) => Ref(region.fold_with(folder), bk, lval.fold_with(folder)),
1596             Len(ref lval) => Len(lval.fold_with(folder)),
1597             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
1598             BinaryOp(op, ref rhs, ref lhs) =>
1599                 BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1600             CheckedBinaryOp(op, ref rhs, ref lhs) =>
1601                 CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
1602             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
1603             Discriminant(ref lval) => Discriminant(lval.fold_with(folder)),
1604             Box(ty) => Box(ty.fold_with(folder)),
1605             Aggregate(ref kind, ref fields) => {
1606                 let kind = box match **kind {
1607                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
1608                     AggregateKind::Tuple => AggregateKind::Tuple,
1609                     AggregateKind::Adt(def, v, substs, n) =>
1610                         AggregateKind::Adt(def, v, substs.fold_with(folder), n),
1611                     AggregateKind::Closure(id, substs) =>
1612                         AggregateKind::Closure(id, substs.fold_with(folder))
1613                 };
1614                 Aggregate(kind, fields.fold_with(folder))
1615             }
1616         }
1617     }
1618
1619     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1620         use mir::Rvalue::*;
1621         match *self {
1622             Use(ref op) => op.visit_with(visitor),
1623             Repeat(ref op, _) => op.visit_with(visitor),
1624             Ref(region, _, ref lval) => region.visit_with(visitor) || lval.visit_with(visitor),
1625             Len(ref lval) => lval.visit_with(visitor),
1626             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
1627             BinaryOp(_, ref rhs, ref lhs) |
1628             CheckedBinaryOp(_, ref rhs, ref lhs) =>
1629                 rhs.visit_with(visitor) || lhs.visit_with(visitor),
1630             UnaryOp(_, ref val) => val.visit_with(visitor),
1631             Discriminant(ref lval) => lval.visit_with(visitor),
1632             Box(ty) => ty.visit_with(visitor),
1633             Aggregate(ref kind, ref fields) => {
1634                 (match **kind {
1635                     AggregateKind::Array(ty) => ty.visit_with(visitor),
1636                     AggregateKind::Tuple => false,
1637                     AggregateKind::Adt(_, _, substs, _) => substs.visit_with(visitor),
1638                     AggregateKind::Closure(_, substs) => substs.visit_with(visitor)
1639                 }) || fields.visit_with(visitor)
1640             }
1641         }
1642     }
1643 }
1644
1645 impl<'tcx> TypeFoldable<'tcx> for Operand<'tcx> {
1646     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1647         match *self {
1648             Operand::Consume(ref lval) => Operand::Consume(lval.fold_with(folder)),
1649             Operand::Constant(ref c) => Operand::Constant(c.fold_with(folder)),
1650         }
1651     }
1652
1653     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1654         match *self {
1655             Operand::Consume(ref lval) => lval.visit_with(visitor),
1656             Operand::Constant(ref c) => c.visit_with(visitor)
1657         }
1658     }
1659 }
1660
1661 impl<'tcx, B, V> TypeFoldable<'tcx> for Projection<'tcx, B, V>
1662     where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>
1663 {
1664     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1665         use mir::ProjectionElem::*;
1666
1667         let base = self.base.fold_with(folder);
1668         let elem = match self.elem {
1669             Deref => Deref,
1670             Field(f, ty) => Field(f, ty.fold_with(folder)),
1671             Index(ref v) => Index(v.fold_with(folder)),
1672             ref elem => elem.clone()
1673         };
1674
1675         Projection {
1676             base: base,
1677             elem: elem
1678         }
1679     }
1680
1681     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
1682         use mir::ProjectionElem::*;
1683
1684         self.base.visit_with(visitor) ||
1685             match self.elem {
1686                 Field(_, ty) => ty.visit_with(visitor),
1687                 Index(ref v) => v.visit_with(visitor),
1688                 _ => false
1689             }
1690     }
1691 }
1692
1693 impl<'tcx> TypeFoldable<'tcx> for Constant<'tcx> {
1694     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1695         Constant {
1696             span: self.span.clone(),
1697             ty: self.ty.fold_with(folder),
1698             literal: self.literal.fold_with(folder)
1699         }
1700     }
1701     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1702         self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
1703     }
1704 }
1705
1706 impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
1707     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1708         match *self {
1709             Literal::Item { def_id, substs } => Literal::Item {
1710                 def_id: def_id,
1711                 substs: substs.fold_with(folder)
1712             },
1713             _ => self.clone()
1714         }
1715     }
1716     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1717         match *self {
1718             Literal::Item { substs, .. } => substs.visit_with(visitor),
1719             _ => false
1720         }
1721     }
1722 }