]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/dataflow/move_paths/mod.rs
Specify output filenames for compatibility with Windows
[rust.git] / src / librustc_mir / dataflow / move_paths / mod.rs
1 // Copyright 2012-2016 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
12 use rustc::ty::{self, TyCtxt};
13 use rustc::mir::*;
14 use rustc::util::nodemap::FxHashMap;
15 use rustc_data_structures::indexed_vec::{IndexVec};
16 use syntax_pos::{Span};
17
18 use std::fmt;
19 use std::ops::{Index, IndexMut};
20
21 use self::abs_domain::{AbstractElem, Lift};
22
23 mod abs_domain;
24
25 // This submodule holds some newtype'd Index wrappers that are using
26 // NonZero to ensure that Option<Index> occupies only a single word.
27 // They are in a submodule to impose privacy restrictions; namely, to
28 // ensure that other code does not accidentally access `index.0`
29 // (which is likely to yield a subtle off-by-one error).
30 pub(crate) mod indexes {
31     use std::fmt;
32     use core::nonzero::NonZero;
33     use rustc_data_structures::indexed_vec::Idx;
34
35     macro_rules! new_index {
36         ($Index:ident, $debug_name:expr) => {
37             #[derive(Copy, Clone, PartialEq, Eq, Hash)]
38             pub struct $Index(NonZero<usize>);
39
40             impl Idx for $Index {
41                 fn new(idx: usize) -> Self {
42                     $Index(NonZero::new(idx + 1).unwrap())
43                 }
44                 fn index(self) -> usize {
45                     self.0.get() - 1
46                 }
47             }
48
49             impl fmt::Debug for $Index {
50                 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
51                     write!(fmt, "{}{}", $debug_name, self.index())
52                 }
53             }
54         }
55     }
56
57     /// Index into MovePathData.move_paths
58     new_index!(MovePathIndex, "mp");
59
60     /// Index into MoveData.moves.
61     new_index!(MoveOutIndex, "mo");
62
63     /// Index into MoveData.inits.
64     new_index!(InitIndex, "in");
65
66     /// Index into Borrows.locations
67     new_index!(BorrowIndex, "bw");
68
69     /// Index into Reservations/Activations bitvector
70     new_index!(ReserveOrActivateIndex, "ra");
71 }
72
73 pub use self::indexes::MovePathIndex;
74 pub use self::indexes::MoveOutIndex;
75 pub use self::indexes::InitIndex;
76
77 impl MoveOutIndex {
78     pub fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex {
79         move_data.moves[*self].path
80     }
81 }
82
83 /// `MovePath` is a canonicalized representation of a path that is
84 /// moved or assigned to.
85 ///
86 /// It follows a tree structure.
87 ///
88 /// Given `struct X { m: M, n: N }` and `x: X`, moves like `drop x.m;`
89 /// move *out* of the l-value `x.m`.
90 ///
91 /// The MovePaths representing `x.m` and `x.n` are siblings (that is,
92 /// one of them will link to the other via the `next_sibling` field,
93 /// and the other will have no entry in its `next_sibling` field), and
94 /// they both have the MovePath representing `x` as their parent.
95 #[derive(Clone)]
96 pub struct MovePath<'tcx> {
97     pub next_sibling: Option<MovePathIndex>,
98     pub first_child: Option<MovePathIndex>,
99     pub parent: Option<MovePathIndex>,
100     pub place: Place<'tcx>,
101 }
102
103 impl<'tcx> fmt::Debug for MovePath<'tcx> {
104     fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
105         write!(w, "MovePath {{")?;
106         if let Some(parent) = self.parent {
107             write!(w, " parent: {:?},", parent)?;
108         }
109         if let Some(first_child) = self.first_child {
110             write!(w, " first_child: {:?},", first_child)?;
111         }
112         if let Some(next_sibling) = self.next_sibling {
113             write!(w, " next_sibling: {:?}", next_sibling)?;
114         }
115         write!(w, " place: {:?} }}", self.place)
116     }
117 }
118
119 impl<'tcx> fmt::Display for MovePath<'tcx> {
120     fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
121         write!(w, "{:?}", self.place)
122     }
123 }
124
125 #[derive(Debug)]
126 pub struct MoveData<'tcx> {
127     pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
128     pub moves: IndexVec<MoveOutIndex, MoveOut>,
129     /// Each Location `l` is mapped to the MoveOut's that are effects
130     /// of executing the code at `l`. (There can be multiple MoveOut's
131     /// for a given `l` because each MoveOut is associated with one
132     /// particular path being moved.)
133     pub loc_map: LocationMap<Vec<MoveOutIndex>>,
134     pub path_map: IndexVec<MovePathIndex, Vec<MoveOutIndex>>,
135     pub rev_lookup: MovePathLookup<'tcx>,
136     pub inits: IndexVec<InitIndex, Init>,
137     /// Each Location `l` is mapped to the Inits that are effects
138     /// of executing the code at `l`.
139     pub init_loc_map: LocationMap<Vec<InitIndex>>,
140     pub init_path_map: IndexVec<MovePathIndex, Vec<InitIndex>>,
141 }
142
143 pub trait HasMoveData<'tcx> {
144     fn move_data(&self) -> &MoveData<'tcx>;
145 }
146
147 #[derive(Debug)]
148 pub struct LocationMap<T> {
149     /// Location-indexed (BasicBlock for outer index, index within BB
150     /// for inner index) map.
151     pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
152 }
153
154 impl<T> Index<Location> for LocationMap<T> {
155     type Output = T;
156     fn index(&self, index: Location) -> &Self::Output {
157         &self.map[index.block][index.statement_index]
158     }
159 }
160
161 impl<T> IndexMut<Location> for LocationMap<T> {
162     fn index_mut(&mut self, index: Location) -> &mut Self::Output {
163         &mut self.map[index.block][index.statement_index]
164     }
165 }
166
167 impl<T> LocationMap<T> where T: Default + Clone {
168     fn new(mir: &Mir) -> Self {
169         LocationMap {
170             map: mir.basic_blocks().iter().map(|block| {
171                 vec![T::default(); block.statements.len()+1]
172             }).collect()
173         }
174     }
175 }
176
177 /// `MoveOut` represents a point in a program that moves out of some
178 /// L-value; i.e., "creates" uninitialized memory.
179 ///
180 /// With respect to dataflow analysis:
181 /// - Generated by moves and declaration of uninitialized variables.
182 /// - Killed by assignments to the memory.
183 #[derive(Copy, Clone)]
184 pub struct MoveOut {
185     /// path being moved
186     pub path: MovePathIndex,
187     /// location of move
188     pub source: Location,
189 }
190
191 impl fmt::Debug for MoveOut {
192     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
193         write!(fmt, "{:?}@{:?}", self.path, self.source)
194     }
195 }
196
197 /// `Init` represents a point in a program that initializes some L-value;
198 #[derive(Copy, Clone)]
199 pub struct Init {
200     /// path being initialized
201     pub path: MovePathIndex,
202     /// span of initialization
203     pub span: Span,
204     /// Extra information about this initialization
205     pub kind: InitKind,
206 }
207
208 /// Additional information about the initialization.
209 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
210 pub enum InitKind {
211     /// Deep init, even on panic
212     Deep,
213     /// Only does a shallow init
214     Shallow,
215     /// This doesn't initialize the variabe on panic (and a panic is possible).
216     NonPanicPathOnly,
217 }
218
219 impl fmt::Debug for Init {
220     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
221         write!(fmt, "{:?}@{:?} ({:?})", self.path, self.span, self.kind)
222     }
223 }
224
225 /// Tables mapping from an l-value to its MovePathIndex.
226 #[derive(Debug)]
227 pub struct MovePathLookup<'tcx> {
228     locals: IndexVec<Local, MovePathIndex>,
229
230     /// projections are made from a base-place and a projection
231     /// elem. The base-place will have a unique MovePathIndex; we use
232     /// the latter as the index into the outer vector (narrowing
233     /// subsequent search so that it is solely relative to that
234     /// base-place). For the remaining lookup, we map the projection
235     /// elem to the associated MovePathIndex.
236     projections: FxHashMap<(MovePathIndex, AbstractElem<'tcx>), MovePathIndex>
237 }
238
239 mod builder;
240
241 #[derive(Copy, Clone, Debug)]
242 pub enum LookupResult {
243     Exact(MovePathIndex),
244     Parent(Option<MovePathIndex>)
245 }
246
247 impl<'tcx> MovePathLookup<'tcx> {
248     // Unlike the builder `fn move_path_for` below, this lookup
249     // alternative will *not* create a MovePath on the fly for an
250     // unknown l-value, but will rather return the nearest available
251     // parent.
252     pub fn find(&self, place: &Place<'tcx>) -> LookupResult {
253         match *place {
254             Place::Local(local) => LookupResult::Exact(self.locals[local]),
255             Place::Static(..) => LookupResult::Parent(None),
256             Place::Projection(ref proj) => {
257                 match self.find(&proj.base) {
258                     LookupResult::Exact(base_path) => {
259                         match self.projections.get(&(base_path, proj.elem.lift())) {
260                             Some(&subpath) => LookupResult::Exact(subpath),
261                             None => LookupResult::Parent(Some(base_path))
262                         }
263                     }
264                     inexact => inexact
265                 }
266             }
267         }
268     }
269
270     pub fn find_local(&self, local: Local) -> MovePathIndex {
271         self.locals[local]
272     }
273 }
274
275 #[derive(Debug)]
276 pub struct IllegalMoveOrigin<'tcx> {
277     pub(crate) span: Span,
278     pub(crate) kind: IllegalMoveOriginKind<'tcx>,
279 }
280
281 #[derive(Debug)]
282 pub(crate) enum IllegalMoveOriginKind<'tcx> {
283     Static,
284     BorrowedContent,
285     InteriorOfTypeWithDestructor { container_ty: ty::Ty<'tcx> },
286     InteriorOfSliceOrArray { ty: ty::Ty<'tcx>, is_index: bool, },
287 }
288
289 #[derive(Debug)]
290 pub enum MoveError<'tcx> {
291     IllegalMove { cannot_move_out_of: IllegalMoveOrigin<'tcx> },
292     UnionMove { path: MovePathIndex },
293 }
294
295 impl<'tcx> MoveError<'tcx> {
296     fn cannot_move_out_of(span: Span, kind: IllegalMoveOriginKind<'tcx>) -> Self {
297         let origin = IllegalMoveOrigin { span, kind };
298         MoveError::IllegalMove { cannot_move_out_of: origin }
299     }
300 }
301
302 impl<'a, 'gcx, 'tcx> MoveData<'tcx> {
303     pub fn gather_moves(mir: &Mir<'tcx>, tcx: TyCtxt<'a, 'gcx, 'tcx>)
304                         -> Result<Self, (Self, Vec<MoveError<'tcx>>)> {
305         builder::gather_moves(mir, tcx)
306     }
307 }