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