Skip to content

Commit 0ca8d6e

Browse files
Rollup merge of #163166 - lqd:deferred-liveness, r=jackh726
Tiny cleanups to deferred liveness As discussed on zulip, this is the first batch of a handful of tiny cleanups about deferred liveness: - some renamings - some simplifications - some comments r? @jackh726
2 parents fa0d183 + 9a3ab65 commit 0ca8d6e

9 files changed

Lines changed: 103 additions & 117 deletions

File tree

‎compiler/rustc_borrowck/src/nll.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ pub(crate) fn compute_regions<'tcx>(
156156
&universal_region_relations.universal_regions,
157157
body,
158158
move_data,
159-
&location_map,
159+
Rc::clone(&location_map),
160160
borrow_set,
161161
);
162162
}

‎compiler/rustc_borrowck/src/polonius/constraints.rs‎

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::rc::Rc;
2+
13
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
24
use rustc_index::IndexVec;
35
use rustc_middle::mir::{Body, Location};
@@ -8,7 +10,7 @@ use crate::BorrowSet;
810
use crate::constraints::OutlivesConstraint;
911
use crate::dataflow::BorrowIndex;
1012
use crate::polonius::ConstraintDirection;
11-
use crate::polonius::liveness::RegionLiveness;
13+
use crate::polonius::liveness::LivenessSource;
1214
use crate::type_check::Locations;
1315

1416
/// A localized outlives constraint reifies the CFG location where the outlives constraint holds,
@@ -38,6 +40,8 @@ pub(super) struct LocalizedNode {
3840
/// The localized constraint graph indexes the physical and logical edges to lazily compute a given
3941
/// node's successors during traversal.
4042
pub(super) struct LocalizedConstraintGraph {
43+
location_map: Rc<DenseLocationMap>,
44+
4145
/// The actual, physical, edges we have recorded for a given node. We localize them on-demand
4246
/// when traversing from the node to the successor region.
4347
edges: FxHashMap<LocalizedNode, FxIndexSet<RegionVid>>,
@@ -48,16 +52,10 @@ pub(super) struct LocalizedConstraintGraph {
4852
logical_edges: IndexVec<RegionVid, FxIndexSet<RegionVid>>,
4953
}
5054

51-
/// The source of liveness information for a given region.
52-
pub(super) trait LivenessSource<'loc> {
53-
fn liveness_for_region(&mut self, region: RegionVid) -> RegionLiveness<'_>;
54-
fn location_map(&self) -> &'loc DenseLocationMap;
55-
}
56-
5755
/// The visitor interface when traversing a `LocalizedConstraintGraph`.
5856
pub(super) trait LocalizedConstraintGraphVisitor {
5957
/// Callback called when traversing a given `loan` encounters a localized `node` it hasn't
60-
/// visited before.
58+
/// visited before, and whether its region is live at that point.
6159
fn on_node_traversed(&mut self, _loan: BorrowIndex, _node: LocalizedNode, _is_live: bool) {}
6260

6361
/// Callback called when discovering a new `successor` node for the `current_node`.
@@ -68,7 +66,7 @@ pub(super) trait LocalizedConstraintGraphVisitor {
6866
impl LocalizedConstraintGraph {
6967
/// Traverses the constraints and returns the indexed graph of edges per node.
7068
pub(super) fn new<'tcx>(
71-
location_map: &DenseLocationMap,
69+
location_map: Rc<DenseLocationMap>,
7270
outlives_constraints: impl Iterator<Item = OutlivesConstraint<'tcx>>,
7371
) -> Self {
7472
let mut edges: FxHashMap<_, FxIndexSet<_>> = FxHashMap::default();
@@ -92,23 +90,21 @@ impl LocalizedConstraintGraph {
9290
}
9391
}
9492

95-
LocalizedConstraintGraph { edges, logical_edges }
93+
LocalizedConstraintGraph { location_map, edges, logical_edges }
9694
}
9795

9896
/// Traverses the localized constraint graph per-loan, and notifies the `visitor` of discovered
9997
/// nodes and successors.
100-
pub(super) fn traverse<'tcx, 'loc>(
98+
pub(super) fn traverse<'tcx>(
10199
&self,
102100
body: &Body<'tcx>,
103101
borrow_set: &BorrowSet<'tcx>,
104-
liveness_source: &mut impl LivenessSource<'loc>,
102+
liveness_source: &mut impl LivenessSource,
105103
visitor: &mut impl LocalizedConstraintGraphVisitor,
106104
) {
107105
let mut visited = FxHashSet::default();
108106
let mut stack = Vec::new();
109107

110-
let location_map = liveness_source.location_map();
111-
112108
// Compute reachability per loan by traversing each loan's subgraph starting from where it
113109
// is introduced.
114110
for (loan_idx, loan) in borrow_set.iter_enumerated() {
@@ -117,15 +113,15 @@ impl LocalizedConstraintGraph {
117113

118114
let start_node = LocalizedNode {
119115
region: loan.region,
120-
point: location_map.point_from_location(loan.reserve_location),
116+
point: self.location_map.point_from_location(loan.reserve_location),
121117
};
122118
visited.insert(start_node);
123119
stack.push(start_node);
124120

125121
while let Some(node) = stack.pop() {
126122
let liveness = liveness_source.liveness_for_region(node.region);
127123
// We've reached a node we haven't visited before.
128-
let location = location_map.to_location(node.point);
124+
let location = self.location_map.to_location(node.point);
129125
visitor.on_node_traversed(loan_idx, node, liveness.is_live_at(node.point));
130126

131127
// When we find a _new_ successor, we'd like to
@@ -181,7 +177,7 @@ impl LocalizedConstraintGraph {
181177
for successor_block in body[location.block].terminator().successors() {
182178
let next_location =
183179
Location { block: successor_block, statement_index: 0 };
184-
let next_point = location_map.point_from_location(next_location);
180+
let next_point = self.location_map.point_from_location(next_location);
185181
if liveness.is_live_at(next_point) {
186182
successor_found(LocalizedNode {
187183
region: node.region,
@@ -224,7 +220,7 @@ impl LocalizedConstraintGraph {
224220
statement_index: body[pred_block].statements.len(),
225221
};
226222
let previous_point =
227-
location_map.point_from_location(previous_location);
223+
self.location_map.point_from_location(previous_location);
228224
successor_found(LocalizedNode {
229225
region: node.region,
230226
point: previous_point,

‎compiler/rustc_borrowck/src/polonius/dump.rs‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use rustc_index::IndexVec;
55
use rustc_middle::mir::pretty::{MirDumper, PassWhere, PrettyPrintMirOptions};
66
use rustc_middle::mir::{Body, Location};
77
use rustc_middle::ty::{RegionVid, TyCtxt};
8-
use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex};
8+
use rustc_mir_dataflow::points::PointIndex;
99
use rustc_session::config::MirIncludeSpans;
1010

1111
use crate::borrow_set::BorrowSet;
@@ -32,7 +32,7 @@ struct CachedLivenessSource<'a, 'tcx> {
3232
liveness: &'a LivenessValues,
3333
}
3434

35-
impl<'a, 'tcx> LivenessSource<'a> for CachedLivenessSource<'a, 'tcx> {
35+
impl<'a, 'tcx> LivenessSource for CachedLivenessSource<'a, 'tcx> {
3636
fn liveness_for_region(&mut self, region: RegionVid) -> RegionLiveness<'_> {
3737
RegionLiveness::new(
3838
region,
@@ -41,9 +41,6 @@ impl<'a, 'tcx> LivenessSource<'a> for CachedLivenessSource<'a, 'tcx> {
4141
self.liveness.points(),
4242
)
4343
}
44-
fn location_map(&self) -> &'a DenseLocationMap {
45-
self.liveness.location_map()
46-
}
4744
}
4845

4946
/// `-Zdump-mir=polonius` dumps MIR annotated with NLL and polonius specific information.

‎compiler/rustc_borrowck/src/polonius/liveness.rs‎

Lines changed: 53 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,63 @@
11
use rustc_index::IndexVec;
22
use rustc_index::interval::{IntervalSet, SparseIntervalMatrix};
33
use rustc_middle::mir::Local;
4-
use rustc_middle::ty::{GenericArg, RegionVid, Ty};
4+
use rustc_middle::ty::{GenericArg, RegionVid, Ty, TyCtxt};
55
use rustc_mir_dataflow::points::PointIndex;
66

7-
use crate::BorrowckInferCtxt;
87
use crate::polonius::{ConstraintDirection, LiveRegionVariances};
98
use crate::region_infer::values::LivenessValues;
109
use crate::type_check::liveness::LivenessComputation;
1110
use crate::universal_regions::UniversalRegions;
1211

12+
/// The source of liveness information for a given region.
13+
pub(super) trait LivenessSource {
14+
fn liveness_for_region(&mut self, region: RegionVid) -> RegionLiveness<'_>;
15+
}
16+
17+
/// For a given region, the relevant liveness and variance information.
18+
pub(super) struct RegionLiveness<'a> {
19+
pub(super) direction: ConstraintDirection,
20+
live_points: Option<&'a IntervalSet<PointIndex>>,
21+
}
22+
23+
impl<'a> RegionLiveness<'a> {
24+
#[inline]
25+
pub(super) fn new<'tcx>(
26+
region: RegionVid,
27+
live_region_variances: &LiveRegionVariances,
28+
universal_regions: &UniversalRegions<'tcx>,
29+
live_points: &'a SparseIntervalMatrix<RegionVid, PointIndex>,
30+
) -> Self {
31+
// Universal regions propagate loans along the CFG, i.e. forwards only.
32+
let is_universal_region = universal_regions.is_universal_region(region);
33+
34+
// Note: there currently are cases related to promoted and const generics, where we don't yet
35+
// have variance information (possibly about temporary regions created when typeck sanitizes the
36+
// promoteds). Until that is done, we conservatively fallback to maximizing reachability by
37+
// adding a bidirectional edge here. This will not limit traversal whatsoever, and thus
38+
// propagate liveness when needed.
39+
//
40+
// FIXME: add the missing variance information and remove this fallback bidirectional edge.
41+
let direction = if is_universal_region {
42+
ConstraintDirection::Forward
43+
} else {
44+
live_region_variances
45+
.get(region)
46+
.copied()
47+
.flatten()
48+
.unwrap_or(ConstraintDirection::Bidirectional)
49+
};
50+
let live_points = live_points.row(region);
51+
Self { direction, live_points }
52+
}
53+
54+
pub(super) fn is_live_at(&self, point: PointIndex) -> bool {
55+
self.live_points.map_or(false, |points| points.contains(point))
56+
}
57+
}
58+
59+
/// The data needed to compute region liveness on-demand while traversing the localized outlives
60+
/// constraint graph to compute loan liveness.
1361
#[derive(Default)]
1462
pub(crate) struct DeferredLocals<'tcx> {
1563
/// For each region, the local whose liveness is deferred.
@@ -24,14 +72,12 @@ pub(crate) struct DeferredLocals<'tcx> {
2472
impl<'tcx> DeferredLocals<'tcx> {
2573
pub(crate) fn defer_local(
2674
&mut self,
27-
infcx: &BorrowckInferCtxt<'tcx>,
75+
tcx: TyCtxt<'tcx>,
2876
universal_regions: &UniversalRegions<'tcx>,
2977
local: Local,
3078
local_ty: Ty<'tcx>,
3179
dropck_kinds: &[GenericArg<'tcx>],
3280
) {
33-
let tcx = infcx.tcx;
34-
3581
// We already have drop data for this local, because we need to register
3682
// region constraints eagerly. So, we'll store this so we don't need to
3783
// recompute.
@@ -42,7 +88,7 @@ impl<'tcx> DeferredLocals<'tcx> {
4288
// we can trace liveness for the local containing it.
4389
let by_region = &mut self.by_region;
4490
tcx.for_each_free_region(&local_ty, |region| {
45-
// See note in [`VarianceExtractor::record_variance`].
91+
// See note in `VarianceExtractor::record_variance`.
4692
if region.is_bound() || region.is_erased() {
4793
return;
4894
}
@@ -58,7 +104,7 @@ impl<'tcx> DeferredLocals<'tcx> {
58104
});
59105
}
60106

61-
/// For a given region, compute the liveness for the local containing it, if if is deferred.
107+
/// For a given region, compute the liveness for the local containing it, if it is deferred.
62108
#[inline]
63109
pub(crate) fn compute_deferred_local(
64110
&mut self,
@@ -80,45 +126,3 @@ impl<'tcx> DeferredLocals<'tcx> {
80126
});
81127
}
82128
}
83-
84-
/// For a given region, the relevant liveness and variance information.
85-
pub(super) struct RegionLiveness<'a> {
86-
pub(super) direction: ConstraintDirection,
87-
live_points: Option<&'a IntervalSet<PointIndex>>,
88-
}
89-
90-
impl<'a> RegionLiveness<'a> {
91-
#[inline]
92-
pub(super) fn new<'tcx>(
93-
region: RegionVid,
94-
live_region_variances: &LiveRegionVariances,
95-
universal_regions: &UniversalRegions<'tcx>,
96-
live_points: &'a SparseIntervalMatrix<RegionVid, PointIndex>,
97-
) -> Self {
98-
// Universal regions propagate loans along the CFG, i.e. forwards only.
99-
let is_universal_region = universal_regions.is_universal_region(region);
100-
101-
// Note: there currently are cases related to promoted and const generics, where we don't yet
102-
// have variance information (possibly about temporary regions created when typeck sanitizes the
103-
// promoteds). Until that is done, we conservatively fallback to maximizing reachability by
104-
// adding a bidirectional edge here. This will not limit traversal whatsoever, and thus
105-
// propagate liveness when needed.
106-
//
107-
// FIXME: add the missing variance information and remove this fallback bidirectional edge.
108-
let direction = if is_universal_region {
109-
ConstraintDirection::Forward
110-
} else {
111-
live_region_variances
112-
.get(region)
113-
.copied()
114-
.flatten()
115-
.unwrap_or(ConstraintDirection::Bidirectional)
116-
};
117-
let live_points = live_points.row(region);
118-
Self { direction, live_points }
119-
}
120-
121-
pub(super) fn is_live_at(&self, point: PointIndex) -> bool {
122-
self.live_points.map_or(false, |points| points.contains(point))
123-
}
124-
}

‎compiler/rustc_borrowck/src/polonius/mod.rs‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ pub(crate) mod legacy;
3939
mod liveness;
4040
mod liveness_constraints;
4141

42+
use std::rc::Rc;
43+
4244
use rustc_data_structures::fx::FxHashSet;
4345
use rustc_index::IndexVec;
4446
use rustc_index::bit_set::DenseBitSet;
@@ -53,7 +55,7 @@ pub(crate) use self::liveness_constraints::record_live_region_variance;
5355
use crate::constraints::OutlivesConstraint;
5456
use crate::dataflow::BorrowIndex;
5557
pub(crate) use crate::polonius::liveness::DeferredLocals;
56-
use crate::polonius::liveness::RegionLiveness;
58+
use crate::polonius::liveness::{LivenessSource, RegionLiveness};
5759
use crate::region_infer::values::LivenessValues;
5860
use crate::type_check::liveness::{LivenessComputation, LocalUseMap};
5961
use crate::universal_regions::UniversalRegions;
@@ -141,7 +143,7 @@ impl<'tcx> PoloniusContext<'tcx> {
141143
universal_regions: &UniversalRegions<'tcx>,
142144
body: &Body<'tcx>,
143145
move_data: &MoveData<'tcx>,
144-
location_map: &DenseLocationMap,
146+
location_map: Rc<DenseLocationMap>,
145147
borrow_set: &BorrowSet<'tcx>,
146148
) {
147149
// We don't need to prepare the graph (index NLL constraints, etc.) if we have no loans to
@@ -151,7 +153,7 @@ impl<'tcx> PoloniusContext<'tcx> {
151153
// on the lazy localized constraint graph to trace the liveness of loans, for the next
152154
// step in the chain (the NLL loan scope and active loans computations).
153155
let graph =
154-
LocalizedConstraintGraph::new(liveness.location_map(), outlives_constraints);
156+
LocalizedConstraintGraph::new(Rc::clone(&location_map), outlives_constraints);
155157

156158
let local_use_map = self
157159
.local_use_map
@@ -161,7 +163,7 @@ impl<'tcx> PoloniusContext<'tcx> {
161163
std::mem::take(&mut self.deferred_locals_for_liveness);
162164
let mut live_loans = LiveLoans::new(location_map.num_points(), borrow_set.len());
163165
let comp =
164-
LivenessComputation::new(infcx, body, location_map, move_data, &local_use_map);
166+
LivenessComputation::new(infcx, body, &location_map, move_data, &local_use_map);
165167
let mut liveness_source = DeferredLivenessSource {
166168
liveness,
167169
live_region_variances: &mut self.live_region_variances,
@@ -190,7 +192,7 @@ struct DeferredLivenessSource<'a, 'tcx> {
190192
comp: LivenessComputation<'a, 'tcx>,
191193
}
192194

193-
impl<'a> LivenessSource<'a> for DeferredLivenessSource<'a, '_> {
195+
impl<'a> LivenessSource for DeferredLivenessSource<'a, '_> {
194196
#[inline]
195197
fn liveness_for_region(&mut self, region: RegionVid) -> RegionLiveness<'_> {
196198
self.deferred_locals_for_liveness.compute_deferred_local(
@@ -208,10 +210,6 @@ impl<'a> LivenessSource<'a> for DeferredLivenessSource<'a, '_> {
208210
self.liveness.points(),
209211
)
210212
}
211-
212-
fn location_map(&self) -> &'a DenseLocationMap {
213-
self.comp.location_map
214-
}
215213
}
216214

217215
/// Visitor to record loan liveness when traversing the localized constraint graph.

‎compiler/rustc_borrowck/src/region_infer/values.rs‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,10 +201,6 @@ impl LivenessValues {
201201
self.location_map.to_location(point)
202202
}
203203

204-
pub(crate) fn location_map(&self) -> &Rc<DenseLocationMap> {
205-
&self.location_map
206-
}
207-
208204
/// When using `-Zpolonius=next`, records the given live loans for the loan scopes and active
209205
/// loans dataflow computations.
210206
pub(crate) fn record_live_loans(&mut self, live_loans: LiveLoans) {

‎compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ impl<'a> Iterator for AppearancesIter<'a> {
8282

8383
impl LocalUseMap {
8484
pub(crate) fn build(
85-
live_locals: &[Local],
85+
mut live_locals: impl Iterator<Item = Local>,
8686
location_map: &DenseLocationMap,
8787
body: &Body<'_>,
8888
) -> Self {
@@ -94,13 +94,11 @@ impl LocalUseMap {
9494
appearances: IndexVec::new(),
9595
};
9696

97-
if live_locals.is_empty() {
98-
return local_use_map;
99-
}
97+
let Some(head) = live_locals.next() else { return local_use_map };
10098

101-
let mut locals_with_use_data: DenseBitSet<Local> =
102-
DenseBitSet::new_empty(body.local_decls.len());
103-
live_locals.iter().for_each(|&local| {
99+
let mut locals_with_use_data = DenseBitSet::new_empty(body.local_decls.len());
100+
locals_with_use_data.insert(head);
101+
live_locals.for_each(|local| {
104102
locals_with_use_data.insert(local);
105103
});
106104

0 commit comments

Comments
 (0)