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