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