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