rustc_borrowck/type_check/liveness/
mod.rs

1use itertools::{Either, Itertools};
2use rustc_data_structures::fx::FxHashSet;
3use rustc_middle::mir::visit::{TyContext, Visitor};
4use rustc_middle::mir::{Body, Local, Location, SourceInfo};
5use rustc_middle::span_bug;
6use rustc_middle::ty::relate::Relate;
7use rustc_middle::ty::visit::TypeVisitable;
8use rustc_middle::ty::{GenericArgsRef, Region, RegionVid, Ty, TyCtxt};
9use rustc_mir_dataflow::ResultsCursor;
10use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
11use rustc_mir_dataflow::move_paths::MoveData;
12use rustc_mir_dataflow::points::DenseLocationMap;
13use tracing::debug;
14
15use super::TypeChecker;
16use crate::constraints::OutlivesConstraintSet;
17use crate::polonius::PoloniusLivenessContext;
18use crate::region_infer::values::LivenessValues;
19use crate::universal_regions::UniversalRegions;
20
21mod local_use_map;
22mod trace;
23
24/// Combines liveness analysis with initialization analysis to
25/// determine which variables are live at which points, both due to
26/// ordinary uses and drops. Returns a set of (ty, location) pairs
27/// that indicate which types must be live at which point in the CFG.
28/// This vector is consumed by `constraint_generation`.
29///
30/// N.B., this computation requires normalization; therefore, it must be
31/// performed before
32pub(super) fn generate<'a, 'tcx>(
33    typeck: &mut TypeChecker<'_, 'tcx>,
34    body: &Body<'tcx>,
35    location_map: &DenseLocationMap,
36    flow_inits: ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
37    move_data: &MoveData<'tcx>,
38) {
39    debug!("liveness::generate");
40
41    let mut free_regions = regions_that_outlive_free_regions(
42        typeck.infcx.num_region_vars(),
43        &typeck.universal_regions,
44        &typeck.constraints.outlives_constraints,
45    );
46
47    // NLLs can avoid computing some liveness data here because its constraints are
48    // location-insensitive, but that doesn't work in polonius: locals whose type contains a region
49    // that outlives a free region are not necessarily live everywhere in a flow-sensitive setting,
50    // unlike NLLs.
51    // We do record these regions in the polonius context, since they're used to differentiate
52    // relevant and boring locals, which is a key distinction used later in diagnostics.
53    if typeck.tcx().sess.opts.unstable_opts.polonius.is_next_enabled() {
54        let (_, boring_locals) = compute_relevant_live_locals(typeck.tcx(), &free_regions, body);
55        typeck.polonius_liveness.as_mut().unwrap().boring_nll_locals =
56            boring_locals.into_iter().collect();
57        free_regions = typeck.universal_regions.universal_regions_iter().collect();
58    }
59    let (relevant_live_locals, boring_locals) =
60        compute_relevant_live_locals(typeck.tcx(), &free_regions, body);
61
62    trace::trace(
63        typeck,
64        body,
65        location_map,
66        flow_inits,
67        move_data,
68        relevant_live_locals,
69        boring_locals,
70    );
71
72    // Mark regions that should be live where they appear within rvalues or within a call: like
73    // args, regions, and types.
74    record_regular_live_regions(
75        typeck.tcx(),
76        &mut typeck.constraints.liveness_constraints,
77        &typeck.universal_regions,
78        &mut typeck.polonius_liveness,
79        body,
80    );
81}
82
83// The purpose of `compute_relevant_live_locals` is to define the subset of `Local`
84// variables for which we need to do a liveness computation. We only need
85// to compute whether a variable `X` is live if that variable contains
86// some region `R` in its type where `R` is not known to outlive a free
87// region (i.e., where `R` may be valid for just a subset of the fn body).
88fn compute_relevant_live_locals<'tcx>(
89    tcx: TyCtxt<'tcx>,
90    free_regions: &FxHashSet<RegionVid>,
91    body: &Body<'tcx>,
92) -> (Vec<Local>, Vec<Local>) {
93    let (boring_locals, relevant_live_locals): (Vec<_>, Vec<_>) =
94        body.local_decls.iter_enumerated().partition_map(|(local, local_decl)| {
95            if tcx.all_free_regions_meet(&local_decl.ty, |r| free_regions.contains(&r.as_var())) {
96                Either::Left(local)
97            } else {
98                Either::Right(local)
99            }
100        });
101
102    debug!("{} total variables", body.local_decls.len());
103    debug!("{} variables need liveness", relevant_live_locals.len());
104    debug!("{} regions outlive free regions", free_regions.len());
105
106    (relevant_live_locals, boring_locals)
107}
108
109/// Computes all regions that are (currently) known to outlive free
110/// regions. For these regions, we do not need to compute
111/// liveness, since the outlives constraints will ensure that they
112/// are live over the whole fn body anyhow.
113fn regions_that_outlive_free_regions<'tcx>(
114    num_region_vars: usize,
115    universal_regions: &UniversalRegions<'tcx>,
116    constraint_set: &OutlivesConstraintSet<'tcx>,
117) -> FxHashSet<RegionVid> {
118    // Build a graph of the outlives constraints thus far. This is
119    // a reverse graph, so for each constraint `R1: R2` we have an
120    // edge `R2 -> R1`. Therefore, if we find all regions
121    // reachable from each free region, we will have all the
122    // regions that are forced to outlive some free region.
123    let rev_constraint_graph = constraint_set.reverse_graph(num_region_vars);
124    let fr_static = universal_regions.fr_static;
125    let rev_region_graph = rev_constraint_graph.region_graph(constraint_set, fr_static);
126
127    // Stack for the depth-first search. Start out with all the free regions.
128    let mut stack: Vec<_> = universal_regions.universal_regions_iter().collect();
129
130    // Set of all free regions, plus anything that outlives them. Initially
131    // just contains the free regions.
132    let mut outlives_free_region: FxHashSet<_> = stack.iter().cloned().collect();
133
134    // Do the DFS -- for each thing in the stack, find all things
135    // that outlive it and add them to the set. If they are not,
136    // push them onto the stack for later.
137    while let Some(sub_region) = stack.pop() {
138        stack.extend(
139            rev_region_graph
140                .outgoing_regions(sub_region)
141                .filter(|&r| outlives_free_region.insert(r)),
142        );
143    }
144
145    // Return the final set of things we visited.
146    outlives_free_region
147}
148
149/// Some variables are "regular live" at `location` -- i.e., they may be used later. This means that
150/// all regions appearing in their type must be live at `location`.
151fn record_regular_live_regions<'tcx>(
152    tcx: TyCtxt<'tcx>,
153    liveness_constraints: &mut LivenessValues,
154    universal_regions: &UniversalRegions<'tcx>,
155    polonius_liveness: &mut Option<PoloniusLivenessContext>,
156    body: &Body<'tcx>,
157) {
158    let mut visitor =
159        LiveVariablesVisitor { tcx, liveness_constraints, universal_regions, polonius_liveness };
160    for (bb, data) in body.basic_blocks.iter_enumerated() {
161        visitor.visit_basic_block_data(bb, data);
162    }
163}
164
165/// Visitor looking for regions that should be live within rvalues or calls.
166struct LiveVariablesVisitor<'a, 'tcx> {
167    tcx: TyCtxt<'tcx>,
168    liveness_constraints: &'a mut LivenessValues,
169    universal_regions: &'a UniversalRegions<'tcx>,
170    polonius_liveness: &'a mut Option<PoloniusLivenessContext>,
171}
172
173impl<'a, 'tcx> Visitor<'tcx> for LiveVariablesVisitor<'a, 'tcx> {
174    /// We sometimes have `args` within an rvalue, or within a
175    /// call. Make them live at the location where they appear.
176    fn visit_args(&mut self, args: &GenericArgsRef<'tcx>, location: Location) {
177        self.record_regions_live_at(*args, location);
178        self.super_args(args);
179    }
180
181    /// We sometimes have `region`s within an rvalue, or within a
182    /// call. Make them live at the location where they appear.
183    fn visit_region(&mut self, region: Region<'tcx>, location: Location) {
184        self.record_regions_live_at(region, location);
185        self.super_region(region);
186    }
187
188    /// We sometimes have `ty`s within an rvalue, or within a
189    /// call. Make them live at the location where they appear.
190    fn visit_ty(&mut self, ty: Ty<'tcx>, ty_context: TyContext) {
191        match ty_context {
192            TyContext::ReturnTy(SourceInfo { span, .. })
193            | TyContext::YieldTy(SourceInfo { span, .. })
194            | TyContext::ResumeTy(SourceInfo { span, .. })
195            | TyContext::UserTy(span)
196            | TyContext::LocalDecl { source_info: SourceInfo { span, .. }, .. } => {
197                span_bug!(span, "should not be visiting outside of the CFG: {:?}", ty_context);
198            }
199            TyContext::Location(location) => {
200                self.record_regions_live_at(ty, location);
201            }
202        }
203
204        self.super_ty(ty);
205    }
206}
207
208impl<'a, 'tcx> LiveVariablesVisitor<'a, 'tcx> {
209    /// Some variable is "regular live" at `location` -- i.e., it may be used later. This means that
210    /// all regions appearing in the type of `value` must be live at `location`.
211    fn record_regions_live_at<T>(&mut self, value: T, location: Location)
212    where
213        T: TypeVisitable<TyCtxt<'tcx>> + Relate<TyCtxt<'tcx>>,
214    {
215        debug!("record_regions_live_at(value={:?}, location={:?})", value, location);
216        self.tcx.for_each_free_region(&value, |live_region| {
217            let live_region_vid = live_region.as_var();
218            self.liveness_constraints.add_location(live_region_vid, location);
219        });
220
221        // When using `-Zpolonius=next`, we record the variance of each live region.
222        if let Some(polonius_liveness) = self.polonius_liveness {
223            polonius_liveness.record_live_region_variance(self.tcx, self.universal_regions, value);
224        }
225    }
226}