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