Skip to content

Commit 388071a

Browse files
JonasAlaifvoidc
authored andcommitted
Allow consumers to retrieve borrowck output
1 parent cda5bec commit 388071a

File tree

7 files changed

+111
-48
lines changed

7 files changed

+111
-48
lines changed

compiler/rustc_borrowck/src/borrow_set.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub struct BorrowSet<'tcx> {
3030
/// Map from local to all the borrows on that local.
3131
pub local_map: FxIndexMap<mir::Local, FxIndexSet<BorrowIndex>>,
3232

33-
pub(crate) locals_state_at_exit: LocalsStateAtExit,
33+
pub locals_state_at_exit: LocalsStateAtExit,
3434
}
3535

3636
impl<'tcx> Index<BorrowIndex> for BorrowSet<'tcx> {
@@ -153,7 +153,7 @@ impl<'tcx> BorrowSet<'tcx> {
153153
self.activation_map.get(&location).map_or(&[], |activations| &activations[..])
154154
}
155155

156-
pub(crate) fn len(&self) -> usize {
156+
pub fn len(&self) -> usize {
157157
self.location_map.len()
158158
}
159159

compiler/rustc_borrowck/src/consumers.rs

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,56 @@ use rustc_middle::mir::Body;
99
use rustc_middle::ty::TyCtxt;
1010

1111
pub use super::{
12+
dataflow::{calculate_borrows_out_of_scope_at_location, BorrowIndex, Borrows},
1213
facts::{AllFacts as PoloniusInput, RustcFacts},
1314
location::{LocationTable, RichLocation},
1415
nll::PoloniusOutput,
16+
region_infer::RegionInferenceContext,
1517
BodyWithBorrowckFacts,
1618
};
1719

18-
/// This function computes Polonius facts for the given body. It makes a copy of
19-
/// the body because it needs to regenerate the region identifiers. This function
20-
/// should never be invoked during a typical compilation session due to performance
21-
/// issues with Polonius.
20+
/// Options determining the output behavior of [`get_body_with_borrowck_facts`].
21+
///
22+
/// If executing under `-Z polonius` the choice here has no effect, and everything as if
23+
/// [`PoloniusOutputFacts`](ConsumerOptions::PoloniusOutputFacts) had been selected
24+
/// will be retrieved.
25+
#[derive(Debug, Copy, Clone)]
26+
pub enum ConsumerOptions {
27+
/// Retrieve the [`Body`] along with the [`BorrowSet`](super::borrow_set::BorrowSet)
28+
/// and [`RegionInferenceContext`]. If you would like the body only, use
29+
/// [`TyCtxt::mir_promoted`].
30+
///
31+
/// These can be used in conjunction with [`calculate_borrows_out_of_scope_at_location`].
32+
RegionInferenceContext,
33+
/// The recommended option. Retrieves the maximal amount of information
34+
/// without significant slowdowns.
35+
///
36+
/// Implies [`RegionInferenceContext`](ConsumerOptions::RegionInferenceContext),
37+
/// and additionally retrieve the [`LocationTable`] and [`PoloniusInput`] that
38+
/// would be given to Polonius. Critically, this does not run Polonius, which
39+
/// one may want to avoid due to performance issues on large bodies.
40+
PoloniusInputFacts,
41+
/// Implies [`PoloniusInputFacts`](ConsumerOptions::PoloniusInputFacts),
42+
/// and additionally runs Polonius to calculate the [`PoloniusOutput`].
43+
PoloniusOutputFacts,
44+
}
45+
46+
impl ConsumerOptions {
47+
/// Should the Polonius input facts be computed?
48+
pub(crate) fn polonius_input(&self) -> bool {
49+
matches!(self, Self::PoloniusInputFacts | Self::PoloniusOutputFacts)
50+
}
51+
/// Should we run Polonius and collect the output facts?
52+
pub(crate) fn polonius_output(&self) -> bool {
53+
matches!(self, Self::PoloniusOutputFacts)
54+
}
55+
}
56+
57+
/// This function computes borrowck facts for the given body. The [`ConsumerOptions`]
58+
/// determine which facts are returned. This function makes a copy of the body because
59+
/// it needs to regenerate the region identifiers. It should never be invoked during a
60+
/// typical compilation session due to the unnecessary overhead of returning
61+
/// [`BodyWithBorrowckFacts`].
2262
///
2363
/// Note:
2464
/// * This function will panic if the required body was already stolen. This
@@ -28,10 +68,14 @@ pub use super::{
2868
/// that shows how to do this at `tests/run-make/obtain-borrowck/`.
2969
///
3070
/// * Polonius is highly unstable, so expect regular changes in its signature or other details.
31-
pub fn get_body_with_borrowck_facts(tcx: TyCtxt<'_>, def: LocalDefId) -> BodyWithBorrowckFacts<'_> {
71+
pub fn get_body_with_borrowck_facts(
72+
tcx: TyCtxt<'_>,
73+
def: LocalDefId,
74+
options: ConsumerOptions,
75+
) -> BodyWithBorrowckFacts<'_> {
3276
let (input_body, promoted) = tcx.mir_promoted(def);
3377
let infcx = tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(def)).build();
3478
let input_body: &Body<'_> = &input_body.borrow();
3579
let promoted: &IndexSlice<_, _> = &promoted.borrow();
36-
*super::do_mir_borrowck(&infcx, input_body, promoted, true).1.unwrap()
80+
*super::do_mir_borrowck(&infcx, input_body, promoted, Some(options)).1.unwrap()
3781
}

compiler/rustc_borrowck/src/dataflow.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -231,27 +231,32 @@ impl<'tcx> OutOfScopePrecomputer<'_, 'tcx> {
231231
}
232232
}
233233

234+
pub fn calculate_borrows_out_of_scope_at_location<'tcx>(
235+
body: &Body<'tcx>,
236+
regioncx: &RegionInferenceContext<'tcx>,
237+
borrow_set: &BorrowSet<'tcx>,
238+
) -> FxIndexMap<Location, Vec<BorrowIndex>> {
239+
let mut prec = OutOfScopePrecomputer::new(body, regioncx);
240+
for (borrow_index, borrow_data) in borrow_set.iter_enumerated() {
241+
let borrow_region = borrow_data.region;
242+
let location = borrow_data.reserve_location;
243+
244+
prec.precompute_borrows_out_of_scope(borrow_index, borrow_region, location);
245+
}
246+
247+
prec.borrows_out_of_scope_at_location
248+
}
249+
234250
impl<'a, 'tcx> Borrows<'a, 'tcx> {
235-
pub(crate) fn new(
251+
pub fn new(
236252
tcx: TyCtxt<'tcx>,
237253
body: &'a Body<'tcx>,
238254
nonlexical_regioncx: &'a RegionInferenceContext<'tcx>,
239255
borrow_set: &'a BorrowSet<'tcx>,
240256
) -> Self {
241-
let mut prec = OutOfScopePrecomputer::new(body, nonlexical_regioncx);
242-
for (borrow_index, borrow_data) in borrow_set.iter_enumerated() {
243-
let borrow_region = borrow_data.region;
244-
let location = borrow_data.reserve_location;
245-
246-
prec.precompute_borrows_out_of_scope(borrow_index, borrow_region, location);
247-
}
248-
249-
Borrows {
250-
tcx,
251-
body,
252-
borrow_set,
253-
borrows_out_of_scope_at_location: prec.borrows_out_of_scope_at_location,
254-
}
257+
let borrows_out_of_scope_at_location =
258+
calculate_borrows_out_of_scope_at_location(body, nonlexical_regioncx, borrow_set);
259+
Borrows { tcx, body, borrow_set, borrows_out_of_scope_at_location }
255260
}
256261

257262
pub fn location(&self, idx: BorrowIndex) -> &Location {

compiler/rustc_borrowck/src/lib.rs

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ use crate::session_diagnostics::VarNeedNotMut;
6262
use self::diagnostics::{AccessKind, RegionName};
6363
use self::location::LocationTable;
6464
use self::prefixes::PrefixSet;
65+
use consumers::ConsumerOptions;
6566
use facts::AllFacts;
6667

6768
use self::path_utils::*;
@@ -144,23 +145,23 @@ fn mir_borrowck(tcx: TyCtxt<'_>, def: LocalDefId) -> &BorrowCheckResult<'_> {
144145
tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bind(hir_owner.def_id)).build();
145146
let input_body: &Body<'_> = &input_body.borrow();
146147
let promoted: &IndexSlice<_, _> = &promoted.borrow();
147-
let opt_closure_req = do_mir_borrowck(&infcx, input_body, promoted, false).0;
148+
let opt_closure_req = do_mir_borrowck(&infcx, input_body, promoted, None).0;
148149
debug!("mir_borrowck done");
149150

150151
tcx.arena.alloc(opt_closure_req)
151152
}
152153

153154
/// Perform the actual borrow checking.
154155
///
155-
/// If `return_body_with_facts` is true, then return the body with non-erased
156-
/// region ids on which the borrow checking was performed together with Polonius
157-
/// facts.
156+
/// Use `consumer_options: None` for the default behavior of returning
157+
/// [`BorrowCheckResult`] only. Otherwise, return [`BodyWithBorrowckFacts`] according
158+
/// to the given [`ConsumerOptions`].
158159
#[instrument(skip(infcx, input_body, input_promoted), fields(id=?input_body.source.def_id()), level = "debug")]
159160
fn do_mir_borrowck<'tcx>(
160161
infcx: &InferCtxt<'tcx>,
161162
input_body: &Body<'tcx>,
162163
input_promoted: &IndexSlice<Promoted, Body<'tcx>>,
163-
return_body_with_facts: bool,
164+
consumer_options: Option<ConsumerOptions>,
164165
) -> (BorrowCheckResult<'tcx>, Option<Box<BodyWithBorrowckFacts<'tcx>>>) {
165166
let def = input_body.source.def_id().expect_local();
166167
debug!(?def);
@@ -241,8 +242,6 @@ fn do_mir_borrowck<'tcx>(
241242
let borrow_set =
242243
Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data));
243244

244-
let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.unstable_opts.polonius;
245-
246245
// Compute non-lexical lifetimes.
247246
let nll::NllOutput {
248247
regioncx,
@@ -262,7 +261,7 @@ fn do_mir_borrowck<'tcx>(
262261
&mdpe.move_data,
263262
&borrow_set,
264263
&upvars,
265-
use_polonius,
264+
consumer_options,
266265
);
267266

268267
// Dump MIR results into a file, if that is enabled. This let us
@@ -444,13 +443,15 @@ fn do_mir_borrowck<'tcx>(
444443
tainted_by_errors,
445444
};
446445

447-
let body_with_facts = if return_body_with_facts {
448-
let output_facts = mbcx.polonius_output.expect("Polonius output was not computed");
446+
let body_with_facts = if consumer_options.is_some() {
447+
let output_facts = mbcx.polonius_output;
449448
Some(Box::new(BodyWithBorrowckFacts {
450449
body: body_owned,
451-
input_facts: *polonius_input.expect("Polonius input facts were not generated"),
450+
borrow_set,
451+
region_inference_context: regioncx,
452+
location_table: polonius_input.as_ref().map(|_| location_table_owned),
453+
input_facts: polonius_input,
452454
output_facts,
453-
location_table: location_table_owned,
454455
}))
455456
} else {
456457
None
@@ -469,12 +470,20 @@ fn do_mir_borrowck<'tcx>(
469470
pub struct BodyWithBorrowckFacts<'tcx> {
470471
/// A mir body that contains region identifiers.
471472
pub body: Body<'tcx>,
472-
/// Polonius input facts.
473-
pub input_facts: AllFacts,
474-
/// Polonius output facts.
475-
pub output_facts: Rc<self::nll::PoloniusOutput>,
476-
/// The table that maps Polonius points to locations in the table.
477-
pub location_table: LocationTable,
473+
/// The set of borrows occurring in `body` with data about them.
474+
pub borrow_set: Rc<BorrowSet<'tcx>>,
475+
/// Context generated during borrowck, intended to be passed to
476+
/// [`OutOfScopePrecomputer`](dataflow::OutOfScopePrecomputer).
477+
pub region_inference_context: Rc<RegionInferenceContext<'tcx>>,
478+
/// The table that maps Polonius points to locations in the table. Populated
479+
/// when using [`ConsumerOptions::PoloniusInputFacts`] or above.
480+
pub location_table: Option<LocationTable>,
481+
/// Polonius input facts. Populated when using
482+
/// [`ConsumerOptions::PoloniusInputFacts`] or above.
483+
pub input_facts: Option<Box<AllFacts>>,
484+
/// Polonius output facts. Populated when using
485+
/// [`ConsumerOptions::PoloniusOutputFacts`] or above.
486+
pub output_facts: Option<Rc<self::nll::PoloniusOutput>>,
478487
}
479488

480489
pub struct BorrowckInferCtxt<'cx, 'tcx> {

compiler/rustc_borrowck/src/nll.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use rustc_mir_dataflow::ResultsCursor;
2727
use crate::{
2828
borrow_set::BorrowSet,
2929
constraint_generation,
30+
consumers::ConsumerOptions,
3031
diagnostics::RegionErrors,
3132
facts::{AllFacts, AllFactsExt, RustcFacts},
3233
invalidation,
@@ -165,10 +166,14 @@ pub(crate) fn compute_regions<'cx, 'tcx>(
165166
move_data: &MoveData<'tcx>,
166167
borrow_set: &BorrowSet<'tcx>,
167168
upvars: &[Upvar<'tcx>],
168-
use_polonius: bool,
169+
consumer_options: Option<ConsumerOptions>,
169170
) -> NllOutput<'tcx> {
171+
let polonius_input = consumer_options.map(|c| c.polonius_input()).unwrap_or_default()
172+
|| infcx.tcx.sess.opts.unstable_opts.polonius;
173+
let polonius_output = consumer_options.map(|c| c.polonius_output()).unwrap_or_default()
174+
|| infcx.tcx.sess.opts.unstable_opts.polonius;
170175
let mut all_facts =
171-
(use_polonius || AllFacts::enabled(infcx.tcx)).then_some(AllFacts::default());
176+
(polonius_input || AllFacts::enabled(infcx.tcx)).then_some(AllFacts::default());
172177

173178
let universal_regions = Rc::new(universal_regions);
174179

@@ -189,7 +194,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>(
189194
move_data,
190195
elements,
191196
upvars,
192-
use_polonius,
197+
polonius_input,
193198
);
194199

195200
if let Some(all_facts) = &mut all_facts {
@@ -284,7 +289,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>(
284289
all_facts.write_to_dir(dir_path, location_table).unwrap();
285290
}
286291

287-
if use_polonius {
292+
if polonius_output {
288293
let algorithm =
289294
env::var("POLONIUS_ALGORITHM").unwrap_or_else(|_| String::from("Hybrid"));
290295
let algorithm = Algorithm::from_str(&algorithm).unwrap();

compiler/rustc_borrowck/src/place_ext.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_middle::mir::{Body, Mutability, Place};
77
use rustc_middle::ty::{self, TyCtxt};
88

99
/// Extension methods for the `Place` type.
10-
pub(crate) trait PlaceExt<'tcx> {
10+
pub trait PlaceExt<'tcx> {
1111
/// Returns `true` if we can safely ignore borrows of this place.
1212
/// This is true whenever there is no action that the user can do
1313
/// to the place `self` that would invalidate the borrow. This is true

compiler/rustc_borrowck/src/places_conflict.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,15 @@ use std::iter;
1616
/// being run in the calling context, the conservative choice is to assume the compared indices
1717
/// are disjoint (and therefore, do not overlap).
1818
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
19-
pub(crate) enum PlaceConflictBias {
19+
pub enum PlaceConflictBias {
2020
Overlap,
2121
NoOverlap,
2222
}
2323

2424
/// Helper function for checking if places conflict with a mutable borrow and deep access depth.
2525
/// This is used to check for places conflicting outside of the borrow checking code (such as in
2626
/// dataflow).
27-
pub(crate) fn places_conflict<'tcx>(
27+
pub fn places_conflict<'tcx>(
2828
tcx: TyCtxt<'tcx>,
2929
body: &Body<'tcx>,
3030
borrow_place: Place<'tcx>,

0 commit comments

Comments
 (0)