1use std::fmt::{Debug, Formatter};
2use std::ops::Range;
3
4use rustc_abi::{FieldIdx, VariantIdx};
5use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry};
6use rustc_data_structures::stack::ensure_sufficient_stack;
7use rustc_index::IndexVec;
8use rustc_index::bit_set::DenseBitSet;
9use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
10use rustc_middle::mir::*;
11use rustc_middle::ty::{self, Ty, TyCtxt};
12use tracing::debug;
13
14use crate::JoinSemiLattice;
15use crate::lattice::{HasBottom, HasTop};
16
17rustc_index::newtype_index!(
18 pub struct PlaceIndex {}
23);
24
25rustc_index::newtype_index!(
26 struct ValueIndex {}
30);
31
32#[derive(PartialEq, Eq, Debug)]
34pub struct StateData<V> {
35 bottom: V,
36 map: FxHashMap<ValueIndex, V>,
38}
39
40impl<V: HasBottom> StateData<V> {
41 fn new() -> StateData<V> {
42 StateData { bottom: V::BOTTOM, map: FxHashMap::default() }
43 }
44
45 fn get(&self, idx: ValueIndex) -> &V {
46 self.map.get(&idx).unwrap_or(&self.bottom)
47 }
48
49 fn insert(&mut self, idx: ValueIndex, elem: V) {
50 if elem.is_bottom() {
51 self.map.remove(&idx);
52 } else {
53 self.map.insert(idx, elem);
54 }
55 }
56}
57
58impl<V: Clone> Clone for StateData<V> {
59 fn clone(&self) -> Self {
60 StateData { bottom: self.bottom.clone(), map: self.map.clone() }
61 }
62
63 fn clone_from(&mut self, source: &Self) {
64 self.map.clone_from(&source.map)
65 }
66}
67
68impl<V: JoinSemiLattice + Clone> JoinSemiLattice for StateData<V> {
69 fn join(&mut self, other: &Self) -> bool {
70 let mut changed = false;
71 #[allow(rustc::potential_query_instability)]
72 for (i, v) in other.map.iter() {
73 match self.map.entry(*i) {
74 StdEntry::Vacant(e) => {
75 e.insert(v.clone());
76 changed = true
77 }
78 StdEntry::Occupied(e) => changed |= e.into_mut().join(v),
79 }
80 }
81 changed
82 }
83}
84
85#[derive(PartialEq, Eq, Debug)]
96pub enum State<V> {
97 Unreachable,
98 Reachable(StateData<V>),
99}
100
101impl<V: Clone> Clone for State<V> {
102 fn clone(&self) -> Self {
103 match self {
104 Self::Reachable(x) => Self::Reachable(x.clone()),
105 Self::Unreachable => Self::Unreachable,
106 }
107 }
108
109 fn clone_from(&mut self, source: &Self) {
110 match (&mut *self, source) {
111 (Self::Reachable(x), Self::Reachable(y)) => {
112 x.clone_from(&y);
113 }
114 _ => *self = source.clone(),
115 }
116 }
117}
118
119impl<V: Clone + HasBottom> State<V> {
120 pub fn new_reachable() -> State<V> {
121 State::Reachable(StateData::new())
122 }
123
124 pub fn all_bottom(&self) -> bool {
125 match self {
126 State::Unreachable => false,
127 State::Reachable(values) =>
128 {
129 #[allow(rustc::potential_query_instability)]
130 values.map.values().all(V::is_bottom)
131 }
132 }
133 }
134
135 pub fn is_reachable(&self) -> bool {
136 matches!(self, State::Reachable(_))
137 }
138
139 pub fn flood_with(&mut self, place: PlaceRef<'_>, map: &Map<'_>, value: V) {
141 self.flood_with_tail_elem(place, None, map, value)
142 }
143
144 pub fn flood(&mut self, place: PlaceRef<'_>, map: &Map<'_>)
146 where
147 V: HasTop,
148 {
149 self.flood_with(place, map, V::TOP)
150 }
151
152 fn flood_discr_with(&mut self, place: PlaceRef<'_>, map: &Map<'_>, value: V) {
154 self.flood_with_tail_elem(place, Some(TrackElem::Discriminant), map, value)
155 }
156
157 pub fn flood_discr(&mut self, place: PlaceRef<'_>, map: &Map<'_>)
159 where
160 V: HasTop,
161 {
162 self.flood_discr_with(place, map, V::TOP)
163 }
164
165 pub fn flood_with_tail_elem(
173 &mut self,
174 place: PlaceRef<'_>,
175 tail_elem: Option<TrackElem>,
176 map: &Map<'_>,
177 value: V,
178 ) {
179 let State::Reachable(values) = self else { return };
180 map.for_each_aliasing_place(place, tail_elem, &mut |vi| values.insert(vi, value.clone()));
181 }
182
183 fn insert_idx(&mut self, target: PlaceIndex, result: ValueOrPlace<V>, map: &Map<'_>) {
188 match result {
189 ValueOrPlace::Value(value) => self.insert_value_idx(target, value, map),
190 ValueOrPlace::Place(source) => self.insert_place_idx(target, source, map),
191 }
192 }
193
194 pub fn insert_value_idx(&mut self, target: PlaceIndex, value: V, map: &Map<'_>) {
199 let State::Reachable(values) = self else { return };
200 if let Some(value_index) = map.places[target].value_index {
201 values.insert(value_index, value)
202 }
203 }
204
205 pub fn insert_place_idx(&mut self, target: PlaceIndex, source: PlaceIndex, map: &Map<'_>) {
213 let State::Reachable(values) = self else { return };
214
215 if let Some(target_value) = map.places[target].value_index {
219 if let Some(source_value) = map.places[source].value_index {
220 values.insert(target_value, values.get(source_value).clone());
221 }
222 }
223 for target_child in map.children(target) {
224 let projection = map.places[target_child].proj_elem.unwrap();
226 if let Some(source_child) = map.projections.get(&(source, projection)) {
227 self.insert_place_idx(target_child, *source_child, map);
228 }
229 }
230 }
231
232 pub fn assign(&mut self, target: PlaceRef<'_>, result: ValueOrPlace<V>, map: &Map<'_>)
234 where
235 V: HasTop,
236 {
237 self.flood(target, map);
238 if let Some(target) = map.find(target) {
239 self.insert_idx(target, result, map);
240 }
241 }
242
243 pub fn assign_discr(&mut self, target: PlaceRef<'_>, result: ValueOrPlace<V>, map: &Map<'_>)
245 where
246 V: HasTop,
247 {
248 self.flood_discr(target, map);
249 if let Some(target) = map.find_discr(target) {
250 self.insert_idx(target, result, map);
251 }
252 }
253
254 pub fn try_get(&self, place: PlaceRef<'_>, map: &Map<'_>) -> Option<V> {
256 let place = map.find(place)?;
257 self.try_get_idx(place, map)
258 }
259
260 pub fn try_get_discr(&self, place: PlaceRef<'_>, map: &Map<'_>) -> Option<V> {
262 let place = map.find_discr(place)?;
263 self.try_get_idx(place, map)
264 }
265
266 pub fn try_get_len(&self, place: PlaceRef<'_>, map: &Map<'_>) -> Option<V> {
268 let place = map.find_len(place)?;
269 self.try_get_idx(place, map)
270 }
271
272 pub fn try_get_idx(&self, place: PlaceIndex, map: &Map<'_>) -> Option<V> {
274 match self {
275 State::Reachable(values) => {
276 map.places[place].value_index.map(|v| values.get(v).clone())
277 }
278 State::Unreachable => None,
279 }
280 }
281
282 pub fn get(&self, place: PlaceRef<'_>, map: &Map<'_>) -> V
286 where
287 V: HasBottom + HasTop,
288 {
289 match self {
290 State::Reachable(_) => self.try_get(place, map).unwrap_or(V::TOP),
291 State::Unreachable => V::BOTTOM,
293 }
294 }
295
296 pub fn get_discr(&self, place: PlaceRef<'_>, map: &Map<'_>) -> V
300 where
301 V: HasBottom + HasTop,
302 {
303 match self {
304 State::Reachable(_) => self.try_get_discr(place, map).unwrap_or(V::TOP),
305 State::Unreachable => V::BOTTOM,
307 }
308 }
309
310 pub fn get_len(&self, place: PlaceRef<'_>, map: &Map<'_>) -> V
314 where
315 V: HasBottom + HasTop,
316 {
317 match self {
318 State::Reachable(_) => self.try_get_len(place, map).unwrap_or(V::TOP),
319 State::Unreachable => V::BOTTOM,
321 }
322 }
323
324 pub fn get_idx(&self, place: PlaceIndex, map: &Map<'_>) -> V
328 where
329 V: HasBottom + HasTop,
330 {
331 match self {
332 State::Reachable(values) => {
333 map.places[place].value_index.map(|v| values.get(v).clone()).unwrap_or(V::TOP)
334 }
335 State::Unreachable => {
336 V::BOTTOM
338 }
339 }
340 }
341}
342
343impl<V: JoinSemiLattice + Clone> JoinSemiLattice for State<V> {
344 fn join(&mut self, other: &Self) -> bool {
345 match (&mut *self, other) {
346 (_, State::Unreachable) => false,
347 (State::Unreachable, _) => {
348 *self = other.clone();
349 true
350 }
351 (State::Reachable(this), State::Reachable(other)) => this.join(other),
352 }
353 }
354}
355
356#[derive(Debug)]
363pub struct Map<'tcx> {
364 locals: IndexVec<Local, Option<PlaceIndex>>,
365 projections: FxHashMap<(PlaceIndex, TrackElem), PlaceIndex>,
366 places: IndexVec<PlaceIndex, PlaceInfo<'tcx>>,
367 value_count: usize,
368 inner_values: IndexVec<PlaceIndex, Range<usize>>,
370 inner_values_buffer: Vec<ValueIndex>,
371}
372
373impl<'tcx> Map<'tcx> {
374 pub fn new(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, value_limit: Option<usize>) -> Self {
380 let mut map = Self {
381 locals: IndexVec::from_elem(None, &body.local_decls),
382 projections: FxHashMap::default(),
383 places: IndexVec::new(),
384 value_count: 0,
385 inner_values: IndexVec::new(),
386 inner_values_buffer: Vec::new(),
387 };
388 let exclude = excluded_locals(body);
389 map.register(tcx, body, exclude, value_limit);
390 debug!("registered {} places ({} nodes in total)", map.value_count, map.places.len());
391 map
392 }
393
394 #[tracing::instrument(level = "trace", skip(self, tcx, body))]
396 fn register(
397 &mut self,
398 tcx: TyCtxt<'tcx>,
399 body: &Body<'tcx>,
400 exclude: DenseBitSet<Local>,
401 value_limit: Option<usize>,
402 ) {
403 for (local, decl) in body.local_decls.iter_enumerated() {
405 if exclude.contains(local) {
406 continue;
407 }
408
409 debug_assert!(self.locals[local].is_none());
411 let place = self.places.push(PlaceInfo::new(decl.ty, None));
412 self.locals[local] = Some(place);
413 }
414
415 let mut collector =
417 PlaceCollector { tcx, body, map: self, assignments: Default::default() };
418 collector.visit_body(body);
419 let PlaceCollector { mut assignments, .. } = collector;
420
421 let mut num_places = 0;
433 while num_places < self.places.len() {
434 num_places = self.places.len();
435
436 for assign in 0.. {
437 let Some(&(lhs, rhs)) = assignments.get_index(assign) else { break };
438
439 let mut child = self.places[lhs].first_child;
441 while let Some(lhs_child) = child {
442 let PlaceInfo { ty, proj_elem, next_sibling, .. } = self.places[lhs_child];
443 let rhs_child =
444 self.register_place(ty, rhs, proj_elem.expect("child is not a projection"));
445 assignments.insert((lhs_child, rhs_child));
446 child = next_sibling;
447 }
448
449 let mut child = self.places[rhs].first_child;
451 while let Some(rhs_child) = child {
452 let PlaceInfo { ty, proj_elem, next_sibling, .. } = self.places[rhs_child];
453 let lhs_child =
454 self.register_place(ty, lhs, proj_elem.expect("child is not a projection"));
455 assignments.insert((lhs_child, rhs_child));
456 child = next_sibling;
457 }
458 }
459 }
460 drop(assignments);
461
462 let typing_env = body.typing_env(tcx);
464 for place_info in self.places.iter_mut() {
465 if let Some(value_limit) = value_limit
467 && self.value_count >= value_limit
468 {
469 break;
470 }
471
472 if let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, place_info.ty) {
473 place_info.ty = ty;
474 }
475
476 assert!(place_info.value_index.is_none());
478 if let Ok(layout) = tcx.layout_of(typing_env.as_query_input(place_info.ty))
479 && layout.backend_repr.is_scalar()
480 {
481 place_info.value_index = Some(self.value_count.into());
482 self.value_count += 1;
483 }
484 }
485
486 self.inner_values_buffer = Vec::with_capacity(self.value_count);
490 self.inner_values = IndexVec::from_elem(0..0, &self.places);
491 for local in body.local_decls.indices() {
492 if let Some(place) = self.locals[local] {
493 self.cache_preorder_invoke(place);
494 }
495 }
496
497 for opt_place in self.locals.iter_mut() {
499 if let Some(place) = *opt_place
500 && self.inner_values[place].is_empty()
501 {
502 *opt_place = None;
503 }
504 }
505 #[allow(rustc::potential_query_instability)]
506 self.projections.retain(|_, child| !self.inner_values[*child].is_empty());
507 }
508
509 #[tracing::instrument(level = "trace", skip(self), ret)]
510 fn register_place(&mut self, ty: Ty<'tcx>, base: PlaceIndex, elem: TrackElem) -> PlaceIndex {
511 *self.projections.entry((base, elem)).or_insert_with(|| {
512 let next = self.places.push(PlaceInfo::new(ty, Some(elem)));
513 self.places[next].next_sibling = self.places[base].first_child;
514 self.places[base].first_child = Some(next);
515 next
516 })
517 }
518
519 fn cache_preorder_invoke(&mut self, root: PlaceIndex) {
522 let start = self.inner_values_buffer.len();
523 if let Some(vi) = self.places[root].value_index {
524 self.inner_values_buffer.push(vi);
525 }
526
527 let mut next_child = self.places[root].first_child;
529 while let Some(child) = next_child {
530 ensure_sufficient_stack(|| self.cache_preorder_invoke(child));
531 next_child = self.places[child].next_sibling;
532 }
533
534 let end = self.inner_values_buffer.len();
535 self.inner_values[root] = start..end;
536 }
537}
538
539struct PlaceCollector<'a, 'tcx> {
540 tcx: TyCtxt<'tcx>,
541 body: &'a Body<'tcx>,
542 map: &'a mut Map<'tcx>,
543 assignments: FxIndexSet<(PlaceIndex, PlaceIndex)>,
544}
545
546impl<'tcx> PlaceCollector<'_, 'tcx> {
547 #[tracing::instrument(level = "trace", skip(self))]
548 fn register_place(&mut self, place: Place<'tcx>) -> Option<PlaceIndex> {
549 let mut place_index = self.map.locals[place.local]?;
551 let mut ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
552 tracing::trace!(?place_index, ?ty);
553
554 if let ty::Ref(_, ref_ty, _) | ty::RawPtr(ref_ty, _) = ty.ty.kind()
555 && let ty::Slice(..) = ref_ty.kind()
556 {
557 self.map.register_place(self.tcx.types.usize, place_index, TrackElem::DerefLen);
558 } else if ty.ty.is_enum() {
559 let discriminant_ty = ty.ty.discriminant_ty(self.tcx);
560 self.map.register_place(discriminant_ty, place_index, TrackElem::Discriminant);
561 }
562
563 for proj in place.projection {
564 let track_elem = proj.try_into().ok()?;
565 ty = ty.projection_ty(self.tcx, proj);
566 place_index = self.map.register_place(ty.ty, place_index, track_elem);
567 tracing::trace!(?proj, ?place_index, ?ty);
568
569 if let ty::Ref(_, ref_ty, _) | ty::RawPtr(ref_ty, _) = ty.ty.kind()
570 && let ty::Slice(..) = ref_ty.kind()
571 {
572 self.map.register_place(self.tcx.types.usize, place_index, TrackElem::DerefLen);
573 } else if ty.ty.is_enum() {
574 let discriminant_ty = ty.ty.discriminant_ty(self.tcx);
575 self.map.register_place(discriminant_ty, place_index, TrackElem::Discriminant);
576 }
577 }
578
579 Some(place_index)
580 }
581}
582
583impl<'tcx> Visitor<'tcx> for PlaceCollector<'_, 'tcx> {
584 #[tracing::instrument(level = "trace", skip(self))]
585 fn visit_place(&mut self, place: &Place<'tcx>, ctxt: PlaceContext, _: Location) {
586 if !ctxt.is_use() {
587 return;
588 }
589
590 self.register_place(*place);
591 }
592
593 fn visit_assign(&mut self, lhs: &Place<'tcx>, rhs: &Rvalue<'tcx>, location: Location) {
594 self.super_assign(lhs, rhs, location);
595
596 match rhs {
597 Rvalue::Use(Operand::Move(rhs) | Operand::Copy(rhs)) | Rvalue::CopyForDeref(rhs) => {
598 let Some(lhs) = self.register_place(*lhs) else { return };
599 let Some(rhs) = self.register_place(*rhs) else { return };
600 self.assignments.insert((lhs, rhs));
601 }
602 Rvalue::Aggregate(kind, fields) => {
603 let Some(mut lhs) = self.register_place(*lhs) else { return };
604 match **kind {
605 AggregateKind::Adt(_, _, _, _, Some(_)) => return,
607 AggregateKind::Adt(_, variant, _, _, None) => {
608 let ty = self.map.places[lhs].ty;
609 if ty.is_enum() {
610 lhs = self.map.register_place(ty, lhs, TrackElem::Variant(variant));
611 }
612 }
613 AggregateKind::RawPtr(..)
614 | AggregateKind::Array(_)
615 | AggregateKind::Tuple
616 | AggregateKind::Closure(..)
617 | AggregateKind::Coroutine(..)
618 | AggregateKind::CoroutineClosure(..) => {}
619 }
620 for (index, field) in fields.iter_enumerated() {
621 if let Some(rhs) = field.place()
622 && let Some(rhs) = self.register_place(rhs)
623 {
624 let lhs = self.map.register_place(
625 self.map.places[rhs].ty,
626 lhs,
627 TrackElem::Field(index),
628 );
629 self.assignments.insert((lhs, rhs));
630 }
631 }
632 }
633 _ => {}
634 }
635 }
636}
637
638impl<'tcx> Map<'tcx> {
639 pub fn apply(&self, place: PlaceIndex, elem: TrackElem) -> Option<PlaceIndex> {
641 self.projections.get(&(place, elem)).copied()
642 }
643
644 fn find_extra(
646 &self,
647 place: PlaceRef<'_>,
648 extra: impl IntoIterator<Item = TrackElem>,
649 ) -> Option<PlaceIndex> {
650 let mut index = *self.locals[place.local].as_ref()?;
651
652 for &elem in place.projection {
653 index = self.apply(index, elem.try_into().ok()?)?;
654 }
655 for elem in extra {
656 index = self.apply(index, elem)?;
657 }
658
659 Some(index)
660 }
661
662 pub fn find(&self, place: PlaceRef<'_>) -> Option<PlaceIndex> {
664 self.find_extra(place, [])
665 }
666
667 pub fn find_discr(&self, place: PlaceRef<'_>) -> Option<PlaceIndex> {
669 self.find_extra(place, [TrackElem::Discriminant])
670 }
671
672 pub fn find_len(&self, place: PlaceRef<'_>) -> Option<PlaceIndex> {
674 self.find_extra(place, [TrackElem::DerefLen])
675 }
676
677 fn children(&self, parent: PlaceIndex) -> impl Iterator<Item = PlaceIndex> {
679 Children::new(self, parent)
680 }
681
682 fn for_each_aliasing_place(
690 &self,
691 place: PlaceRef<'_>,
692 tail_elem: Option<TrackElem>,
693 f: &mut impl FnMut(ValueIndex),
694 ) {
695 if place.is_indirect_first_projection() {
696 return;
698 }
699 let Some(mut index) = self.locals[place.local] else {
700 return;
702 };
703 let elems = place.projection.iter().map(|&elem| elem.try_into()).chain(tail_elem.map(Ok));
704 for elem in elems {
705 if let Some(vi) = self.places[index].value_index {
707 f(vi);
708 }
709
710 let Ok(elem) = elem else { return };
711 let sub = self.apply(index, elem);
712 if let TrackElem::Variant(..) | TrackElem::Discriminant = elem {
713 self.for_each_variant_sibling(index, sub, f);
715 }
716 if let Some(sub) = sub {
717 index = sub
718 } else {
719 return;
720 }
721 }
722 self.for_each_value_inside(index, f);
723 }
724
725 fn for_each_variant_sibling(
727 &self,
728 parent: PlaceIndex,
729 preserved_child: Option<PlaceIndex>,
730 f: &mut impl FnMut(ValueIndex),
731 ) {
732 for sibling in self.children(parent) {
733 let elem = self.places[sibling].proj_elem;
734 if let Some(TrackElem::Variant(..) | TrackElem::Discriminant) = elem
737 && Some(sibling) != preserved_child
739 {
740 self.for_each_value_inside(sibling, f);
741 }
742 }
743 }
744
745 fn for_each_value_inside(&self, root: PlaceIndex, f: &mut impl FnMut(ValueIndex)) {
747 let range = self.inner_values[root].clone();
748 let values = &self.inner_values_buffer[range];
749 for &v in values {
750 f(v)
751 }
752 }
753
754 pub fn for_each_projection_value<O>(
756 &self,
757 root: PlaceIndex,
758 value: O,
759 project: &mut impl FnMut(TrackElem, &O) -> Option<O>,
760 f: &mut impl FnMut(PlaceIndex, &O),
761 ) {
762 if self.inner_values[root].is_empty() {
764 return;
765 }
766
767 if self.places[root].value_index.is_some() {
768 f(root, &value)
769 }
770
771 for child in self.children(root) {
772 let elem = self.places[child].proj_elem.unwrap();
773 if let Some(value) = project(elem, &value) {
774 self.for_each_projection_value(child, value, project, f);
775 }
776 }
777 }
778}
779
780#[derive(Debug)]
785struct PlaceInfo<'tcx> {
786 ty: Ty<'tcx>,
788
789 value_index: Option<ValueIndex>,
791
792 proj_elem: Option<TrackElem>,
794
795 first_child: Option<PlaceIndex>,
797
798 next_sibling: Option<PlaceIndex>,
800}
801
802impl<'tcx> PlaceInfo<'tcx> {
803 fn new(ty: Ty<'tcx>, proj_elem: Option<TrackElem>) -> Self {
804 Self { ty, next_sibling: None, first_child: None, proj_elem, value_index: None }
805 }
806}
807
808struct Children<'a, 'tcx> {
809 map: &'a Map<'tcx>,
810 next: Option<PlaceIndex>,
811}
812
813impl<'a, 'tcx> Children<'a, 'tcx> {
814 fn new(map: &'a Map<'tcx>, parent: PlaceIndex) -> Self {
815 Self { map, next: map.places[parent].first_child }
816 }
817}
818
819impl Iterator for Children<'_, '_> {
820 type Item = PlaceIndex;
821
822 fn next(&mut self) -> Option<Self::Item> {
823 match self.next {
824 Some(child) => {
825 self.next = self.map.places[child].next_sibling;
826 Some(child)
827 }
828 None => None,
829 }
830 }
831}
832
833#[derive(Debug)]
835pub enum ValueOrPlace<V> {
836 Value(V),
837 Place(PlaceIndex),
838}
839
840impl<V: HasTop> ValueOrPlace<V> {
841 pub const TOP: Self = ValueOrPlace::Value(V::TOP);
842}
843
844#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
848pub enum TrackElem {
849 Field(FieldIdx),
850 Variant(VariantIdx),
851 Discriminant,
852 DerefLen,
854}
855
856impl<V, T> TryFrom<ProjectionElem<V, T>> for TrackElem {
857 type Error = ();
858
859 fn try_from(value: ProjectionElem<V, T>) -> Result<Self, Self::Error> {
860 match value {
861 ProjectionElem::Field(field, _) => Ok(TrackElem::Field(field)),
862 ProjectionElem::Downcast(_, idx) => Ok(TrackElem::Variant(idx)),
863 _ => Err(()),
864 }
865 }
866}
867
868pub fn iter_fields<'tcx>(
870 ty: Ty<'tcx>,
871 tcx: TyCtxt<'tcx>,
872 typing_env: ty::TypingEnv<'tcx>,
873 mut f: impl FnMut(Option<VariantIdx>, FieldIdx, Ty<'tcx>),
874) {
875 match ty.kind() {
876 ty::Tuple(list) => {
877 for (field, ty) in list.iter().enumerate() {
878 f(None, field.into(), ty);
879 }
880 }
881 ty::Adt(def, args) => {
882 if def.is_union() {
883 return;
884 }
885 for (v_index, v_def) in def.variants().iter_enumerated() {
886 let variant = if def.is_struct() { None } else { Some(v_index) };
887 for (f_index, f_def) in v_def.fields.iter().enumerate() {
888 let field_ty = f_def.ty(tcx, args);
889 let field_ty = tcx
890 .try_normalize_erasing_regions(typing_env, field_ty)
891 .unwrap_or_else(|_| tcx.erase_regions(field_ty));
892 f(variant, f_index.into(), field_ty);
893 }
894 }
895 }
896 ty::Closure(_, args) => {
897 iter_fields(args.as_closure().tupled_upvars_ty(), tcx, typing_env, f);
898 }
899 ty::Coroutine(_, args) => {
900 iter_fields(args.as_coroutine().tupled_upvars_ty(), tcx, typing_env, f);
901 }
902 ty::CoroutineClosure(_, args) => {
903 iter_fields(args.as_coroutine_closure().tupled_upvars_ty(), tcx, typing_env, f);
904 }
905 _ => (),
906 }
907}
908
909pub fn excluded_locals(body: &Body<'_>) -> DenseBitSet<Local> {
911 struct Collector {
912 result: DenseBitSet<Local>,
913 }
914
915 impl<'tcx> Visitor<'tcx> for Collector {
916 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
917 if (context.is_borrow()
918 || context.is_address_of()
919 || context.is_drop()
920 || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput))
921 && !place.is_indirect()
922 {
923 self.result.insert(place.local);
926 }
927 }
928 }
929
930 let mut collector = Collector { result: DenseBitSet::new_empty(body.local_decls.len()) };
931 collector.visit_body(body);
932 collector.result
933}
934
935fn debug_with_context_rec<V: Debug + Eq + HasBottom>(
936 place: PlaceIndex,
937 place_str: &str,
938 new: &StateData<V>,
939 old: Option<&StateData<V>>,
940 map: &Map<'_>,
941 f: &mut Formatter<'_>,
942) -> std::fmt::Result {
943 if let Some(value) = map.places[place].value_index {
944 match old {
945 None => writeln!(f, "{}: {:?}", place_str, new.get(value))?,
946 Some(old) => {
947 if new.get(value) != old.get(value) {
948 writeln!(f, "\u{001f}-{}: {:?}", place_str, old.get(value))?;
949 writeln!(f, "\u{001f}+{}: {:?}", place_str, new.get(value))?;
950 }
951 }
952 }
953 }
954
955 for child in map.children(place) {
956 let info_elem = map.places[child].proj_elem.unwrap();
957 let child_place_str = match info_elem {
958 TrackElem::Discriminant => {
959 format!("discriminant({place_str})")
960 }
961 TrackElem::Variant(idx) => {
962 format!("({place_str} as {idx:?})")
963 }
964 TrackElem::Field(field) => {
965 if place_str.starts_with('*') {
966 format!("({}).{}", place_str, field.index())
967 } else {
968 format!("{}.{}", place_str, field.index())
969 }
970 }
971 TrackElem::DerefLen => {
972 format!("Len(*{})", place_str)
973 }
974 };
975 debug_with_context_rec(child, &child_place_str, new, old, map, f)?;
976 }
977
978 Ok(())
979}
980
981pub fn debug_with_context<V: Debug + Eq + HasBottom>(
982 new: &StateData<V>,
983 old: Option<&StateData<V>>,
984 map: &Map<'_>,
985 f: &mut Formatter<'_>,
986) -> std::fmt::Result {
987 for (local, place) in map.locals.iter_enumerated() {
988 if let Some(place) = place {
989 debug_with_context_rec(*place, &format!("{local:?}"), new, old, map, f)?;
990 }
991 }
992 Ok(())
993}