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