1use itertools::{Either, Itertools};
2use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
3use rustc_index::interval::IntervalSet;
4use rustc_middle::mir::visit::{TyContext, Visitor};
5use rustc_middle::mir::{Body, Local, Location, SourceInfo};
6use rustc_middle::ty::relate::Relate;
7use rustc_middle::ty::{GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeVisitable};
8use rustc_mir_dataflow::move_paths::MoveData;
9use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex};
10use rustc_span::span_bug;
11use rustc_trait_selection::traits::outlives_for_liveness::FreeRegionsVisitor;
12use tracing::debug;
1314use super::TypeChecker;
15use crate::BorrowckInferCtxt;
16use crate::constraints::OutlivesConstraintSet;
17use crate::polonius::{PoloniusContext, record_live_region_variance};
18use crate::region_infer::values::LivenessValues;
19use crate::universal_regions::UniversalRegions;
2021mod local_use_map;
22mod trace;
2324pub(crate) use local_use_map::LocalUseMap;
25pub(crate) use trace::LivenessComputation;
2627/// Combines liveness analysis with initialization analysis to
28/// determine which variables are live at which points, both due to
29/// ordinary uses and drops. Returns a set of (ty, location) pairs
30/// that indicate which types must be live at which point in the CFG.
31/// This vector is consumed by `constraint_generation`.
32///
33/// N.B., this computation requires normalization; therefore, it must be
34/// performed before
35pub(super) fn generate<'tcx>(
36 typeck: &mut TypeChecker<'_, 'tcx>,
37 location_map: &DenseLocationMap,
38 move_data: &MoveData<'tcx>,
39) {
40{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs:40",
"rustc_borrowck::type_check::liveness",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs"),
::tracing_core::__macro_support::Option::Some(40u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::liveness"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("liveness::generate")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("liveness::generate");
41let _timer = typeck.tcx().prof.generic_activity("borrowck_liveness");
4243// Universal regions are live at every point.
44for region in typeck.universal_regions.universal_regions_iter() {
45 typeck.constraints.liveness_constraints.add_all_points(region);
46 }
4748let free_regions = regions_that_outlive_free_regions(
49typeck.infcx.num_region_vars(),
50&typeck.universal_regions,
51&typeck.constraints.outlives_constraints,
52 );
5354let (relevant_live_locals, boring_locals) =
55compute_relevant_live_locals(typeck.tcx(), &free_regions, typeck.body);
5657// Under Polonius Alpha, a larger set of locals are considered relevant: specifically,
58 // locals containing regions *outliving* universal regions are relevant and only
59 // locals containing solely universal regions are considered boring.
60 //
61 // However, we don't actually need liveness information for *all* these locals,
62 // only when actually computing loans. So, we can defer computing the liveness
63 // until we try to propagate the loan, which is gated on `LocalizedConstraintGraph`
64 // traversal.
65 //
66 // Potentially in theory, we could defer computing liveness for *all* locals,
67 // but that's a much bigger refactor (many things rely on liveness of
68 // NLL-relevant locals). So, we only defer NLL-boring/Polonius-relevant locals
69 // for now.
70 // FIXME: this NLL optimization idea, to reduce work to relevant locals only, still makes sense
71 // for polonius, and should be investigated to improve liveness performance.
72let deferred_locals = if typeck.polonius_context.is_none() || typeck.borrow_set.len() == 0 {
73// If we aren't going to be using the additional liveness information,
74 // don't even bother computing the larger relevant set.
75 // Similarly, since this liveness information is ultimately used for *loan*
76 // liveness, we don't need to compute it when there are no loans.
77FxIndexSet::default()
78 } else {
79// As described above, we can defer computing liveness for the regions that are
80 // NLL-boring-and-polonius-relevant. Let's find these.
81 //
82 // Note that this is basically a simplified version of `compute_relevant_live_locals`
83 // avoiding the allocations that are unnecessary in our more limited use-case.
84let tcx = typeck.tcx();
85let universal_regions = typeck.universal_regions;
86let boring_nll_locals: FxHashSet<_> = boring_locals.iter().copied().collect();
87let deferred_polonius_locals = typeck88 .body
89 .local_decls
90 .iter_enumerated()
91 .filter_map(|(local, decl)| {
92// The polonius-relevant locals are the ones whose types do not only contain
93 // universal regions.
94if boring_nll_locals.contains(&local)
95 && !tcx.all_free_regions_meet(&decl.ty, |r| {
96universal_regions.is_universal_region(r.as_var())
97 })
98 {
99Some(local)
100 } else {
101None102 }
103 })
104 .collect();
105106typeck.polonius_context.as_mut().unwrap().boring_nll_locals = boring_nll_locals;
107deferred_polonius_locals108 };
109110 trace::trace(
111typeck,
112location_map,
113move_data,
114&relevant_live_locals,
115&boring_locals,
116&deferred_locals,
117 );
118119// Mark regions that should be live where they appear within rvalues or within a call: like
120 // args, regions, and types.
121record_regular_live_regions(
122typeck.tcx(),
123&mut typeck.constraints.liveness_constraints,
124&typeck.universal_regions,
125&mut typeck.polonius_context,
126typeck.body,
127 );
128}
129130// The purpose of `compute_relevant_live_locals` is to define the subset of `Local`
131// variables for which we need to do a liveness computation. We only need
132// to compute whether a variable `X` is live if that variable contains
133// some region `R` in its type where `R` is not known to outlive a free
134// region (i.e., where `R` may be valid for just a subset of the fn body).
135fn compute_relevant_live_locals<'tcx>(
136 tcx: TyCtxt<'tcx>,
137 free_regions: &FxHashSet<RegionVid>,
138 body: &Body<'tcx>,
139) -> (Vec<Local>, Vec<Local>) {
140let (boring_locals, relevant_live_locals): (Vec<_>, Vec<_>) =
141body.local_decls.iter_enumerated().partition_map(|(local, local_decl)| {
142if tcx.all_free_regions_meet(&local_decl.ty, |r| free_regions.contains(&r.as_var())) {
143 Either::Left(local)
144 } else {
145 Either::Right(local)
146 }
147 });
148149{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs:149",
"rustc_borrowck::type_check::liveness",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs"),
::tracing_core::__macro_support::Option::Some(149u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::liveness"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} total variables",
body.local_decls.len()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("{} total variables", body.local_decls.len());
150{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs:150",
"rustc_borrowck::type_check::liveness",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs"),
::tracing_core::__macro_support::Option::Some(150u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::liveness"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} variables need liveness",
relevant_live_locals.len()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("{} variables need liveness", relevant_live_locals.len());
151{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs:151",
"rustc_borrowck::type_check::liveness",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs"),
::tracing_core::__macro_support::Option::Some(151u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::liveness"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} regions outlive free regions",
free_regions.len()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("{} regions outlive free regions", free_regions.len());
152153 (relevant_live_locals, boring_locals)
154}
155156/// Computes all regions that are (currently) known to outlive free
157/// regions. For these regions, we do not need to compute
158/// liveness, since the outlives constraints will ensure that they
159/// are live over the whole fn body anyhow.
160fn regions_that_outlive_free_regions<'tcx>(
161 num_region_vars: usize,
162 universal_regions: &UniversalRegions<'tcx>,
163 constraint_set: &OutlivesConstraintSet<'tcx>,
164) -> FxHashSet<RegionVid> {
165// Build a graph of the outlives constraints thus far. This is
166 // a reverse graph, so for each constraint `R1: R2` we have an
167 // edge `R2 -> R1`. Therefore, if we find all regions
168 // reachable from each free region, we will have all the
169 // regions that are forced to outlive some free region.
170let rev_constraint_graph = constraint_set.reverse_graph(num_region_vars);
171let fr_static = universal_regions.fr_static;
172let rev_region_graph = rev_constraint_graph.region_graph(constraint_set, fr_static);
173174// Stack for the depth-first search. Start out with all the free regions.
175let mut stack: Vec<_> = universal_regions.universal_regions_iter().collect();
176177// Set of all free regions, plus anything that outlives them. Initially
178 // just contains the free regions.
179let mut outlives_free_region: FxHashSet<_> = stack.iter().cloned().collect();
180181// Do the DFS -- for each thing in the stack, find all things
182 // that outlive it and add them to the set. If they are not,
183 // push them onto the stack for later.
184while let Some(sub_region) = stack.pop() {
185 stack.extend(
186 rev_region_graph
187 .outgoing_regions(sub_region)
188 .filter(|&r| outlives_free_region.insert(r)),
189 );
190 }
191192// Return the final set of things we visited.
193outlives_free_region194}
195196/// Some variables are "regular live" at `location` -- i.e., they may be used later. This means that
197/// all regions appearing in their type must be live at `location`.
198fn record_regular_live_regions<'tcx>(
199 tcx: TyCtxt<'tcx>,
200 liveness_constraints: &mut LivenessValues,
201 universal_regions: &UniversalRegions<'tcx>,
202 polonius_context: &mut Option<PoloniusContext<'tcx>>,
203 body: &Body<'tcx>,
204) {
205let mut visitor =
206LiveVariablesVisitor { tcx, liveness_constraints, universal_regions, polonius_context };
207for (bb, data) in body.basic_blocks.iter_enumerated() {
208 visitor.visit_basic_block_data(bb, data);
209 }
210}
211212/// Visitor looking for regions that should be live within rvalues or calls.
213struct LiveVariablesVisitor<'a, 'tcx> {
214 tcx: TyCtxt<'tcx>,
215 liveness_constraints: &'a mut LivenessValues,
216 universal_regions: &'a UniversalRegions<'tcx>,
217 polonius_context: &'a mut Option<PoloniusContext<'tcx>>,
218}
219220impl<'a, 'tcx> Visitor<'tcx> for LiveVariablesVisitor<'a, 'tcx> {
221/// We sometimes have `args` within an rvalue, or within a
222 /// call. Make them live at the location where they appear.
223fn visit_args(&mut self, args: &GenericArgs<'tcx>, location: Location) {
224self.record_regions_live_at(*args, location);
225self.super_args(args);
226 }
227228/// We sometimes have `region`s within an rvalue, or within a
229 /// call. Make them live at the location where they appear.
230fn visit_region(&mut self, region: Region<'tcx>, location: Location) {
231self.record_regions_live_at(region, location);
232self.super_region(region);
233 }
234235/// We sometimes have `ty`s within an rvalue, or within a
236 /// call. Make them live at the location where they appear.
237fn visit_ty(&mut self, ty: Ty<'tcx>, ty_context: TyContext) {
238match ty_context {
239 TyContext::ReturnTy(SourceInfo { span, .. })
240 | TyContext::YieldTy(SourceInfo { span, .. })
241 | TyContext::ResumeTy(SourceInfo { span, .. })
242 | TyContext::UserTy(span)
243 | TyContext::LocalDecl { source_info: SourceInfo { span, .. }, .. } => {
244::rustc_span::macros::bug_impl(Some(span),
format_args!("should not be visiting outside of the CFG: {0:?}",
ty_context), Location::caller());span_bug!(span, "should not be visiting outside of the CFG: {:?}", ty_context);
245 }
246 TyContext::Location(location) => {
247self.record_regions_live_at(ty, location);
248 }
249 }
250251self.super_ty(ty);
252 }
253}
254255impl<'a, 'tcx> LiveVariablesVisitor<'a, 'tcx> {
256/// Some variable is "regular live" at `location` -- i.e., it may be used later. This means that
257 /// all regions appearing in the type of `value` must be live at `location`.
258fn record_regions_live_at<T>(&mut self, value: T, location: Location)
259where
260T: TypeVisitable<TyCtxt<'tcx>> + Relate<TyCtxt<'tcx>>,
261 {
262{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs:262",
"rustc_borrowck::type_check::liveness",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs"),
::tracing_core::__macro_support::Option::Some(262u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::liveness"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("record_regions_live_at(value={0:?}, location={1:?})",
value, location) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("record_regions_live_at(value={:?}, location={:?})", value, location);
263self.tcx.for_each_free_region(&value, |live_region| {
264let live_region_vid = live_region.as_var();
265self.liveness_constraints.add_location(live_region_vid, location);
266 });
267268// When using `-Zpolonius=next`, we record the variance of each live region.
269if let Some(polonius_context) = self.polonius_context {
270record_live_region_variance(
271self.tcx,
272&mut polonius_context.live_region_variances,
273self.universal_regions,
274value,
275 );
276 }
277 }
278}
279280pub(crate) fn make_all_regions_live<'tcx>(
281 infcx: &BorrowckInferCtxt<'tcx>,
282 universal_regions: &UniversalRegions<'tcx>,
283 liveness: &mut LivenessValues,
284 value: impl TypeVisitable<TyCtxt<'tcx>>,
285 live_at: &IntervalSet<PointIndex>,
286) {
287{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs:287",
"rustc_borrowck::type_check::liveness",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_borrowck/src/type_check/liveness/mod.rs"),
::tracing_core::__macro_support::Option::Some(287u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check::liveness"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_all_regions_live(value={0:?})",
value) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("make_all_regions_live(value={value:?})");
288value.visit_with(&mut FreeRegionsVisitor {
289 tcx: infcx.tcx,
290 param_env: infcx.param_env,
291 op: |r| liveness.add_points(universal_regions.to_region_vid(r), live_at),
292 });
293}