rustc_mir_dataflow/move_paths/
mod.rs1use std::fmt;
4use std::ops::{Index, IndexMut};
5
6use rustc_abi::{FieldIdx, VariantIdx};
7use rustc_data_structures::fx::FxHashMap;
8use rustc_index::{IndexSlice, IndexVec};
9use rustc_middle::mir::*;
10use rustc_middle::ty::{Ty, TyCtxt};
11use rustc_span::Span;
12use smallvec::SmallVec;
13
14use crate::un_derefer::UnDerefer;
15
16rustc_index::newtype_index! {
17 #[orderable]
18 #[debug_format = "mp{}"]
19 pub struct MovePathIndex {}
20}
21
22impl polonius_engine::Atom for MovePathIndex {
23 fn index(self) -> usize {
24 rustc_index::Idx::index(self)
25 }
26}
27
28rustc_index::newtype_index! {
29 #[orderable]
30 #[debug_format = "mo{}"]
31 pub struct MoveOutIndex {}
32}
33
34rustc_index::newtype_index! {
35 #[debug_format = "in{}"]
36 pub struct InitIndex {}
37}
38
39impl MoveOutIndex {
40 pub fn move_path_index(self, move_data: &MoveData<'_>) -> MovePathIndex {
41 move_data.moves[self].path
42 }
43}
44
45#[derive(Clone)]
58pub struct MovePath<'tcx> {
59 pub next_sibling: Option<MovePathIndex>,
60 pub first_child: Option<MovePathIndex>,
61 pub parent: Option<MovePathIndex>,
62 pub place: Place<'tcx>,
63}
64
65impl<'tcx> MovePath<'tcx> {
66 pub fn parents<'a>(
68 &self,
69 move_paths: &'a IndexSlice<MovePathIndex, MovePath<'tcx>>,
70 ) -> impl 'a + Iterator<Item = (MovePathIndex, &'a MovePath<'tcx>)> {
71 let first = self.parent.map(|mpi| (mpi, &move_paths[mpi]));
72 MovePathLinearIter {
73 next: first,
74 fetch_next: move |_, parent: &MovePath<'_>| {
75 parent.parent.map(|mpi| (mpi, &move_paths[mpi]))
76 },
77 }
78 }
79
80 pub fn children<'a>(
82 &self,
83 move_paths: &'a IndexSlice<MovePathIndex, MovePath<'tcx>>,
84 ) -> impl 'a + Iterator<Item = (MovePathIndex, &'a MovePath<'tcx>)> {
85 let first = self.first_child.map(|mpi| (mpi, &move_paths[mpi]));
86 MovePathLinearIter {
87 next: first,
88 fetch_next: move |_, child: &MovePath<'_>| {
89 child.next_sibling.map(|mpi| (mpi, &move_paths[mpi]))
90 },
91 }
92 }
93
94 pub fn find_descendant(
99 &self,
100 move_paths: &IndexSlice<MovePathIndex, MovePath<'_>>,
101 f: impl Fn(MovePathIndex) -> bool,
102 ) -> Option<MovePathIndex> {
103 let Some(child) = self.first_child else { return None };
104 let mut todo = vec![child];
105
106 while let Some(mpi) = todo.pop() {
107 if f(mpi) {
108 return Some(mpi);
109 }
110
111 let move_path = &move_paths[mpi];
112 if let Some(child) = move_path.first_child {
113 todo.push(child);
114 }
115
116 if let Some(sibling) = move_path.next_sibling {
119 todo.push(sibling);
120 }
121 }
122
123 None
124 }
125}
126
127impl<'tcx> fmt::Debug for MovePath<'tcx> {
128 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
129 write!(w, "MovePath {{")?;
130 if let Some(parent) = self.parent {
131 write!(w, " parent: {parent:?},")?;
132 }
133 if let Some(first_child) = self.first_child {
134 write!(w, " first_child: {first_child:?},")?;
135 }
136 if let Some(next_sibling) = self.next_sibling {
137 write!(w, " next_sibling: {next_sibling:?}")?;
138 }
139 write!(w, " place: {:?} }}", self.place)
140 }
141}
142
143impl<'tcx> fmt::Display for MovePath<'tcx> {
144 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
145 write!(w, "{:?}", self.place)
146 }
147}
148
149struct MovePathLinearIter<'a, 'tcx, F> {
150 next: Option<(MovePathIndex, &'a MovePath<'tcx>)>,
151 fetch_next: F,
152}
153
154impl<'a, 'tcx, F> Iterator for MovePathLinearIter<'a, 'tcx, F>
155where
156 F: FnMut(MovePathIndex, &'a MovePath<'tcx>) -> Option<(MovePathIndex, &'a MovePath<'tcx>)>,
157{
158 type Item = (MovePathIndex, &'a MovePath<'tcx>);
159
160 fn next(&mut self) -> Option<Self::Item> {
161 let ret = self.next.take()?;
162 self.next = (self.fetch_next)(ret.0, ret.1);
163 Some(ret)
164 }
165}
166
167#[derive(Debug)]
168pub struct MoveData<'tcx> {
169 pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
170 pub moves: IndexVec<MoveOutIndex, MoveOut>,
171 pub loc_map: LocationMap<SmallVec<[MoveOutIndex; 4]>>,
176 pub path_map: IndexVec<MovePathIndex, SmallVec<[MoveOutIndex; 4]>>,
177 pub rev_lookup: MovePathLookup<'tcx>,
178 pub inits: IndexVec<InitIndex, Init>,
179 pub init_loc_map: LocationMap<SmallVec<[InitIndex; 4]>>,
182 pub init_path_map: IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
183}
184
185pub trait HasMoveData<'tcx> {
186 fn move_data(&self) -> &MoveData<'tcx>;
187}
188
189#[derive(Debug)]
190pub struct LocationMap<T> {
191 pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
194}
195
196impl<T> Index<Location> for LocationMap<T> {
197 type Output = T;
198 fn index(&self, index: Location) -> &Self::Output {
199 &self.map[index.block][index.statement_index]
200 }
201}
202
203impl<T> IndexMut<Location> for LocationMap<T> {
204 fn index_mut(&mut self, index: Location) -> &mut Self::Output {
205 &mut self.map[index.block][index.statement_index]
206 }
207}
208
209impl<T> LocationMap<T>
210where
211 T: Default + Clone,
212{
213 fn new(body: &Body<'_>) -> Self {
214 LocationMap {
215 map: body
216 .basic_blocks
217 .iter()
218 .map(|block| vec![T::default(); block.statements.len() + 1])
219 .collect(),
220 }
221 }
222}
223
224#[derive(Copy, Clone)]
231pub struct MoveOut {
232 pub path: MovePathIndex,
234 pub source: Location,
236}
237
238impl fmt::Debug for MoveOut {
239 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
240 write!(fmt, "{:?}@{:?}", self.path, self.source)
241 }
242}
243
244#[derive(Copy, Clone)]
246pub struct Init {
247 pub path: MovePathIndex,
249 pub location: InitLocation,
251 pub kind: InitKind,
253}
254
255#[derive(Copy, Clone, Debug, PartialEq, Eq)]
258pub enum InitLocation {
259 Argument(Local),
260 Statement(Location),
261}
262
263#[derive(Copy, Clone, Debug, PartialEq, Eq)]
265pub enum InitKind {
266 Deep,
268 Shallow,
270 NonPanicPathOnly,
272}
273
274impl fmt::Debug for Init {
275 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
276 write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
277 }
278}
279
280impl Init {
281 pub fn span<'tcx>(&self, body: &Body<'tcx>) -> Span {
282 match self.location {
283 InitLocation::Argument(local) => body.local_decls[local].source_info.span,
284 InitLocation::Statement(location) => body.source_info(location).span,
285 }
286 }
287}
288
289#[derive(Debug)]
291pub struct MovePathLookup<'tcx> {
292 locals: IndexVec<Local, Option<MovePathIndex>>,
293
294 projections: FxHashMap<(MovePathIndex, MoveSubPath), MovePathIndex>,
301
302 un_derefer: UnDerefer<'tcx>,
303}
304
305mod builder;
306
307#[derive(Copy, Clone, Debug)]
308pub enum LookupResult {
309 Exact(MovePathIndex),
310 Parent(Option<MovePathIndex>),
311}
312
313impl<'tcx> MovePathLookup<'tcx> {
314 pub fn find(&self, place: PlaceRef<'tcx>) -> LookupResult {
319 let Some(mut result) = self.find_local(place.local) else {
320 return LookupResult::Parent(None);
321 };
322
323 for (_, elem) in self.un_derefer.iter_projections(place) {
324 let subpath = match MoveSubPath::of(elem.kind()) {
325 MoveSubPathResult::One(kind) => self.projections.get(&(result, kind)),
326 MoveSubPathResult::Subslice { .. } => None, MoveSubPathResult::Skip => continue,
328 MoveSubPathResult::Stop => None,
329 };
330
331 let Some(&subpath) = subpath else {
332 return LookupResult::Parent(Some(result));
333 };
334 result = subpath;
335 }
336
337 LookupResult::Exact(result)
338 }
339
340 #[inline]
341 pub fn find_local(&self, local: Local) -> Option<MovePathIndex> {
342 self.locals[local]
343 }
344
345 pub fn iter_locals_enumerated(
348 &self,
349 ) -> impl DoubleEndedIterator<Item = (Local, MovePathIndex)> {
350 self.locals.iter_enumerated().filter_map(|(l, &idx)| Some((l, idx?)))
351 }
352}
353
354impl<'tcx> MoveData<'tcx> {
355 pub fn gather_moves(
356 body: &Body<'tcx>,
357 tcx: TyCtxt<'tcx>,
358 filter: impl Fn(Ty<'tcx>) -> bool,
359 ) -> MoveData<'tcx> {
360 builder::gather_moves(body, tcx, filter)
361 }
362
363 pub fn base_local(&self, mut mpi: MovePathIndex) -> Local {
366 loop {
367 let path = &self.move_paths[mpi];
368 if let Some(l) = path.place.as_local() {
369 return l;
370 }
371 mpi = path.parent.expect("root move paths should be locals");
372 }
373 }
374
375 pub fn find_in_move_path_or_its_descendants(
376 &self,
377 root: MovePathIndex,
378 pred: impl Fn(MovePathIndex) -> bool,
379 ) -> Option<MovePathIndex> {
380 if pred(root) {
381 return Some(root);
382 }
383
384 self.move_paths[root].find_descendant(&self.move_paths, pred)
385 }
386}
387
388#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
390pub enum MoveSubPath {
391 Deref,
392 Field(FieldIdx),
393 ConstantIndex(u64),
394 Downcast(VariantIdx),
395 UnwrapUnsafeBinder,
396}
397
398#[derive(Copy, Clone, Debug, PartialEq, Eq)]
399pub enum MoveSubPathResult {
400 One(MoveSubPath),
401 Subslice { from: u64, to: u64 },
402 Skip,
403 Stop,
404}
405
406impl MoveSubPath {
407 pub fn of(elem: ProjectionKind) -> MoveSubPathResult {
408 let subpath = match elem {
409 ProjectionKind::Deref => MoveSubPath::Deref,
411 ProjectionKind::Field(idx, _) => MoveSubPath::Field(idx),
412 ProjectionKind::ConstantIndex { offset, min_length: _, from_end: false } => {
413 MoveSubPath::ConstantIndex(offset)
414 }
415 ProjectionKind::Downcast(_, idx) => MoveSubPath::Downcast(idx),
416 ProjectionKind::UnwrapUnsafeBinder(_) => MoveSubPath::UnwrapUnsafeBinder,
417
418 ProjectionKind::OpaqueCast(_) => {
422 return MoveSubPathResult::Skip;
423 }
424
425 ProjectionKind::Index(_)
427 | ProjectionKind::ConstantIndex { offset: _, min_length: _, from_end: true }
428 | ProjectionKind::Subslice { from: _, to: _, from_end: true } => {
429 return MoveSubPathResult::Stop;
430 }
431
432 ProjectionKind::Subslice { from, to, from_end: false } => {
435 return MoveSubPathResult::Subslice { from, to };
436 }
437 };
438
439 MoveSubPathResult::One(subpath)
440 }
441}