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; 1]>>,
183 pub init_path_map: IndexVec<MovePathIndex, SmallVec<[InitIndex; 4]>>,
184}
185
186pub trait HasMoveData<'tcx> {
187 fn move_data(&self) -> &MoveData<'tcx>;
188}
189
190#[derive(Debug)]
191pub struct LocationMap<T> {
192 pub(crate) map: IndexVec<BasicBlock, Vec<T>>,
195}
196
197impl<T> Index<Location> for LocationMap<T> {
198 type Output = T;
199 fn index(&self, index: Location) -> &Self::Output {
200 &self.map[index.block][index.statement_index]
201 }
202}
203
204impl<T> IndexMut<Location> for LocationMap<T> {
205 fn index_mut(&mut self, index: Location) -> &mut Self::Output {
206 &mut self.map[index.block][index.statement_index]
207 }
208}
209
210impl<T> LocationMap<T>
211where
212 T: Default + Clone,
213{
214 fn new(body: &Body<'_>) -> Self {
215 LocationMap {
216 map: body
217 .basic_blocks
218 .iter()
219 .map(|block| vec![T::default(); block.statements.len() + 1])
220 .collect(),
221 }
222 }
223}
224
225#[derive(Copy, Clone)]
232pub struct MoveOut {
233 pub path: MovePathIndex,
235 pub source: Location,
237}
238
239impl fmt::Debug for MoveOut {
240 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
241 write!(fmt, "{:?}@{:?}", self.path, self.source)
242 }
243}
244
245#[derive(Copy, Clone)]
247pub struct Init {
248 pub path: MovePathIndex,
250 pub location: InitLocation,
252 pub kind: InitKind,
254}
255
256#[derive(Copy, Clone, Debug, PartialEq, Eq)]
259pub enum InitLocation {
260 Argument(Local),
261 Statement(Location),
262}
263
264#[derive(Copy, Clone, Debug, PartialEq, Eq)]
266pub enum InitKind {
267 Deep,
269 Shallow,
271 NonPanicPathOnly,
273}
274
275impl fmt::Debug for Init {
276 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
277 write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
278 }
279}
280
281impl Init {
282 pub fn span<'tcx>(&self, body: &Body<'tcx>) -> Span {
283 match self.location {
284 InitLocation::Argument(local) => body.local_decls[local].source_info.span,
285 InitLocation::Statement(location) => body.source_info(location).span,
286 }
287 }
288}
289
290#[derive(Debug)]
292pub struct MovePathLookup<'tcx> {
293 locals: IndexVec<Local, Option<MovePathIndex>>,
294
295 projections: FxHashMap<(MovePathIndex, MoveSubPath), MovePathIndex>,
302
303 un_derefer: UnDerefer<'tcx>,
304}
305
306mod builder;
307
308#[derive(Copy, Clone, Debug)]
309pub enum LookupResult {
310 Exact(MovePathIndex),
311 Parent(Option<MovePathIndex>),
312}
313
314impl<'tcx> MovePathLookup<'tcx> {
315 pub fn find(&self, place: PlaceRef<'tcx>) -> LookupResult {
320 let Some(mut result) = self.find_local(place.local) else {
321 return LookupResult::Parent(None);
322 };
323
324 for (_, elem) in self.un_derefer.iter_projections(place) {
325 let subpath = match MoveSubPath::of(elem.kind()) {
326 MoveSubPathResult::One(kind) => self.projections.get(&(result, kind)),
327 MoveSubPathResult::Subslice { .. } => None, MoveSubPathResult::Skip => continue,
329 MoveSubPathResult::Stop => None,
330 };
331
332 let Some(&subpath) = subpath else {
333 return LookupResult::Parent(Some(result));
334 };
335 result = subpath;
336 }
337
338 LookupResult::Exact(result)
339 }
340
341 #[inline]
342 pub fn find_local(&self, local: Local) -> Option<MovePathIndex> {
343 self.locals[local]
344 }
345
346 pub fn iter_locals_enumerated(
349 &self,
350 ) -> impl DoubleEndedIterator<Item = (Local, MovePathIndex)> {
351 self.locals.iter_enumerated().filter_map(|(l, &idx)| Some((l, idx?)))
352 }
353}
354
355impl<'tcx> MoveData<'tcx> {
356 pub fn gather_moves(
357 body: &Body<'tcx>,
358 tcx: TyCtxt<'tcx>,
359 filter: impl Fn(Ty<'tcx>) -> bool,
360 ) -> MoveData<'tcx> {
361 builder::gather_moves(body, tcx, filter)
362 }
363
364 pub fn base_local(&self, mut mpi: MovePathIndex) -> Local {
367 loop {
368 let path = &self.move_paths[mpi];
369 if let Some(l) = path.place.as_local() {
370 return l;
371 }
372 mpi = path.parent.expect("root move paths should be locals");
373 }
374 }
375
376 pub fn find_in_move_path_or_its_descendants(
377 &self,
378 root: MovePathIndex,
379 pred: impl Fn(MovePathIndex) -> bool,
380 ) -> Option<MovePathIndex> {
381 if pred(root) {
382 return Some(root);
383 }
384
385 self.move_paths[root].find_descendant(&self.move_paths, pred)
386 }
387}
388
389#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
391pub enum MoveSubPath {
392 Deref,
393 Field(FieldIdx),
394 ConstantIndex(u64),
395 Downcast(VariantIdx),
396 UnwrapUnsafeBinder,
397}
398
399#[derive(Copy, Clone, Debug, PartialEq, Eq)]
400pub enum MoveSubPathResult {
401 One(MoveSubPath),
402 Subslice { from: u64, to: u64 },
403 Skip,
404 Stop,
405}
406
407impl MoveSubPath {
408 pub fn of(elem: ProjectionKind) -> MoveSubPathResult {
409 let subpath = match elem {
410 ProjectionKind::Deref => MoveSubPath::Deref,
412 ProjectionKind::Field(idx, _) => MoveSubPath::Field(idx),
413 ProjectionKind::ConstantIndex { offset, min_length: _, from_end: false } => {
414 MoveSubPath::ConstantIndex(offset)
415 }
416 ProjectionKind::Downcast(_, idx) => MoveSubPath::Downcast(idx),
417 ProjectionKind::UnwrapUnsafeBinder(_) => MoveSubPath::UnwrapUnsafeBinder,
418
419 ProjectionKind::OpaqueCast(_) => {
423 return MoveSubPathResult::Skip;
424 }
425
426 ProjectionKind::Index(_)
428 | ProjectionKind::ConstantIndex { offset: _, min_length: _, from_end: true }
429 | ProjectionKind::Subslice { from: _, to: _, from_end: true } => {
430 return MoveSubPathResult::Stop;
431 }
432
433 ProjectionKind::Subslice { from, to, from_end: false } => {
436 return MoveSubPathResult::Subslice { from, to };
437 }
438 };
439
440 MoveSubPathResult::One(subpath)
441 }
442}