]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_borrowck/src/nll.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / compiler / rustc_borrowck / src / nll.rs
CommitLineData
60c5eb7d
XL
1//! The entry point of the NLL borrow checker.
2
17df50a5 3use rustc_data_structures::vec_map::VecMap;
dfeec247 4use rustc_index::vec::IndexVec;
74b04a01 5use rustc_infer::infer::InferCtxt;
c295e0f8 6use rustc_middle::mir::{create_dump_file, dump_enabled, dump_mir, PassWhere};
ba9703b0 7use rustc_middle::mir::{
f9f354fc
XL
8 BasicBlock, Body, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind, Location,
9 Promoted,
ba9703b0 10};
5e7ed085 11use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey, Region, RegionVid};
dfeec247 12use rustc_span::symbol::sym;
94b46f34 13use std::env;
dfeec247 14use std::fmt::Debug;
ff7c6d11 15use std::io;
83c7162d 16use std::path::PathBuf;
94b46f34
XL
17use std::rc::Rc;
18use std::str::FromStr;
ff7c6d11 19
94b46f34 20use polonius_engine::{Algorithm, Output};
60c5eb7d 21
c295e0f8
XL
22use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
23use rustc_mir_dataflow::move_paths::{InitKind, InitLocation, MoveData};
24use rustc_mir_dataflow::ResultsCursor;
ff7c6d11 25
c295e0f8 26use crate::{
60c5eb7d 27 borrow_set::BorrowSet,
dfeec247
XL
28 constraint_generation,
29 diagnostics::RegionErrors,
60c5eb7d 30 facts::{AllFacts, AllFactsExt, RustcFacts},
dfeec247
XL
31 invalidation,
32 location::LocationTable,
33 region_infer::{values::RegionValueElements, RegionInferenceContext},
34 renumber,
35 type_check::{self, MirTypeckRegionConstraints, MirTypeckResults},
60c5eb7d 36 universal_regions::UniversalRegions,
f035d41b 37 Upvar,
60c5eb7d 38};
ff7c6d11 39
94222f64 40pub type PoloniusOutput = Output<RustcFacts>;
ff7c6d11 41
dfeec247
XL
42/// The output of `nll::compute_regions`. This includes the computed `RegionInferenceContext`, any
43/// closure requirements to propagate, and any generated errors.
44crate struct NllOutput<'tcx> {
45 pub regioncx: RegionInferenceContext<'tcx>,
5e7ed085 46 pub opaque_type_values: VecMap<OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>>,
94222f64 47 pub polonius_input: Option<Box<AllFacts>>,
dfeec247
XL
48 pub polonius_output: Option<Rc<PoloniusOutput>>,
49 pub opt_closure_req: Option<ClosureRegionRequirements<'tcx>>,
50 pub nll_errors: RegionErrors<'tcx>,
51}
52
53/// Rewrites the regions in the MIR to use NLL variables, also scraping out the set of universal
54/// regions (e.g., region parameters) declared on the function. That set will need to be given to
ff7c6d11 55/// `compute_regions`.
c295e0f8
XL
56#[instrument(skip(infcx, param_env, body, promoted), level = "debug")]
57pub(crate) fn replace_regions_in_mir<'cx, 'tcx>(
dc9dc135 58 infcx: &InferCtxt<'cx, 'tcx>,
ff7c6d11 59 param_env: ty::ParamEnv<'tcx>,
f9f354fc
XL
60 body: &mut Body<'tcx>,
61 promoted: &mut IndexVec<Promoted, Body<'tcx>>,
ff7c6d11 62) -> UniversalRegions<'tcx> {
29967ef6
XL
63 let def = body.source.with_opt_param().as_local().unwrap();
64
c295e0f8 65 debug!(?def);
ff7c6d11
XL
66
67 // Compute named region information. This also renumbers the inputs/outputs.
3dfed10e 68 let universal_regions = UniversalRegions::new(infcx, def, param_env);
ff7c6d11
XL
69
70 // Replace all remaining regions with fresh inference variables.
e1599b0c 71 renumber::renumber_mir(infcx, body, promoted);
ff7c6d11 72
c295e0f8 73 dump_mir(infcx.tcx, None, "renumber", &0, body, |_, _| Ok(()));
ff7c6d11
XL
74
75 universal_regions
76}
77
e1599b0c
XL
78// This function populates an AllFacts instance with base facts related to
79// MovePaths and needed for the move analysis.
80fn populate_polonius_move_facts(
81 all_facts: &mut AllFacts,
82 move_data: &MoveData<'_>,
83 location_table: &LocationTable,
dfeec247
XL
84 body: &Body<'_>,
85) {
e1599b0c 86 all_facts
74b04a01 87 .path_is_var
5e7ed085 88 .extend(move_data.rev_lookup.iter_locals_enumerated().map(|(l, r)| (r, l)));
e1599b0c
XL
89
90 for (child, move_path) in move_data.move_paths.iter_enumerated() {
74b04a01
XL
91 if let Some(parent) = move_path.parent {
92 all_facts.child_path.push((child, parent));
93 }
e1599b0c
XL
94 }
95
74b04a01
XL
96 let fn_entry_start = location_table
97 .start_index(Location { block: BasicBlock::from_u32(0u32), statement_index: 0 });
98
e1599b0c
XL
99 // initialized_at
100 for init in move_data.inits.iter() {
e1599b0c
XL
101 match init.location {
102 InitLocation::Statement(location) => {
103 let block_data = &body[location.block];
104 let is_terminator = location.statement_index == block_data.statements.len();
105
106 if is_terminator && init.kind == InitKind::NonPanicPathOnly {
107 // We are at the terminator of an init that has a panic path,
108 // and where the init should not happen on panic
109
110 for &successor in block_data.terminator().successors() {
111 if body[successor].is_cleanup {
112 continue;
113 }
114
115 // The initialization happened in (or rather, when arriving at)
116 // the successors, but not in the unwind block.
dfeec247 117 let first_statement = Location { block: successor, statement_index: 0 };
e1599b0c 118 all_facts
74b04a01 119 .path_assigned_at_base
e1599b0c
XL
120 .push((init.path, location_table.start_index(first_statement)));
121 }
e1599b0c
XL
122 } else {
123 // In all other cases, the initialization just happens at the
124 // midpoint, like any other effect.
74b04a01
XL
125 all_facts
126 .path_assigned_at_base
127 .push((init.path, location_table.mid_index(location)));
e1599b0c 128 }
dfeec247 129 }
e1599b0c
XL
130 // Arguments are initialized on function entry
131 InitLocation::Argument(local) => {
132 assert!(body.local_kind(local) == LocalKind::Arg);
74b04a01 133 all_facts.path_assigned_at_base.push((init.path, fn_entry_start));
e1599b0c
XL
134 }
135 }
136 }
137
5e7ed085 138 for (local, path) in move_data.rev_lookup.iter_locals_enumerated() {
74b04a01
XL
139 if body.local_kind(local) != LocalKind::Arg {
140 // Non-arguments start out deinitialised; we simulate this with an
141 // initial move:
142 all_facts.path_moved_at_base.push((path, fn_entry_start));
143 }
144 }
145
e1599b0c
XL
146 // moved_out_at
147 // deinitialisation is assumed to always happen!
148 all_facts
74b04a01 149 .path_moved_at_base
dfeec247 150 .extend(move_data.moves.iter().map(|mo| (mo.path, location_table.mid_index(mo.source))));
e1599b0c
XL
151}
152
ff7c6d11
XL
153/// Computes the (non-lexical) regions from the input MIR.
154///
155/// This may result in errors being reported.
c295e0f8 156pub(crate) fn compute_regions<'cx, 'tcx>(
dc9dc135 157 infcx: &InferCtxt<'cx, 'tcx>,
ff7c6d11 158 universal_regions: UniversalRegions<'tcx>,
f9f354fc
XL
159 body: &Body<'tcx>,
160 promoted: &IndexVec<Promoted, Body<'tcx>>,
83c7162d 161 location_table: &LocationTable,
dc9dc135 162 param_env: ty::ParamEnv<'tcx>,
74b04a01 163 flow_inits: &mut ResultsCursor<'cx, 'tcx, MaybeInitializedPlaces<'cx, 'tcx>>,
ff7c6d11 164 move_data: &MoveData<'tcx>,
83c7162d 165 borrow_set: &BorrowSet<'tcx>,
5869c6ff 166 upvars: &[Upvar<'tcx>],
c295e0f8 167 use_polonius: bool,
dfeec247 168) -> NllOutput<'tcx> {
c295e0f8
XL
169 let mut all_facts =
170 (use_polonius || AllFacts::enabled(infcx.tcx)).then_some(AllFacts::default());
94b46f34 171
8faf50e0
XL
172 let universal_regions = Rc::new(universal_regions);
173
dfeec247 174 let elements = &Rc::new(RegionValueElements::new(&body));
8faf50e0 175
ff7c6d11 176 // Run the MIR type-checker.
74b04a01
XL
177 let MirTypeckResults { constraints, universal_region_relations, opaque_type_values } =
178 type_check::type_check(
179 infcx,
180 param_env,
181 body,
182 promoted,
74b04a01
XL
183 &universal_regions,
184 location_table,
185 borrow_set,
186 &mut all_facts,
187 flow_inits,
188 move_data,
189 elements,
f035d41b 190 upvars,
5e7ed085 191 use_polonius,
74b04a01 192 );
ff7c6d11 193
83c7162d 194 if let Some(all_facts) = &mut all_facts {
60c5eb7d 195 let _prof_timer = infcx.tcx.prof.generic_activity("polonius_fact_generation");
dfeec247 196 all_facts.universal_region.extend(universal_regions.universal_regions());
60c5eb7d
XL
197 populate_polonius_move_facts(all_facts, move_data, location_table, &body);
198
199 // Emit universal regions facts, and their relations, for Polonius.
200 //
201 // 1: universal regions are modeled in Polonius as a pair:
202 // - the universal region vid itself.
203 // - a "placeholder loan" associated to this universal region. Since they don't exist in
204 // the `borrow_set`, their `BorrowIndex` are synthesized as the universal region index
205 // added to the existing number of loans, as if they succeeded them in the set.
206 //
3dfed10e 207 let borrow_count = borrow_set.len();
60c5eb7d
XL
208 debug!(
209 "compute_regions: polonius placeholders, num_universals={}, borrow_count={}",
210 universal_regions.len(),
211 borrow_count
212 );
213
214 for universal_region in universal_regions.universal_regions() {
215 let universal_region_idx = universal_region.index();
216 let placeholder_loan_idx = borrow_count + universal_region_idx;
217 all_facts.placeholder.push((universal_region, placeholder_loan_idx.into()));
218 }
219
220 // 2: the universal region relations `outlives` constraints are emitted as
94222f64 221 // `known_placeholder_subset` facts.
60c5eb7d
XL
222 for (fr1, fr2) in universal_region_relations.known_outlives() {
223 if fr1 != fr2 {
224 debug!(
94222f64
XL
225 "compute_regions: emitting polonius `known_placeholder_subset` \
226 fr1={:?}, fr2={:?}",
60c5eb7d
XL
227 fr1, fr2
228 );
5e7ed085 229 all_facts.known_placeholder_subset.push((fr1, fr2));
60c5eb7d
XL
230 }
231 }
83c7162d
XL
232 }
233
94b46f34
XL
234 // Create the region inference context, taking ownership of the
235 // region inference data that was contained in `infcx`, and the
236 // base constraints generated by the type-check.
ff7c6d11 237 let var_origins = infcx.take_region_var_origins();
94b46f34 238 let MirTypeckRegionConstraints {
a1dfa0c6
XL
239 placeholder_indices,
240 placeholder_index_to_region: _,
8faf50e0 241 mut liveness_constraints,
94b46f34 242 outlives_constraints,
dc9dc135 243 member_constraints,
0bf4aa26 244 closure_bounds_mapping,
94222f64 245 universe_causes,
94b46f34 246 type_tests,
b7449926 247 } = constraints;
a1dfa0c6 248 let placeholder_indices = Rc::new(placeholder_indices);
8faf50e0
XL
249
250 constraint_generation::generate_constraints(
251 infcx,
252 &mut liveness_constraints,
253 &mut all_facts,
254 location_table,
dc9dc135 255 &body,
8faf50e0
XL
256 borrow_set,
257 );
258
94b46f34
XL
259 let mut regioncx = RegionInferenceContext::new(
260 var_origins,
261 universal_regions,
0bf4aa26 262 placeholder_indices,
8faf50e0 263 universal_region_relations,
94b46f34 264 outlives_constraints,
dc9dc135 265 member_constraints,
0bf4aa26 266 closure_bounds_mapping,
94222f64 267 universe_causes,
94b46f34 268 type_tests,
8faf50e0
XL
269 liveness_constraints,
270 elements,
94b46f34 271 );
ff7c6d11 272
94b46f34 273 // Generate various additional constraints.
dfeec247 274 invalidation::generate_invalidates(infcx.tcx, &mut all_facts, location_table, body, borrow_set);
ff7c6d11 275
29967ef6
XL
276 let def_id = body.source.def_id();
277
83c7162d 278 // Dump facts if requested.
94222f64 279 let polonius_output = all_facts.as_ref().and_then(|all_facts| {
94b46f34 280 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
29967ef6
XL
281 let def_path = infcx.tcx.def_path(def_id);
282 let dir_path = PathBuf::from(&infcx.tcx.sess.opts.debugging_opts.nll_facts_dir)
283 .join(def_path.to_filename_friendly_no_crate());
94b46f34
XL
284 all_facts.write_to_dir(dir_path, location_table).unwrap();
285 }
286
c295e0f8 287 if use_polonius {
dfeec247 288 let algorithm =
94222f64 289 env::var("POLONIUS_ALGORITHM").unwrap_or_else(|_| String::from("Hybrid"));
94b46f34
XL
290 let algorithm = Algorithm::from_str(&algorithm).unwrap();
291 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
60c5eb7d 292 let _prof_timer = infcx.tcx.prof.generic_activity("polonius_analysis");
dfeec247 293 Some(Rc::new(Output::compute(&all_facts, algorithm, false)))
94b46f34
XL
294 } else {
295 None
296 }
297 });
ff7c6d11
XL
298
299 // Solve the region constraints.
dfeec247 300 let (closure_region_requirements, nll_errors) =
29967ef6 301 regioncx.solve(infcx, &body, polonius_output.clone());
dfeec247 302
74b04a01
XL
303 if !nll_errors.is_empty() {
304 // Suppress unhelpful extra errors in `infer_opaque_types`.
305 infcx.set_tainted_by_errors();
306 }
307
5e7ed085 308 let remapped_opaque_tys = regioncx.infer_opaque_types(&infcx, opaque_type_values);
74b04a01 309
dfeec247
XL
310 NllOutput {
311 regioncx,
74b04a01 312 opaque_type_values: remapped_opaque_tys,
94222f64 313 polonius_input: all_facts.map(Box::new),
dfeec247
XL
314 polonius_output,
315 opt_closure_req: closure_region_requirements,
316 nll_errors,
317 }
ff7c6d11
XL
318}
319
dfeec247 320pub(super) fn dump_mir_results<'a, 'tcx>(
dc9dc135 321 infcx: &InferCtxt<'a, 'tcx>,
dc9dc135 322 body: &Body<'tcx>,
f035d41b 323 regioncx: &RegionInferenceContext<'tcx>,
9fa01778 324 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
ff7c6d11 325) {
c295e0f8 326 if !dump_enabled(infcx.tcx, "nll", body.source.def_id()) {
ff7c6d11
XL
327 return;
328 }
329
c295e0f8 330 dump_mir(infcx.tcx, None, "nll", &0, body, |pass_where, out| {
dfeec247
XL
331 match pass_where {
332 // Before the CFG, dump out the values for each region variable.
333 PassWhere::BeforeCFG => {
f035d41b 334 regioncx.dump_mir(infcx.tcx, out)?;
dfeec247
XL
335 writeln!(out, "|")?;
336
337 if let Some(closure_region_requirements) = closure_region_requirements {
338 writeln!(out, "| Free Region Constraints")?;
339 for_each_region_constraint(closure_region_requirements, &mut |msg| {
340 writeln!(out, "| {}", msg)
341 })?;
0731742a 342 writeln!(out, "|")?;
ff7c6d11 343 }
dfeec247 344 }
ff7c6d11 345
dfeec247 346 PassWhere::BeforeLocation(_) => {}
ff7c6d11 347
dfeec247 348 PassWhere::AfterTerminator(_) => {}
8faf50e0 349
dfeec247
XL
350 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
351 }
352 Ok(())
353 });
ff7c6d11
XL
354
355 // Also dump the inference graph constraints as a graphviz file.
9fa01778 356 let _: io::Result<()> = try {
ff7c6d11 357 let mut file =
c295e0f8 358 create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, body.source)?;
8faf50e0
XL
359 regioncx.dump_graphviz_raw_constraints(&mut file)?;
360 };
361
362 // Also dump the inference graph constraints as a graphviz file.
9fa01778 363 let _: io::Result<()> = try {
8faf50e0 364 let mut file =
c295e0f8 365 create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, body.source)?;
8faf50e0 366 regioncx.dump_graphviz_scc_constraints(&mut file)?;
94b46f34 367 };
ff7c6d11
XL
368}
369
dfeec247 370pub(super) fn dump_annotation<'a, 'tcx>(
dc9dc135
XL
371 infcx: &InferCtxt<'a, 'tcx>,
372 body: &Body<'tcx>,
b7449926 373 regioncx: &RegionInferenceContext<'tcx>,
9fa01778 374 closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
5e7ed085 375 opaque_type_values: &VecMap<OpaqueTypeKey<'tcx>, OpaqueHiddenType<'tcx>>,
5099ac24 376 errors: &mut crate::error::BorrowckErrors<'tcx>,
ff7c6d11
XL
377) {
378 let tcx = infcx.tcx;
3c0e092e 379 let base_def_id = tcx.typeck_root_def_id(body.source.def_id());
48663c56 380 if !tcx.has_attr(base_def_id, sym::rustc_regions) {
ff7c6d11
XL
381 return;
382 }
383
384 // When the enclosing function is tagged with `#[rustc_regions]`,
385 // we dump out various bits of state as warnings. This is useful
386 // for verifying that the compiler is behaving as expected. These
387 // warnings focus on the closure region requirements -- for
388 // viewing the intraprocedural state, the -Zdump-mir output is
389 // better.
390
74b04a01 391 let mut err = if let Some(closure_region_requirements) = closure_region_requirements {
dfeec247 392 let mut err = tcx.sess.diagnostic().span_note_diag(body.span, "external requirements");
ff7c6d11 393
b7449926 394 regioncx.annotate(tcx, &mut err);
ff7c6d11
XL
395
396 err.note(&format!(
397 "number of external vids: {}",
398 closure_region_requirements.num_external_vids
399 ));
400
401 // Dump the region constraints we are imposing *between* those
402 // newly created variables.
403 for_each_region_constraint(closure_region_requirements, &mut |msg| {
404 err.note(msg);
405 Ok(())
dfeec247
XL
406 })
407 .unwrap();
ff7c6d11 408
74b04a01 409 err
ff7c6d11 410 } else {
dfeec247 411 let mut err = tcx.sess.diagnostic().span_note_diag(body.span, "no external requirements");
b7449926 412 regioncx.annotate(tcx, &mut err);
8faf50e0 413
74b04a01
XL
414 err
415 };
416
417 if !opaque_type_values.is_empty() {
418 err.note(&format!("Inferred opaque type values:\n{:#?}", opaque_type_values));
ff7c6d11 419 }
74b04a01 420
5099ac24 421 errors.buffer_non_error_diag(err);
ff7c6d11
XL
422}
423
424fn for_each_region_constraint(
9fa01778 425 closure_region_requirements: &ClosureRegionRequirements<'_>,
0531ce1d 426 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
ff7c6d11
XL
427) -> io::Result<()> {
428 for req in &closure_region_requirements.outlives_requirements {
0531ce1d 429 let subject: &dyn Debug = match &req.subject {
ff7c6d11
XL
430 ClosureOutlivesSubject::Region(subject) => subject,
431 ClosureOutlivesSubject::Ty(ty) => ty,
432 };
dfeec247 433 with_msg(&format!("where {:?}: {:?}", subject, req.outlived_free_region,))?;
ff7c6d11
XL
434 }
435 Ok(())
436}
437
438/// Right now, we piggy back on the `ReVar` to store our NLL inference
439/// regions. These are indexed with `RegionVid`. This method will
0531ce1d 440/// assert that the region is a `ReVar` and extract its internal index.
ff7c6d11
XL
441/// This is reasonable because in our MIR we replace all universal regions
442/// with inference variables.
443pub trait ToRegionVid {
444 fn to_region_vid(self) -> RegionVid;
445}
446
5099ac24 447impl<'tcx> ToRegionVid for Region<'tcx> {
ff7c6d11 448 fn to_region_vid(self) -> RegionVid {
5099ac24 449 if let ty::ReVar(vid) = *self { vid } else { bug!("region is not an ReVar: {:?}", self) }
ff7c6d11
XL
450 }
451}
452
453impl ToRegionVid for RegionVid {
454 fn to_region_vid(self) -> RegionVid {
455 self
456 }
457}
0bf4aa26
XL
458
459crate trait ConstraintDescription {
460 fn description(&self) -> &'static str;
461}