Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 207b712

Browse files
committedApr 17, 2025
Auto merge of #139965 - amandasystems:marginally-improved-scc-annotations, r=<try>
Decouple SCC annotations from SCCs This rewires SCC annotations to have them be a separate, visitor-type data structure. It was broken out of #130227, which needed them to be able to remove unused annotations after computation without recomputing the SCCs themselves. As a drive-by it also removes some redundant code from the hot loop in SCC construction for a performance improvement. r? lcnr
2 parents 15c4cce + ae763d6 commit 207b712

File tree

4 files changed

+226
-157
lines changed

4 files changed

+226
-157
lines changed
 

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

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_middle::ty::{RegionVid, TyCtxt, VarianceDiagInfo};
77
use rustc_span::Span;
88
use tracing::{debug, instrument};
99

10-
use crate::region_infer::{ConstraintSccs, RegionDefinition, RegionTracker};
10+
use crate::region_infer::{AnnotatedSccs, ConstraintSccs, RegionDefinition, SccAnnotations};
1111
use crate::type_check::Locations;
1212
use crate::universal_regions::UniversalRegions;
1313

@@ -61,12 +61,14 @@ impl<'tcx> OutlivesConstraintSet<'tcx> {
6161
&self,
6262
static_region: RegionVid,
6363
definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
64-
) -> ConstraintSccs {
64+
) -> AnnotatedSccs {
6565
let constraint_graph = self.graph(definitions.len());
6666
let region_graph = &constraint_graph.region_graph(self, static_region);
67-
ConstraintSccs::new_with_annotation(&region_graph, |r| {
68-
RegionTracker::new(r, &definitions[r])
69-
})
67+
let mut annotation_visitor = SccAnnotations::new(definitions);
68+
(
69+
ConstraintSccs::new_with_annotation(&region_graph, &mut annotation_visitor),
70+
annotation_visitor.scc_to_annotation,
71+
)
7072
}
7173

7274
/// This method handles Universe errors by rewriting the constraint
@@ -108,9 +110,9 @@ impl<'tcx> OutlivesConstraintSet<'tcx> {
108110
&mut self,
109111
universal_regions: &UniversalRegions<'tcx>,
110112
definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
111-
) -> ConstraintSccs {
113+
) -> AnnotatedSccs {
112114
let fr_static = universal_regions.fr_static;
113-
let sccs = self.compute_sccs(fr_static, definitions);
115+
let (sccs, annotations) = self.compute_sccs(fr_static, definitions);
114116

115117
// Changed to `true` if we added any constraints to `self` and need to
116118
// recompute SCCs.
@@ -124,7 +126,7 @@ impl<'tcx> OutlivesConstraintSet<'tcx> {
124126
continue;
125127
}
126128

127-
let annotation = sccs.annotation(scc);
129+
let annotation = annotations[scc];
128130

129131
// If this SCC participates in a universe violation,
130132
// e.g. if it reaches a region with a universe smaller than
@@ -154,7 +156,7 @@ impl<'tcx> OutlivesConstraintSet<'tcx> {
154156
self.compute_sccs(fr_static, definitions)
155157
} else {
156158
// If we didn't add any back-edges; no more work needs doing
157-
sccs
159+
(sccs, annotations)
158160
}
159161
}
160162
}

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

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,13 @@ mod reverse_sccs;
4747

4848
pub(crate) mod values;
4949

50-
pub(crate) type ConstraintSccs = Sccs<RegionVid, ConstraintSccIndex, RegionTracker>;
50+
pub(crate) type ConstraintSccs = Sccs<RegionVid, ConstraintSccIndex>;
51+
pub(crate) type AnnotatedSccs = (ConstraintSccs, IndexVec<ConstraintSccIndex, RegionTracker>);
5152

5253
/// An annotation for region graph SCCs that tracks
53-
/// the values of its elements.
54+
/// the values of its elements. This annotates a single SCC.
5455
#[derive(Copy, Debug, Clone)]
55-
pub struct RegionTracker {
56+
pub(crate) struct RegionTracker {
5657
/// The largest universe of a placeholder reached from this SCC.
5758
/// This includes placeholders within this SCC.
5859
max_placeholder_universe_reached: UniverseIndex,
@@ -97,6 +98,31 @@ impl scc::Annotation for RegionTracker {
9798
}
9899
}
99100

101+
/// A Visitor for SCC annotation construction.
102+
pub(crate) struct SccAnnotations<'d, 'tcx, A: scc::Annotation> {
103+
pub(crate) scc_to_annotation: IndexVec<ConstraintSccIndex, A>,
104+
definitions: &'d IndexVec<RegionVid, RegionDefinition<'tcx>>,
105+
}
106+
107+
impl<'d, 'tcx, A: scc::Annotation> SccAnnotations<'d, 'tcx, A> {
108+
pub(crate) fn new(definitions: &'d IndexVec<RegionVid, RegionDefinition<'tcx>>) -> Self {
109+
Self { scc_to_annotation: IndexVec::new(), definitions }
110+
}
111+
}
112+
113+
impl scc::Annotations<RegionVid, ConstraintSccIndex, RegionTracker>
114+
for SccAnnotations<'_, '_, RegionTracker>
115+
{
116+
fn new(&self, element: RegionVid) -> RegionTracker {
117+
RegionTracker::new(element, &self.definitions[element])
118+
}
119+
120+
fn annotate_scc(&mut self, scc: ConstraintSccIndex, annotation: RegionTracker) {
121+
let idx = self.scc_to_annotation.push(annotation);
122+
assert!(idx == scc);
123+
}
124+
}
125+
100126
impl RegionTracker {
101127
pub(crate) fn new(rvid: RegionVid, definition: &RegionDefinition<'_>) -> Self {
102128
let (representative_is_placeholder, representative_is_existential) = match definition.origin
@@ -166,6 +192,8 @@ pub struct RegionInferenceContext<'tcx> {
166192
/// compute the values of each region.
167193
constraint_sccs: ConstraintSccs,
168194

195+
scc_annotations: IndexVec<ConstraintSccIndex, RegionTracker>,
196+
169197
/// Reverse of the SCC constraint graph -- i.e., an edge `A -> B` exists if
170198
/// `B: A`. This is used to compute the universal regions that are required
171199
/// to outlive a given SCC. Computed lazily.
@@ -446,7 +474,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
446474

447475
let definitions = create_definitions(infcx, &universal_regions);
448476

449-
let constraint_sccs =
477+
let (constraint_sccs, scc_annotations) =
450478
outlives_constraints.add_outlives_static(&universal_regions, &definitions);
451479
let constraints = Frozen::freeze(outlives_constraints);
452480
let constraint_graph = Frozen::freeze(constraints.graph(definitions.len()));
@@ -472,6 +500,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
472500
constraints,
473501
constraint_graph,
474502
constraint_sccs,
503+
scc_annotations,
475504
rev_scc_graph: None,
476505
member_constraints,
477506
member_constraints_applied: Vec::new(),
@@ -757,6 +786,10 @@ impl<'tcx> RegionInferenceContext<'tcx> {
757786
debug!(value = ?self.scc_values.region_value_str(scc_a));
758787
}
759788

789+
fn scc_annotations(&self) -> &IndexVec<ConstraintSccIndex, RegionTracker> {
790+
&self.scc_annotations
791+
}
792+
760793
/// Invoked for each `R0 member of [R1..Rn]` constraint.
761794
///
762795
/// `scc` is the SCC containing R0, and `choice_regions` are the
@@ -798,7 +831,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
798831

799832
// If the member region lives in a higher universe, we currently choose
800833
// the most conservative option by leaving it unchanged.
801-
if !self.constraint_sccs().annotation(scc).min_universe().is_root() {
834+
if !self.scc_annotations()[scc].min_universe().is_root() {
802835
return;
803836
}
804837

@@ -874,8 +907,8 @@ impl<'tcx> RegionInferenceContext<'tcx> {
874907
/// in `scc_a`. Used during constraint propagation, and only once
875908
/// the value of `scc_b` has been computed.
876909
fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
877-
let a_annotation = self.constraint_sccs().annotation(scc_a);
878-
let b_annotation = self.constraint_sccs().annotation(scc_b);
910+
let a_annotation = self.scc_annotations()[scc_a];
911+
let b_annotation = self.scc_annotations()[scc_b];
879912
let a_universe = a_annotation.min_universe();
880913

881914
// If scc_b's declared universe is a subset of
@@ -991,7 +1024,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
9911024
"lower_bound = {:?} r_scc={:?} universe={:?}",
9921025
lower_bound,
9931026
r_scc,
994-
self.constraint_sccs.annotation(r_scc).min_universe()
1027+
self.scc_annotations()[r_scc].min_universe()
9951028
);
9961029
// If the type test requires that `T: 'a` where `'a` is a
9971030
// placeholder from another universe, that effectively requires
@@ -1472,7 +1505,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
14721505
/// The minimum universe of any variable reachable from this
14731506
/// SCC, inside or outside of it.
14741507
fn scc_universe(&self, scc: ConstraintSccIndex) -> UniverseIndex {
1475-
self.constraint_sccs().annotation(scc).min_universe()
1508+
self.scc_annotations()[scc].min_universe()
14761509
}
14771510

14781511
/// Checks the final value for the free region `fr` to see if it
@@ -2219,7 +2252,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
22192252
/// they *must* be equal (though not having the same repr does not
22202253
/// mean they are unequal).
22212254
fn scc_representative(&self, scc: ConstraintSccIndex) -> RegionVid {
2222-
self.constraint_sccs.annotation(scc).representative
2255+
self.scc_annotations()[scc].representative
22232256
}
22242257

22252258
pub(crate) fn liveness_constraints(&self) -> &LivenessValues {

‎compiler/rustc_data_structures/src/graph/scc/mod.rs

Lines changed: 66 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use std::fmt::Debug;
1313
use std::ops::Range;
1414

1515
use rustc_index::{Idx, IndexSlice, IndexVec};
16-
use tracing::{debug, instrument};
16+
use tracing::{debug, instrument, trace};
1717

1818
use crate::fx::FxHashSet;
1919
use crate::graph::vec_graph::VecGraph;
@@ -48,6 +48,20 @@ pub trait Annotation: Debug + Copy {
4848
}
4949
}
5050

51+
/// An accumulator for annotations.
52+
pub trait Annotations<N: Idx, S: Idx, A: Annotation> {
53+
fn new(&self, element: N) -> A;
54+
fn annotate_scc(&mut self, scc: S, annotation: A);
55+
}
56+
57+
/// The nil annotation accumulator, which does nothing.
58+
impl<N: Idx, S: Idx> Annotations<N, S, ()> for () {
59+
fn new(&self, _element: N) -> () {
60+
()
61+
}
62+
fn annotate_scc(&mut self, _scc: S, _annotation: ()) {}
63+
}
64+
5165
/// The empty annotation, which does nothing.
5266
impl Annotation for () {
5367
fn merge_reached(self, _other: Self) -> Self {
@@ -62,23 +76,20 @@ impl Annotation for () {
6276
/// the index type for the graph nodes and `S` is the index type for
6377
/// the SCCs. We can map from each node to the SCC that it
6478
/// participates in, and we also have the successors of each SCC.
65-
pub struct Sccs<N: Idx, S: Idx, A: Annotation = ()> {
79+
pub struct Sccs<N: Idx, S: Idx> {
6680
/// For each node, what is the SCC index of the SCC to which it
6781
/// belongs.
6882
scc_indices: IndexVec<N, S>,
6983

7084
/// Data about all the SCCs.
71-
scc_data: SccData<S, A>,
85+
scc_data: SccData<S>,
7286
}
7387

7488
/// Information about an invidividual SCC node.
75-
struct SccDetails<A: Annotation> {
89+
struct SccDetails {
7690
/// For this SCC, the range of `all_successors` where its
7791
/// successors can be found.
7892
range: Range<usize>,
79-
80-
/// User-specified metadata about the SCC.
81-
annotation: A,
8293
}
8394

8495
// The name of this struct should discourage you from making it public and leaking
@@ -87,35 +98,29 @@ struct SccDetails<A: Annotation> {
8798
// is difficult when it's publicly inspectable.
8899
//
89100
// Obey the law of Demeter!
90-
struct SccData<S: Idx, A: Annotation> {
101+
struct SccData<S: Idx> {
91102
/// Maps SCC indices to their metadata, including
92103
/// offsets into `all_successors`.
93-
scc_details: IndexVec<S, SccDetails<A>>,
104+
scc_details: IndexVec<S, SccDetails>,
94105

95106
/// Contains the successors for all the Sccs, concatenated. The
96107
/// range of indices corresponding to a given SCC is found in its
97108
/// `scc_details.range`.
98109
all_successors: Vec<S>,
99110
}
100111

101-
impl<N: Idx, S: Idx + Ord> Sccs<N, S, ()> {
112+
impl<N: Idx, S: Idx + Ord> Sccs<N, S> {
102113
/// Compute SCCs without annotations.
103114
pub fn new(graph: &impl Successors<Node = N>) -> Self {
104-
Self::new_with_annotation(graph, |_| ())
115+
Self::new_with_annotation(graph, &mut ())
105116
}
106-
}
107117

108-
impl<N: Idx, S: Idx + Ord, A: Annotation> Sccs<N, S, A> {
109118
/// Compute SCCs and annotate them with a user-supplied annotation
110-
pub fn new_with_annotation<F: Fn(N) -> A>(
119+
pub fn new_with_annotation<A: Annotation, AA: Annotations<N, S, A>>(
111120
graph: &impl Successors<Node = N>,
112-
to_annotation: F,
121+
annotations: &mut AA,
113122
) -> Self {
114-
SccsConstruction::construct(graph, to_annotation)
115-
}
116-
117-
pub fn annotation(&self, scc: S) -> A {
118-
self.scc_data.annotation(scc)
123+
SccsConstruction::construct(graph, annotations)
119124
}
120125

121126
pub fn scc_indices(&self) -> &IndexSlice<N, S> {
@@ -136,7 +141,13 @@ impl<N: Idx, S: Idx + Ord, A: Annotation> Sccs<N, S, A> {
136141
pub fn all_sccs(&self) -> impl Iterator<Item = S> + 'static {
137142
(0..self.scc_data.len()).map(S::new)
138143
}
139-
144+
/*
145+
/// Returns an iterator over the SCC annotations in the graph
146+
/// The order is the same as `all_sccs()`, dependency order.
147+
pub fn all_annotations(&self, annotations: &A) -> impl Iterator<Item = (S, A)> + use<'_, N, S, A> {
148+
self.all_sccs().map(|scc| (scc, self.annotation(scc)))
149+
}
150+
*/
140151
/// Returns the SCC to which a node `r` belongs.
141152
pub fn scc(&self, r: N) -> S {
142153
self.scc_indices[r]
@@ -160,27 +171,27 @@ impl<N: Idx, S: Idx + Ord, A: Annotation> Sccs<N, S, A> {
160171
}
161172
}
162173

163-
impl<N: Idx, S: Idx + Ord, A: Annotation> DirectedGraph for Sccs<N, S, A> {
174+
impl<N: Idx, S: Idx + Ord> DirectedGraph for Sccs<N, S> {
164175
type Node = S;
165176

166177
fn num_nodes(&self) -> usize {
167178
self.num_sccs()
168179
}
169180
}
170181

171-
impl<N: Idx, S: Idx + Ord, A: Annotation> NumEdges for Sccs<N, S, A> {
182+
impl<N: Idx, S: Idx + Ord> NumEdges for Sccs<N, S> {
172183
fn num_edges(&self) -> usize {
173184
self.scc_data.all_successors.len()
174185
}
175186
}
176187

177-
impl<N: Idx, S: Idx + Ord, A: Annotation> Successors for Sccs<N, S, A> {
188+
impl<N: Idx, S: Idx + Ord> Successors for Sccs<N, S> {
178189
fn successors(&self, node: S) -> impl Iterator<Item = Self::Node> {
179190
self.successors(node).iter().cloned()
180191
}
181192
}
182193

183-
impl<S: Idx, A: Annotation> SccData<S, A> {
194+
impl<S: Idx> SccData<S> {
184195
/// Number of SCCs,
185196
fn len(&self) -> usize {
186197
self.scc_details.len()
@@ -192,38 +203,32 @@ impl<S: Idx, A: Annotation> SccData<S, A> {
192203
}
193204

194205
/// Creates a new SCC with `successors` as its successors and
195-
/// the maximum weight of its internal nodes `scc_max_weight` and
196206
/// returns the resulting index.
197-
fn create_scc(&mut self, successors: impl IntoIterator<Item = S>, annotation: A) -> S {
207+
fn create_scc(&mut self, successors: impl IntoIterator<Item = S>) -> S {
198208
// Store the successors on `scc_successors_vec`, remembering
199209
// the range of indices.
200210
let all_successors_start = self.all_successors.len();
201211
self.all_successors.extend(successors);
202212
let all_successors_end = self.all_successors.len();
203213

204214
debug!(
205-
"create_scc({:?}) successors={:?}, annotation={:?}",
215+
"create_scc({:?}) successors={:?}",
206216
self.len(),
207217
&self.all_successors[all_successors_start..all_successors_end],
208-
annotation
209218
);
210219

211220
let range = all_successors_start..all_successors_end;
212-
let metadata = SccDetails { range, annotation };
221+
let metadata = SccDetails { range };
213222
self.scc_details.push(metadata)
214223
}
215-
216-
fn annotation(&self, scc: S) -> A {
217-
self.scc_details[scc].annotation
218-
}
219224
}
220225

221-
struct SccsConstruction<'c, G, S, A, F>
226+
struct SccsConstruction<'c, 'a, G, S, A, AA>
222227
where
223228
G: DirectedGraph + Successors,
224229
S: Idx,
225230
A: Annotation,
226-
F: Fn(G::Node) -> A,
231+
AA: Annotations<G::Node, S, A>,
227232
{
228233
graph: &'c G,
229234

@@ -247,11 +252,9 @@ where
247252
/// around between successors to amortize memory allocation costs.
248253
duplicate_set: FxHashSet<S>,
249254

250-
scc_data: SccData<S, A>,
255+
scc_data: SccData<S>,
251256

252-
/// A function that constructs an initial SCC annotation
253-
/// out of a single node.
254-
to_annotation: F,
257+
annotations: &'a mut AA,
255258
}
256259

257260
#[derive(Copy, Clone, Debug)]
@@ -299,12 +302,12 @@ enum WalkReturn<S, A> {
299302
Complete { scc_index: S, annotation: A },
300303
}
301304

302-
impl<'c, G, S, A, F> SccsConstruction<'c, G, S, A, F>
305+
impl<'c, 'a, G, S, A, AA> SccsConstruction<'c, 'a, G, S, A, AA>
303306
where
304307
G: DirectedGraph + Successors,
305308
S: Idx,
306-
F: Fn(G::Node) -> A,
307309
A: Annotation,
310+
AA: Annotations<G::Node, S, A>,
308311
{
309312
/// Identifies SCCs in the graph `G` and computes the resulting
310313
/// DAG. This uses a variant of [Tarjan's
@@ -320,7 +323,7 @@ where
320323
/// Additionally, we keep track of a current annotation of the SCC.
321324
///
322325
/// [wikipedia]: https://bit.ly/2EZIx84
323-
fn construct(graph: &'c G, to_annotation: F) -> Sccs<G::Node, S, A> {
326+
fn construct(graph: &'c G, annotations: &'a mut AA) -> Sccs<G::Node, S> {
324327
let num_nodes = graph.num_nodes();
325328

326329
let mut this = Self {
@@ -330,7 +333,7 @@ where
330333
successors_stack: Vec::new(),
331334
scc_data: SccData { scc_details: IndexVec::new(), all_successors: Vec::new() },
332335
duplicate_set: FxHashSet::default(),
333-
to_annotation,
336+
annotations,
334337
};
335338

336339
let scc_indices = graph
@@ -408,7 +411,7 @@ where
408411
// a potentially derived version of the root state for non-root nodes in the chain.
409412
let (root_state, assigned_state) = {
410413
loop {
411-
debug!("find_state(r = {node:?} in state {:?})", self.node_states[node]);
414+
trace!("find_state(r = {node:?} in state {:?})", self.node_states[node]);
412415
match self.node_states[node] {
413416
// This must have been the first and only state since it is unexplored*;
414417
// no update needed! * Unless there is a bug :')
@@ -482,7 +485,7 @@ where
482485
if previous_node == node {
483486
return root_state;
484487
}
485-
debug!("Compressing {node:?} down to {previous_node:?} with state {assigned_state:?}");
488+
trace!("Compressing {node:?} down to {previous_node:?} with state {assigned_state:?}");
486489

487490
// Update to previous node in the link.
488491
match self.node_states[previous_node] {
@@ -507,9 +510,9 @@ where
507510
/// Call this method when `inspect_node` has returned `None`. Having the
508511
/// caller decide avoids mutual recursion between the two methods and allows
509512
/// us to maintain an allocated stack for nodes on the path between calls.
510-
#[instrument(skip(self, initial), level = "debug")]
513+
#[instrument(skip(self, initial), level = "trace")]
511514
fn walk_unvisited_node(&mut self, initial: G::Node) -> WalkReturn<S, A> {
512-
debug!("Walk unvisited node: {initial:?}");
515+
trace!("Walk unvisited node: {initial:?}");
513516
struct VisitingNodeFrame<G: DirectedGraph, Successors, A> {
514517
node: G::Node,
515518
successors: Option<Successors>,
@@ -537,7 +540,7 @@ where
537540
successors_len: 0,
538541
min_cycle_root: initial,
539542
successor_node: initial,
540-
current_component_annotation: (self.to_annotation)(initial),
543+
current_component_annotation: self.annotations.new(initial),
541544
}];
542545

543546
let mut return_value = None;
@@ -556,19 +559,15 @@ where
556559
let node = *node;
557560
let depth = *depth;
558561

559-
// node is definitely in the current component, add it to the annotation.
560-
if node != initial {
561-
current_component_annotation.update_scc((self.to_annotation)(node));
562-
}
563-
debug!(
562+
trace!(
564563
"Visiting {node:?} at depth {depth:?}, annotation: {current_component_annotation:?}"
565564
);
566565

567566
let successors = match successors {
568567
Some(successors) => successors,
569568
None => {
570569
// This None marks that we still have the initialize this node's frame.
571-
debug!(?depth, ?node);
570+
trace!(?depth, ?node);
572571

573572
debug_assert_matches!(self.node_states[node], NodeState::NotVisited);
574573

@@ -598,7 +597,7 @@ where
598597
return_value.take().into_iter().map(|walk| (*successor_node, Some(walk)));
599598

600599
let successor_walk = successors.map(|successor_node| {
601-
debug!(?node, ?successor_node);
600+
trace!(?node, ?successor_node);
602601
(successor_node, self.inspect_node(successor_node))
603602
});
604603
for (successor_node, walk) in returned_walk.chain(successor_walk) {
@@ -609,13 +608,13 @@ where
609608
min_depth: successor_min_depth,
610609
annotation: successor_annotation,
611610
}) => {
612-
debug!(
611+
trace!(
613612
"Cycle found from {node:?}, minimum depth: {successor_min_depth:?}, annotation: {successor_annotation:?}"
614613
);
615614
// Track the minimum depth we can reach.
616615
assert!(successor_min_depth <= depth);
617616
if successor_min_depth < *min_depth {
618-
debug!(?node, ?successor_min_depth);
617+
trace!(?node, ?successor_min_depth);
619618
*min_depth = successor_min_depth;
620619
*min_cycle_root = successor_node;
621620
}
@@ -627,20 +626,20 @@ where
627626
scc_index: successor_scc_index,
628627
annotation: successor_annotation,
629628
}) => {
630-
debug!(
629+
trace!(
631630
"Complete; {node:?} is root of complete-visited SCC idx {successor_scc_index:?} with annotation {successor_annotation:?}"
632631
);
633632
// Push the completed SCC indices onto
634633
// the `successors_stack` for later.
635-
debug!(?node, ?successor_scc_index);
634+
trace!(?node, ?successor_scc_index);
636635
successors_stack.push(successor_scc_index);
637636
current_component_annotation.update_reachable(successor_annotation);
638637
}
639638
// `node` has no more (direct) successors; search recursively.
640639
None => {
641640
let depth = depth + 1;
642-
debug!("Recursing down into {successor_node:?} at depth {depth:?}");
643-
debug!(?depth, ?successor_node);
641+
trace!("Recursing down into {successor_node:?} at depth {depth:?}");
642+
trace!(?depth, ?successor_node);
644643
// Remember which node the return value will come from.
645644
frame.successor_node = successor_node;
646645
// Start a new stack frame, then step into it.
@@ -652,14 +651,14 @@ where
652651
min_depth: depth,
653652
min_cycle_root: successor_node,
654653
successor_node,
655-
current_component_annotation: (self.to_annotation)(successor_node),
654+
current_component_annotation: self.annotations.new(successor_node),
656655
});
657656
continue 'recurse;
658657
}
659658
}
660659
}
661660

662-
debug!("Finished walk from {node:?} with annotation: {current_component_annotation:?}");
661+
trace!("Finished walk from {node:?} with annotation: {current_component_annotation:?}");
663662

664663
// Completed walk, remove `node` from the stack.
665664
let r = self.node_stack.pop();
@@ -691,8 +690,9 @@ where
691690

692691
debug!("Creating SCC rooted in {node:?} with successor {:?}", frame.successor_node);
693692

694-
let scc_index =
695-
self.scc_data.create_scc(deduplicated_successors, current_component_annotation);
693+
let scc_index = self.scc_data.create_scc(deduplicated_successors);
694+
695+
self.annotations.annotate_scc(scc_index, current_component_annotation);
696696

697697
self.node_states[node] =
698698
NodeState::InCycle { scc_index, annotation: current_component_annotation };

‎compiler/rustc_data_structures/src/graph/scc/tests.rs

Lines changed: 106 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,36 @@ use crate::graph::tests::TestGraph;
55

66
#[derive(Copy, Clone, Debug)]
77
struct MaxReached(usize);
8-
type UsizeSccs = Sccs<usize, usize, ()>;
9-
type MaxReachedSccs = Sccs<usize, usize, MaxReached>;
8+
struct Maxes(IndexVec<usize, MaxReached>, fn(usize) -> usize);
9+
type UsizeSccs = Sccs<usize, usize>;
10+
11+
impl Annotations<usize, usize, MaxReached> for Maxes {
12+
fn new(&self, element: usize) -> MaxReached {
13+
MaxReached(self.1(element))
14+
}
15+
16+
fn annotate_scc(&mut self, scc: usize, annotation: MaxReached) {
17+
let i = self.0.push(annotation);
18+
assert!(i == scc);
19+
}
20+
}
21+
22+
impl Maxes {
23+
fn annotation(&self, scc: usize) -> MaxReached {
24+
self.0[scc]
25+
}
26+
fn new(mapping: fn(usize) -> usize) -> Self {
27+
Self(IndexVec::new(), mapping)
28+
}
29+
}
1030

1131
impl Annotation for MaxReached {
1232
fn merge_scc(self, other: Self) -> Self {
1333
Self(std::cmp::max(other.0, self.0))
1434
}
1535

1636
fn merge_reached(self, other: Self) -> Self {
17-
self.merge_scc(other)
37+
Self(std::cmp::max(other.0, self.0))
1838
}
1939
}
2040

@@ -24,17 +44,29 @@ impl PartialEq<usize> for MaxReached {
2444
}
2545
}
2646

27-
impl MaxReached {
28-
fn from_usize(nr: usize) -> Self {
29-
Self(nr)
30-
}
31-
}
32-
3347
#[derive(Copy, Clone, Debug)]
3448
struct MinMaxIn {
3549
min: usize,
3650
max: usize,
3751
}
52+
struct MinMaxes(IndexVec<usize, MinMaxIn>, fn(usize) -> MinMaxIn);
53+
54+
impl MinMaxes {
55+
fn annotation(&self, scc: usize) -> MinMaxIn {
56+
self.0[scc]
57+
}
58+
}
59+
60+
impl Annotations<usize, usize, MinMaxIn> for MinMaxes {
61+
fn new(&self, element: usize) -> MinMaxIn {
62+
self.1(element)
63+
}
64+
65+
fn annotate_scc(&mut self, scc: usize, annotation: MinMaxIn) {
66+
let i = self.0.push(annotation);
67+
assert!(i == scc);
68+
}
69+
}
3870

3971
impl Annotation for MinMaxIn {
4072
fn merge_scc(self, other: Self) -> Self {
@@ -261,67 +293,68 @@ fn bench_sccc(b: &mut test::Bencher) {
261293
#[test]
262294
fn test_max_self_loop() {
263295
let graph = TestGraph::new(0, &[(0, 0)]);
264-
let sccs: MaxReachedSccs =
265-
Sccs::new_with_annotation(&graph, |n| if n == 0 { MaxReached(17) } else { MaxReached(0) });
266-
assert_eq!(sccs.annotation(0), 17);
296+
let mut annotations = Maxes(IndexVec::new(), |n| if n == 0 { 17 } else { 0 });
297+
Sccs::new_with_annotation(&graph, &mut annotations);
298+
assert_eq!(annotations.0[0], 17);
267299
}
268300

269301
#[test]
270302
fn test_max_branch() {
271303
let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 4)]);
272-
let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, MaxReached::from_usize);
273-
assert_eq!(sccs.annotation(sccs.scc(0)), 4);
274-
assert_eq!(sccs.annotation(sccs.scc(1)), 3);
275-
assert_eq!(sccs.annotation(sccs.scc(2)), 4);
304+
let mut annotations = Maxes(IndexVec::new(), |n| n);
305+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
306+
assert_eq!(annotations.0[sccs.scc(0)], 4);
307+
assert_eq!(annotations.0[sccs.scc(1)], 3);
308+
assert_eq!(annotations.0[sccs.scc(2)], 4);
276309
}
310+
277311
#[test]
278312
fn test_single_cycle_max() {
279313
let graph = TestGraph::new(0, &[(0, 2), (2, 3), (2, 4), (4, 1), (1, 2)]);
280-
let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, MaxReached::from_usize);
281-
assert_eq!(sccs.annotation(sccs.scc(2)), 4);
282-
assert_eq!(sccs.annotation(sccs.scc(0)), 4);
283-
}
284-
285-
#[test]
286-
fn test_simple_cycle_max() {
287-
let graph = TestGraph::new(0, &[(0, 1), (1, 2), (2, 0)]);
288-
let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, MaxReached::from_usize);
289-
assert_eq!(sccs.num_sccs(), 1);
314+
let mut annotations = Maxes(IndexVec::new(), |n| n);
315+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
316+
assert_eq!(annotations.0[sccs.scc(2)], 4);
317+
assert_eq!(annotations.0[sccs.scc(0)], 4);
290318
}
291319

292320
#[test]
293321
fn test_double_cycle_max() {
294322
let graph =
295323
TestGraph::new(0, &[(0, 1), (1, 2), (1, 4), (2, 3), (2, 4), (3, 5), (4, 1), (5, 4)]);
296-
let sccs: MaxReachedSccs =
297-
Sccs::new_with_annotation(&graph, |n| if n == 5 { MaxReached(2) } else { MaxReached(1) });
324+
let mut annotations = Maxes(IndexVec::new(), |n| if n == 5 { 2 } else { 1 });
298325

299-
assert_eq!(sccs.annotation(sccs.scc(0)).0, 2);
326+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
327+
328+
assert_eq!(annotations.0[sccs.scc(0)].0, 2);
300329
}
301330

302331
#[test]
303332
fn test_bug_minimised() {
304333
let graph = TestGraph::new(0, &[(0, 3), (0, 1), (3, 2), (2, 3), (1, 4), (4, 5), (5, 4)]);
305-
let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, |n| match n {
306-
3 => MaxReached(1),
307-
_ => MaxReached(0),
334+
let mut annotations = Maxes(IndexVec::new(), |n| match n {
335+
3 => 1,
336+
_ => 0,
308337
});
309-
assert_eq!(sccs.annotation(sccs.scc(2)), 1);
310-
assert_eq!(sccs.annotation(sccs.scc(1)), 0);
311-
assert_eq!(sccs.annotation(sccs.scc(4)), 0);
338+
339+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
340+
assert_eq!(annotations.annotation(sccs.scc(2)), 1);
341+
assert_eq!(annotations.annotation(sccs.scc(1)), 0);
342+
assert_eq!(annotations.annotation(sccs.scc(4)), 0);
312343
}
313344

314345
#[test]
315346
fn test_bug_max_leak_minimised() {
316347
let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (3, 0), (3, 4), (4, 3)]);
317-
let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, |w| match w {
318-
4 => MaxReached(1),
319-
_ => MaxReached(0),
348+
let mut annotations = Maxes(IndexVec::new(), |w| match w {
349+
4 => 1,
350+
_ => 0,
320351
});
321352

322-
assert_eq!(sccs.annotation(sccs.scc(2)), 0);
323-
assert_eq!(sccs.annotation(sccs.scc(3)), 1);
324-
assert_eq!(sccs.annotation(sccs.scc(0)), 1);
353+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
354+
355+
assert_eq!(annotations.annotation(sccs.scc(2)), 0);
356+
assert_eq!(annotations.annotation(sccs.scc(3)), 1);
357+
assert_eq!(annotations.annotation(sccs.scc(0)), 1);
325358
}
326359

327360
#[test]
@@ -369,48 +402,49 @@ fn test_bug_max_leak() {
369402
(23, 24),
370403
],
371404
);
372-
let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, |w| match w {
373-
22 => MaxReached(1),
374-
24 => MaxReached(2),
375-
27 => MaxReached(2),
376-
_ => MaxReached(0),
405+
let mut annotations = Maxes::new(|w| match w {
406+
22 => 1,
407+
24 => 2,
408+
27 => 2,
409+
_ => 0,
377410
});
378-
379-
assert_eq!(sccs.annotation(sccs.scc(2)), 0);
380-
assert_eq!(sccs.annotation(sccs.scc(7)), 0);
381-
assert_eq!(sccs.annotation(sccs.scc(8)), 2);
382-
assert_eq!(sccs.annotation(sccs.scc(23)), 2);
383-
assert_eq!(sccs.annotation(sccs.scc(3)), 2);
384-
assert_eq!(sccs.annotation(sccs.scc(0)), 2);
411+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
412+
413+
assert_eq!(annotations.annotation(sccs.scc(2)), 0);
414+
assert_eq!(annotations.annotation(sccs.scc(7)), 0);
415+
assert_eq!(annotations.annotation(sccs.scc(8)), 2);
416+
assert_eq!(annotations.annotation(sccs.scc(23)), 2);
417+
assert_eq!(annotations.annotation(sccs.scc(3)), 2);
418+
assert_eq!(annotations.annotation(sccs.scc(0)), 2);
385419
}
386420

387421
#[test]
388422
fn test_bug_max_zero_stick_shape() {
389423
let graph = TestGraph::new(0, &[(0, 1), (1, 2), (2, 3), (3, 2), (3, 4)]);
390-
391-
let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, |w| match w {
392-
4 => MaxReached(1),
393-
_ => MaxReached(0),
424+
let mut annotations = Maxes::new(|w| match w {
425+
4 => 1,
426+
_ => 0,
394427
});
428+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
395429

396-
assert_eq!(sccs.annotation(sccs.scc(0)), 1);
397-
assert_eq!(sccs.annotation(sccs.scc(1)), 1);
398-
assert_eq!(sccs.annotation(sccs.scc(2)), 1);
399-
assert_eq!(sccs.annotation(sccs.scc(3)), 1);
400-
assert_eq!(sccs.annotation(sccs.scc(4)), 1);
430+
assert_eq!(annotations.annotation(sccs.scc(0)), 1);
431+
assert_eq!(annotations.annotation(sccs.scc(1)), 1);
432+
assert_eq!(annotations.annotation(sccs.scc(2)), 1);
433+
assert_eq!(annotations.annotation(sccs.scc(3)), 1);
434+
assert_eq!(annotations.annotation(sccs.scc(4)), 1);
401435
}
402436

403437
#[test]
404438
fn test_min_max_in() {
405439
let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (3, 0), (3, 4), (4, 3), (3, 5)]);
406-
let sccs: Sccs<usize, usize, MinMaxIn> =
407-
Sccs::new_with_annotation(&graph, |w| MinMaxIn { min: w, max: w });
408-
409-
assert_eq!(sccs.annotation(sccs.scc(2)).min, 2);
410-
assert_eq!(sccs.annotation(sccs.scc(2)).max, 2);
411-
assert_eq!(sccs.annotation(sccs.scc(0)).min, 0);
412-
assert_eq!(sccs.annotation(sccs.scc(0)).max, 4);
413-
assert_eq!(sccs.annotation(sccs.scc(3)).min, 0);
414-
assert_eq!(sccs.annotation(sccs.scc(3)).max, 4);
415-
assert_eq!(sccs.annotation(sccs.scc(5)).min, 5);
440+
let mut annotations = MinMaxes(IndexVec::new(), |w| MinMaxIn { min: w, max: w });
441+
let sccs = Sccs::new_with_annotation(&graph, &mut annotations);
442+
443+
assert_eq!(annotations.annotation(sccs.scc(2)).min, 2);
444+
assert_eq!(annotations.annotation(sccs.scc(2)).max, 2);
445+
assert_eq!(annotations.annotation(sccs.scc(0)).min, 0);
446+
assert_eq!(annotations.annotation(sccs.scc(0)).max, 4);
447+
assert_eq!(annotations.annotation(sccs.scc(3)).min, 0);
448+
assert_eq!(annotations.annotation(sccs.scc(3)).max, 4);
449+
assert_eq!(annotations.annotation(sccs.scc(5)).min, 5);
416450
}

0 commit comments

Comments
 (0)
Please sign in to comment.