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 mut todo = if let Some(child) = self.first_child {
104 vec![child]
105 } else {
106 return None;
107 };
108
109 while let Some(mpi) = todo.pop() {
110 if f(mpi) {
111 return Some(mpi);
112 }
113
114 let move_path = &move_paths[mpi];
115 if let Some(child) = move_path.first_child {
116 todo.push(child);
117 }
118
119 if let Some(sibling) = move_path.next_sibling {
122 todo.push(sibling);
123 }
124 }
125
126 None
127 }
128}
129
130impl<'tcx> fmt::Debug for MovePath<'tcx> {
131 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
132 write!(w, "MovePath {{")?;
133 if let Some(parent) = self.parent {
134 write!(w, " parent: {parent:?},")?;
135 }
136 if let Some(first_child) = self.first_child {
137 write!(w, " first_child: {first_child:?},")?;
138 }
139 if let Some(next_sibling) = self.next_sibling {
140 write!(w, " next_sibling: {next_sibling:?}")?;
141 }
142 write!(w, " place: {:?} }}", self.place)
143 }
144}
145
146impl<'tcx> fmt::Display for MovePath<'tcx> {
147 fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
148 write!(w, "{:?}", self.place)
149 }
150}
151
152struct MovePathLinearIter<'a, 'tcx, F> {
153 next: Option<(MovePathIndex, &'a MovePath<'tcx>)>,
154 fetch_next: F,
155}
156
157impl<'a, 'tcx, F> Iterator for MovePathLinearIter<'a, 'tcx, F>
158where
159 F: FnMut(MovePathIndex, &'a MovePath<'tcx>) -> Option<(MovePathIndex, &'a MovePath<'tcx>)>,
160{
161 type Item = (MovePathIndex, &'a MovePath<'tcx>);
162
163 fn next(&mut self) -> Option<Self::Item> {
164 let ret = self.next.take()?;
165 self.next = (self.fetch_next)(ret.0, ret.1);
166 Some(ret)
167 }
168}
169
170#[derive(Debug)]
171pub struct MoveData<'tcx> {
172 pub move_paths: IndexVec<MovePathIndex, MovePath<'tcx>>,
173 pub moves: IndexVec<MoveOutIndex, MoveOut>,
174 pub loc_map: LocationMap<SmallVec<[MoveOutIndex; 4]>>,
179 pub path_map: IndexVec<MovePathIndex, SmallVec<[MoveOutIndex; 4]>>,
180 pub rev_lookup: MovePathLookup<'tcx>,
181 pub inits: IndexVec<InitIndex, Init>,
182 pub init_loc_map: LocationMap<SmallVec<[InitIndex; 4]>>,
185 pub init_path_map: IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
186}
187
188pub trait HasMoveData<'tcx> {
189 fn move_data(&self) -> &MoveData<'tcx>;
190}
191
192#[derive(Debug)]
193pub struct LocationMap<T> {
194 pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
197}
198
199impl<T> Index<Location> for LocationMap<T> {
200 type Output = T;
201 fn index(&self, index: Location) -> &Self::Output {
202 &self.map[index.block][index.statement_index]
203 }
204}
205
206impl<T> IndexMut<Location> for LocationMap<T> {
207 fn index_mut(&mut self, index: Location) -> &mut Self::Output {
208 &mut self.map[index.block][index.statement_index]
209 }
210}
211
212impl<T> LocationMap<T>
213where
214 T: Default + Clone,
215{
216 fn new(body: &Body<'_>) -> Self {
217 LocationMap {
218 map: body
219 .basic_blocks
220 .iter()
221 .map(|block| vec![T::default(); block.statements.len() + 1])
222 .collect(),
223 }
224 }
225}
226
227#[derive(Copy, Clone)]
234pub struct MoveOut {
235 pub path: MovePathIndex,
237 pub source: Location,
239}
240
241impl fmt::Debug for MoveOut {
242 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
243 write!(fmt, "{:?}@{:?}", self.path, self.source)
244 }
245}
246
247#[derive(Copy, Clone)]
249pub struct Init {
250 pub path: MovePathIndex,
252 pub location: InitLocation,
254 pub kind: InitKind,
256}
257
258#[derive(Copy, Clone, Debug, PartialEq, Eq)]
261pub enum InitLocation {
262 Argument(Local),
263 Statement(Location),
264}
265
266#[derive(Copy, Clone, Debug, PartialEq, Eq)]
268pub enum InitKind {
269 Deep,
271 Shallow,
273 NonPanicPathOnly,
275}
276
277impl fmt::Debug for Init {
278 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
279 write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
280 }
281}
282
283impl Init {
284 pub fn span<'tcx>(&self, body: &Body<'tcx>) -> Span {
285 match self.location {
286 InitLocation::Argument(local) => body.local_decls[local].source_info.span,
287 InitLocation::Statement(location) => body.source_info(location).span,
288 }
289 }
290}
291
292#[derive(Debug)]
294pub struct MovePathLookup<'tcx> {
295 locals: IndexVec<Local, Option<MovePathIndex>>,
296
297 projections: FxHashMap<(MovePathIndex, MoveSubPath), MovePathIndex>,
304
305 un_derefer: UnDerefer<'tcx>,
306}
307
308mod builder;
309
310#[derive(Copy, Clone, Debug)]
311pub enum LookupResult {
312 Exact(MovePathIndex),
313 Parent(Option<MovePathIndex>),
314}
315
316impl<'tcx> MovePathLookup<'tcx> {
317 pub fn find(&self, place: PlaceRef<'tcx>) -> LookupResult {
322 let Some(mut result) = self.find_local(place.local) else {
323 return LookupResult::Parent(None);
324 };
325
326 for (_, elem) in self.un_derefer.iter_projections(place) {
327 let subpath = match MoveSubPath::of(elem.kind()) {
328 MoveSubPathResult::One(kind) => self.projections.get(&(result, kind)),
329 MoveSubPathResult::Subslice { .. } => None, MoveSubPathResult::Skip => continue,
331 MoveSubPathResult::Stop => None,
332 };
333
334 if let Some(&subpath) = subpath {
335 result = subpath;
336 } else {
337 return LookupResult::Parent(Some(result));
338 }
339 }
340
341 LookupResult::Exact(result)
342 }
343
344 #[inline]
345 pub fn find_local(&self, local: Local) -> Option<MovePathIndex> {
346 self.locals[local]
347 }
348
349 pub fn iter_locals_enumerated(
352 &self,
353 ) -> impl DoubleEndedIterator<Item = (Local, MovePathIndex)> {
354 self.locals.iter_enumerated().filter_map(|(l, &idx)| Some((l, idx?)))
355 }
356}
357
358impl<'tcx> MoveData<'tcx> {
359 pub fn gather_moves(
360 body: &Body<'tcx>,
361 tcx: TyCtxt<'tcx>,
362 filter: impl Fn(Ty<'tcx>) -> bool,
363 ) -> MoveData<'tcx> {
364 builder::gather_moves(body, tcx, filter)
365 }
366
367 pub fn base_local(&self, mut mpi: MovePathIndex) -> Local {
370 loop {
371 let path = &self.move_paths[mpi];
372 if let Some(l) = path.place.as_local() {
373 return l;
374 }
375 mpi = path.parent.expect("root move paths should be locals");
376 }
377 }
378
379 pub fn find_in_move_path_or_its_descendants(
380 &self,
381 root: MovePathIndex,
382 pred: impl Fn(MovePathIndex) -> bool,
383 ) -> Option<MovePathIndex> {
384 if pred(root) {
385 return Some(root);
386 }
387
388 self.move_paths[root].find_descendant(&self.move_paths, pred)
389 }
390}
391
392#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
394pub enum MoveSubPath {
395 Deref,
396 Field(FieldIdx),
397 ConstantIndex(u64),
398 Downcast(VariantIdx),
399 UnwrapUnsafeBinder,
400}
401
402#[derive(Copy, Clone, Debug, PartialEq, Eq)]
403pub enum MoveSubPathResult {
404 One(MoveSubPath),
405 Subslice { from: u64, to: u64 },
406 Skip,
407 Stop,
408}
409
410impl MoveSubPath {
411 pub fn of(elem: ProjectionKind) -> MoveSubPathResult {
412 let subpath = match elem {
413 ProjectionKind::Deref => MoveSubPath::Deref,
415 ProjectionKind::Field(idx, _) => MoveSubPath::Field(idx),
416 ProjectionKind::ConstantIndex { offset, min_length: _, from_end: false } => {
417 MoveSubPath::ConstantIndex(offset)
418 }
419 ProjectionKind::Downcast(_, idx) => MoveSubPath::Downcast(idx),
420 ProjectionKind::UnwrapUnsafeBinder(_) => MoveSubPath::UnwrapUnsafeBinder,
421
422 ProjectionKind::OpaqueCast(_) => {
426 return MoveSubPathResult::Skip;
427 }
428
429 ProjectionKind::Index(_)
431 | ProjectionKind::ConstantIndex { offset: _, min_length: _, from_end: true }
432 | ProjectionKind::Subslice { from: _, to: _, from_end: true } => {
433 return MoveSubPathResult::Stop;
434 }
435
436 ProjectionKind::Subslice { from, to, from_end: false } => {
439 return MoveSubPathResult::Subslice { from, to };
440 }
441 };
442
443 MoveSubPathResult::One(subpath)
444 }
445}