]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/dataflow/move_paths/mod.rs
3051a687eac7008c519c32b4d51ed3b854e39ce6
[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 std::num::NonZeroUsize;
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, PartialOrd, Ord)]
38             pub struct $Index(NonZeroUsize);
39
40             impl Idx for $Index {
41                 fn new(idx: usize) -> Self {
42                     $Index(NonZeroUsize::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
70 pub use self::indexes::MovePathIndex;
71 pub use self::indexes::MoveOutIndex;
72 pub use self::indexes::InitIndex;
73
74 impl MoveOutIndex {
75     pub fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex {
76         move_data.moves[*self].path
77     }
78 }
79
80 /// `MovePath` is a canonicalized representation of a path that is
81 /// moved or assigned to.
82 ///
83 /// It follows a tree structure.
84 ///
85 /// Given `struct X { m: M, n: N }` and `x: X`, moves like `drop x.m;`
86 /// move *out* of the place `x.m`.
87 ///
88 /// The MovePaths representing `x.m` and `x.n` are siblings (that is,
89 /// one of them will link to the other via the `next_sibling` field,
90 /// and the other will have no entry in its `next_sibling` field), and
91 /// they both have the MovePath representing `x` as their parent.
92 #[derive(Clone)]
93 pub struct MovePath<'tcx> {
94     pub next_sibling: Option<MovePathIndex>,
95     pub first_child: Option<MovePathIndex>,
96     pub parent: Option<MovePathIndex>,
97     pub place: Place<'tcx>,
98 }
99
100 impl<'tcx> fmt::Debug for MovePath<'tcx> {
101     fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
102         write!(w, "MovePath {{")?;
103         if let Some(parent) = self.parent {
104             write!(w, " parent: {:?},", parent)?;
105         }
106         if let Some(first_child) = self.first_child {
107             write!(w, " first_child: {:?},", first_child)?;
108         }
109         if let Some(next_sibling) = self.next_sibling {
110             write!(w, " next_sibling: {:?}", next_sibling)?;
111         }
112         write!(w, " place: {:?} }}", self.place)
113     }
114 }
115
116 impl<'tcx> fmt::Display for MovePath<'tcx> {
117     fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
118         write!(w, "{:?}", self.place)
119     }
120 }
121
122 #[derive(Debug)]
123 pub struct MoveData<'tcx> {
124     pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
125     pub moves: IndexVec<MoveOutIndex, MoveOut>,
126     /// Each Location `l` is mapped to the MoveOut's that are effects
127     /// of executing the code at `l`. (There can be multiple MoveOut's
128     /// for a given `l` because each MoveOut is associated with one
129     /// particular path being moved.)
130     pub loc_map: LocationMap<Vec<MoveOutIndex>>,
131     pub path_map: IndexVec<MovePathIndex, Vec<MoveOutIndex>>,
132     pub rev_lookup: MovePathLookup<'tcx>,
133     pub inits: IndexVec<InitIndex, Init>,
134     /// Each Location `l` is mapped to the Inits that are effects
135     /// of executing the code at `l`.
136     pub init_loc_map: LocationMap<Vec<InitIndex>>,
137     pub init_path_map: IndexVec<MovePathIndex, Vec<InitIndex>>,
138 }
139
140 pub trait HasMoveData<'tcx> {
141     fn move_data(&self) -> &MoveData<'tcx>;
142 }
143
144 #[derive(Debug)]
145 pub struct LocationMap<T> {
146     /// Location-indexed (BasicBlock for outer index, index within BB
147     /// for inner index) map.
148     pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
149 }
150
151 impl<T> Index<Location> for LocationMap<T> {
152     type Output = T;
153     fn index(&self, index: Location) -> &Self::Output {
154         &self.map[index.block][index.statement_index]
155     }
156 }
157
158 impl<T> IndexMut<Location> for LocationMap<T> {
159     fn index_mut(&mut self, index: Location) -> &mut Self::Output {
160         &mut self.map[index.block][index.statement_index]
161     }
162 }
163
164 impl<T> LocationMap<T> where T: Default + Clone {
165     fn new(mir: &Mir) -> Self {
166         LocationMap {
167             map: mir.basic_blocks().iter().map(|block| {
168                 vec![T::default(); block.statements.len()+1]
169             }).collect()
170         }
171     }
172 }
173
174 /// `MoveOut` represents a point in a program that moves out of some
175 /// L-value; i.e., "creates" uninitialized memory.
176 ///
177 /// With respect to dataflow analysis:
178 /// - Generated by moves and declaration of uninitialized variables.
179 /// - Killed by assignments to the memory.
180 #[derive(Copy, Clone)]
181 pub struct MoveOut {
182     /// path being moved
183     pub path: MovePathIndex,
184     /// location of move
185     pub source: Location,
186 }
187
188 impl fmt::Debug for MoveOut {
189     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
190         write!(fmt, "{:?}@{:?}", self.path, self.source)
191     }
192 }
193
194 /// `Init` represents a point in a program that initializes some L-value;
195 #[derive(Copy, Clone)]
196 pub struct Init {
197     /// path being initialized
198     pub path: MovePathIndex,
199     /// span of initialization
200     pub span: Span,
201     /// Extra information about this initialization
202     pub kind: InitKind,
203 }
204
205 /// Additional information about the initialization.
206 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
207 pub enum InitKind {
208     /// Deep init, even on panic
209     Deep,
210     /// Only does a shallow init
211     Shallow,
212     /// This doesn't initialize the variable on panic (and a panic is possible).
213     NonPanicPathOnly,
214 }
215
216 impl fmt::Debug for Init {
217     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
218         write!(fmt, "{:?}@{:?} ({:?})", self.path, self.span, self.kind)
219     }
220 }
221
222 /// Tables mapping from a place to its MovePathIndex.
223 #[derive(Debug)]
224 pub struct MovePathLookup<'tcx> {
225     locals: IndexVec<Local, MovePathIndex>,
226
227     /// projections are made from a base-place and a projection
228     /// elem. The base-place will have a unique MovePathIndex; we use
229     /// the latter as the index into the outer vector (narrowing
230     /// subsequent search so that it is solely relative to that
231     /// base-place). For the remaining lookup, we map the projection
232     /// elem to the associated MovePathIndex.
233     projections: FxHashMap<(MovePathIndex, AbstractElem<'tcx>), MovePathIndex>
234 }
235
236 mod builder;
237
238 #[derive(Copy, Clone, Debug)]
239 pub enum LookupResult {
240     Exact(MovePathIndex),
241     Parent(Option<MovePathIndex>)
242 }
243
244 impl<'tcx> MovePathLookup<'tcx> {
245     // Unlike the builder `fn move_path_for` below, this lookup
246     // alternative will *not* create a MovePath on the fly for an
247     // unknown place, but will rather return the nearest available
248     // parent.
249     pub fn find(&self, place: &Place<'tcx>) -> LookupResult {
250         match *place {
251             Place::Local(local) => LookupResult::Exact(self.locals[local]),
252             Place::Static(..) => LookupResult::Parent(None),
253             Place::Projection(ref proj) => {
254                 match self.find(&proj.base) {
255                     LookupResult::Exact(base_path) => {
256                         match self.projections.get(&(base_path, proj.elem.lift())) {
257                             Some(&subpath) => LookupResult::Exact(subpath),
258                             None => LookupResult::Parent(Some(base_path))
259                         }
260                     }
261                     inexact => inexact
262                 }
263             }
264         }
265     }
266
267     pub fn find_local(&self, local: Local) -> MovePathIndex {
268         self.locals[local]
269     }
270 }
271
272 #[derive(Debug)]
273 pub struct IllegalMoveOrigin<'tcx> {
274     pub(crate) location: Location,
275     pub(crate) kind: IllegalMoveOriginKind<'tcx>,
276 }
277
278 #[derive(Debug)]
279 pub(crate) enum IllegalMoveOriginKind<'tcx> {
280     /// Illegal move due to attempt to move from `static` variable.
281     Static,
282
283     /// Illegal move due to attempt to move from behind a reference.
284     BorrowedContent {
285         /// The content's type: if erroneous code was trying to move
286         /// from `*x` where `x: &T`, then this will be `T`.
287         target_ty: ty::Ty<'tcx>,
288     },
289
290     /// Illegal move due to attempt to move from field of an ADT that
291     /// implements `Drop`. Rust maintains invariant that all `Drop`
292     /// ADT's remain fully-initialized so that user-defined destructor
293     /// can safely read from all of the ADT's fields.
294     InteriorOfTypeWithDestructor { container_ty: ty::Ty<'tcx> },
295
296     /// Illegal move due to attempt to move out of a slice or array.
297     InteriorOfSliceOrArray { ty: ty::Ty<'tcx>, is_index: bool, },
298 }
299
300 #[derive(Debug)]
301 pub enum MoveError<'tcx> {
302     IllegalMove { cannot_move_out_of: IllegalMoveOrigin<'tcx> },
303     UnionMove { path: MovePathIndex },
304 }
305
306 impl<'tcx> MoveError<'tcx> {
307     fn cannot_move_out_of(location: Location, kind: IllegalMoveOriginKind<'tcx>) -> Self {
308         let origin = IllegalMoveOrigin { location, kind };
309         MoveError::IllegalMove { cannot_move_out_of: origin }
310     }
311 }
312
313 impl<'a, 'gcx, 'tcx> MoveData<'tcx> {
314     pub fn gather_moves(mir: &Mir<'tcx>, tcx: TyCtxt<'a, 'gcx, 'tcx>)
315                         -> Result<Self, (Self, Vec<MoveError<'tcx>>)> {
316         builder::gather_moves(mir, tcx)
317     }
318 }