rustc_borrowck/polonius/mod.rs
1//! Polonius analysis and support code:
2//! - dedicated constraints
3//! - conversion from NLL constraints
4//! - debugging utilities
5//! - etc.
6//!
7//! The current implementation models the flow-sensitive borrow-checking concerns as a graph
8//! containing both information about regions and information about the control flow.
9//!
10//! Loan propagation is seen as a reachability problem (with some subtleties) between where the loan
11//! is introduced and a given point.
12//!
13//! Constraints arising from type-checking allow loans to flow from region to region at the same CFG
14//! point. Constraints arising from liveness allow loans to flow within from point to point, between
15//! live regions at these points.
16//!
17//! Edges can be bidirectional to encode invariant relationships, and loans can flow "back in time"
18//! to traverse these constraints arising earlier in the CFG.
19//!
20//! When incorporating kills in the traversal, the loans reaching a given point are considered live.
21//!
22//! After this, the usual NLL process happens. These live loans are fed into a dataflow analysis
23//! combining them with the points where loans go out of NLL scope (the frontier where they stop
24//! propagating to a live region), to yield the "loans in scope" or "active loans", at a given
25//! point.
26//!
27//! Illegal accesses are still computed by checking whether one of these resulting loans is
28//! invalidated.
29//!
30//! More information on this simple approach can be found in the following links, and in the future
31//! in the rustc dev guide:
32//! - <https://smallcultfollowing.com/babysteps/blog/2023/09/22/polonius-part-1/>
33//! - <https://smallcultfollowing.com/babysteps/blog/2023/09/29/polonius-part-2/>
34//!
35
36mod constraints;
37mod dump;
38pub(crate) mod legacy;
39mod liveness_constraints;
40
41use std::collections::BTreeMap;
42
43use rustc_data_structures::fx::FxHashSet;
44use rustc_index::bit_set::DenseBitSet;
45use rustc_middle::mir::{Body, Local};
46use rustc_middle::ty::RegionVid;
47use rustc_mir_dataflow::points::PointIndex;
48
49pub(self) use self::constraints::*;
50pub(crate) use self::dump::dump_polonius_mir;
51pub(crate) use self::liveness_constraints::record_live_region_variance;
52use crate::BorrowSet;
53use crate::constraints::OutlivesConstraint;
54use crate::dataflow::BorrowIndex;
55use crate::region_infer::values::LivenessValues;
56use crate::universal_regions::UniversalRegions;
57
58#[derive(Clone)]
59pub(crate) struct LiveLoans {
60 num_points: usize,
61 // This matrix always has more rows (PointIndex) than columns (BorrowIndex),
62 // and the borrow dimension is usually very low (single digit in 90% of cases in our benchmark suite),
63 // so we store it packed in a single bitset. Rows are points, columns are borrows.
64 flat_matrix: DenseBitSet<usize>,
65}
66
67impl LiveLoans {
68 pub(crate) fn new(num_points: usize, num_borrows: usize) -> Self {
69 Self { num_points, flat_matrix: DenseBitSet::new_empty(num_points * num_borrows) }
70 }
71 pub(crate) fn insert(&mut self, row: PointIndex, col: BorrowIndex) {
72 let bit_index = row.index() + self.num_points * col.index();
73 self.flat_matrix.insert(bit_index);
74 }
75 pub(crate) fn contains(&self, row: PointIndex, col: BorrowIndex) -> bool {
76 let bit_index = row.index() + self.num_points * col.index();
77 self.flat_matrix.contains(bit_index)
78 }
79}
80
81/// This struct holds the necessary
82/// - liveness data, created during MIR typeck, and which will be used to lazily compute the
83/// polonius localized constraints, during NLL region inference as well as MIR dumping,
84/// - data needed by the borrowck error computation and diagnostics.
85#[derive(Default)]
86pub(crate) struct PoloniusContext {
87 /// The graph from which we extract the localized outlives constraints.
88 graph: Option<LocalizedConstraintGraph>,
89
90 /// The expected edge direction per live region: the kind of directed edge we'll create as
91 /// liveness constraints depends on the variance of types with respect to each contained region.
92 pub(crate) live_region_variances: BTreeMap<RegionVid, ConstraintDirection>,
93
94 /// The regions that outlive free regions are used to distinguish relevant live locals from
95 /// boring locals. A boring local is one whose type contains only such regions. Polonius
96 /// currently has more boring locals than NLLs so we record the latter to use in errors and
97 /// diagnostics, to focus on the locals we consider relevant and match NLL diagnostics.
98 pub(crate) boring_nll_locals: FxHashSet<Local>,
99}
100
101/// The direction a constraint can flow into. Used to create liveness constraints according to
102/// variance.
103#[derive(Copy, Clone, PartialEq, Eq, Debug)]
104pub(crate) enum ConstraintDirection {
105 /// For covariant cases, we add a forward edge `O at P1 -> O at P2`.
106 Forward,
107
108 /// For contravariant cases, we add a backward edge `O at P2 -> O at P1`
109 Backward,
110
111 /// For invariant cases, we add both the forward and backward edges `O at P1 <-> O at P2`.
112 Bidirectional,
113}
114
115impl PoloniusContext {
116 /// Computes live loans using the set of loans model for `-Zpolonius=next`.
117 ///
118 /// First, creates a constraint graph combining regions and CFG points, by:
119 /// - converting NLL typeck constraints to be localized
120 /// - encoding liveness constraints
121 ///
122 /// Then, this graph is traversed, reachability is recorded as loan liveness, to be used by the
123 /// loan scope and active loans computations.
124 ///
125 /// The constraint data will be used to compute errors and diagnostics.
126 pub(crate) fn compute_loan_liveness<'tcx>(
127 &mut self,
128 liveness: &mut LivenessValues,
129 outlives_constraints: impl Iterator<Item = OutlivesConstraint<'tcx>>,
130 universal_regions: &UniversalRegions<'tcx>,
131 body: &Body<'tcx>,
132 borrow_set: &BorrowSet<'tcx>,
133 num_points: usize,
134 ) {
135 // We don't need to prepare the graph (index NLL constraints, etc.) if we have no loans to
136 // trace throughout localized constraints.
137 if borrow_set.len() > 0 {
138 // From the outlives constraints, liveness, and variances, we can compute reachability
139 // on the lazy localized constraint graph to trace the liveness of loans, for the next
140 // step in the chain (the NLL loan scope and active loans computations).
141 let graph = LocalizedConstraintGraph::new(liveness, outlives_constraints);
142
143 let mut live_loans = LiveLoans::new(num_points, borrow_set.len());
144 let mut visitor = LoanLivenessVisitor { liveness, live_loans: &mut live_loans };
145 graph.traverse(
146 body,
147 liveness,
148 &self.live_region_variances,
149 universal_regions,
150 borrow_set,
151 &mut visitor,
152 );
153 liveness.record_live_loans(live_loans);
154
155 // The graph can be traversed again during MIR dumping, so we store it here.
156 self.graph = Some(graph);
157 }
158 }
159}
160
161/// Visitor to record loan liveness when traversing the localized constraint graph.
162struct LoanLivenessVisitor<'a> {
163 liveness: &'a LivenessValues,
164 live_loans: &'a mut LiveLoans,
165}
166
167impl LocalizedConstraintGraphVisitor for LoanLivenessVisitor<'_> {
168 fn on_node_traversed(&mut self, loan: BorrowIndex, node: LocalizedNode) {
169 // Record the loan as being live on entry to this point if it reaches a live region
170 // there.
171 //
172 // This is an approximation of liveness (which is the thing we want), in that we're
173 // using a single notion of reachability to represent what used to be _two_ different
174 // transitive closures. It didn't seem impactful when coming up with the single-graph
175 // and reachability through space (regions) + time (CFG) concepts, but in practice the
176 // combination of time-traveling with kills is more impactful than initially
177 // anticipated.
178 //
179 // Kills should prevent a loan from reaching its successor points in the CFG, but not
180 // while time-traveling: we're not actually at that CFG point, but looking for
181 // predecessor regions that contain the loan. One of the two TCs we had pushed the
182 // transitive subset edges to each point instead of having backward edges, and the
183 // problem didn't exist before. In the abstract, naive reachability is not enough to
184 // model this, we'd need a slightly different solution. For example, maybe with a
185 // two-step traversal:
186 // - at each point we first traverse the subgraph (and possibly time-travel) looking for
187 // exit nodes while ignoring kills,
188 // - and then when we're back at the current point, we continue normally.
189 //
190 // Another (less annoying) subtlety is that kills and the loan use-map are
191 // flow-insensitive. Kills can actually appear in places before a loan is introduced, or
192 // at a location that is actually unreachable in the CFG from the introduction point,
193 // and these can also be encountered during time-traveling.
194 //
195 // The simplest change that made sense to "fix" the issues above is taking into account
196 // kills that are:
197 // - reachable from the introduction point
198 // - encountered during forward traversal. Note that this is not transitive like the
199 // two-step traversal described above: only kills encountered on exit via a backward
200 // edge are ignored.
201 //
202 // This version of the analysis, however, is enough in practice to pass the tests that
203 // we care about and NLLs reject, without regressions on crater, and is an actionable
204 // subset of the full analysis. It also naturally points to areas of improvement that we
205 // wish to explore later, namely handling kills appropriately during traversal, instead
206 // of continuing traversal to all the reachable nodes.
207 //
208 // FIXME: analyze potential unsoundness, possibly in concert with a borrowck
209 // implementation in a-mir-formality, fuzzing, or manually crafting counter-examples.
210 if self.liveness.is_live_at_point(node.region, node.point) {
211 self.live_loans.insert(node.point, loan);
212 }
213 }
214}