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