1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use borrow_check::borrow_set::BorrowSet;
12 use borrow_check::location::{LocationIndex, LocationTable};
13 use borrow_check::nll::facts::AllFactsExt;
14 use borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints};
15 use borrow_check::nll::type_check::liveness::liveness_map::NllLivenessMap;
16 use borrow_check::nll::region_infer::values::RegionValueElements;
17 use dataflow::indexes::BorrowIndex;
18 use dataflow::move_paths::MoveData;
19 use dataflow::FlowAtLocation;
20 use dataflow::MaybeInitializedPlaces;
21 use rustc::hir::def_id::DefId;
22 use rustc::infer::InferCtxt;
23 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir};
24 use rustc::ty::{self, RegionKind, RegionVid};
25 use rustc_errors::Diagnostic;
29 use std::path::PathBuf;
31 use std::str::FromStr;
32 use transform::MirSource;
34 use self::mir_util::PassWhere;
35 use polonius_engine::{Algorithm, Output};
39 mod constraint_generation;
40 pub mod explain_borrow;
43 crate mod region_infer;
46 mod universal_regions;
50 use self::facts::AllFacts;
51 use self::region_infer::RegionInferenceContext;
52 use self::universal_regions::UniversalRegions;
54 /// Rewrites the regions in the MIR to use NLL variables, also
55 /// scraping out the set of universal regions (e.g., region parameters)
56 /// declared on the function. That set will need to be given to
57 /// `compute_regions`.
58 pub(in borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
59 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
61 param_env: ty::ParamEnv<'tcx>,
63 ) -> UniversalRegions<'tcx> {
64 debug!("replace_regions_in_mir(def_id={:?})", def_id);
66 // Compute named region information. This also renumbers the inputs/outputs.
67 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
69 // Replace all remaining regions with fresh inference variables.
70 renumber::renumber_mir(infcx, mir);
72 let source = MirSource::item(def_id);
73 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
78 /// Computes the (non-lexical) regions from the input MIR.
80 /// This may result in errors being reported.
81 pub(in borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
82 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
84 universal_regions: UniversalRegions<'tcx>,
86 location_table: &LocationTable,
87 param_env: ty::ParamEnv<'gcx>,
88 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
89 move_data: &MoveData<'tcx>,
90 borrow_set: &BorrowSet<'tcx>,
91 errors_buffer: &mut Vec<Diagnostic>,
93 RegionInferenceContext<'tcx>,
94 Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex>>>,
95 Option<ClosureRegionRequirements<'gcx>>,
97 let mut all_facts = if AllFacts::enabled(infcx.tcx) {
98 Some(AllFacts::default())
103 let universal_regions = Rc::new(universal_regions);
105 let elements = &Rc::new(RegionValueElements::new(mir));
107 // Run the MIR type-checker.
108 let MirTypeckResults {
110 universal_region_relations,
111 } = type_check::type_check(
126 if let Some(all_facts) = &mut all_facts {
129 .extend(universal_regions.universal_regions());
132 // Create the region inference context, taking ownership of the
133 // region inference data that was contained in `infcx`, and the
134 // base constraints generated by the type-check.
135 let var_origins = infcx.take_region_var_origins();
136 let MirTypeckRegionConstraints {
137 mut liveness_constraints,
138 outlives_constraints,
142 constraint_generation::generate_constraints(
144 &mut liveness_constraints,
151 let mut regioncx = RegionInferenceContext::new(
154 universal_region_relations,
156 outlives_constraints,
158 liveness_constraints,
162 // Generate various additional constraints.
163 invalidation::generate_invalidates(
172 // Dump facts if requested.
173 let polonius_output = all_facts.and_then(|all_facts| {
174 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
175 let def_path = infcx.tcx.hir.def_path(def_id);
177 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
178 all_facts.write_to_dir(dir_path, location_table).unwrap();
181 if infcx.tcx.sess.opts.debugging_opts.polonius {
182 let algorithm = env::var("POLONIUS_ALGORITHM")
183 .unwrap_or(String::from("DatafrogOpt"));
184 let algorithm = Algorithm::from_str(&algorithm).unwrap();
185 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
186 Some(Rc::new(Output::compute(
196 // Solve the region constraints.
197 let closure_region_requirements = regioncx.solve(infcx, &mir, def_id, errors_buffer);
199 // Dump MIR results into a file, if that is enabled. This let us
200 // write unit-tests, as well as helping with debugging.
203 MirSource::item(def_id),
206 &closure_region_requirements,
209 // We also have a `#[rustc_nll]` annotation that causes us to dump
211 dump_annotation(infcx, &mir, def_id, ®ioncx, &closure_region_requirements, errors_buffer);
213 (regioncx, polonius_output, closure_region_requirements)
216 fn dump_mir_results<'a, 'gcx, 'tcx>(
217 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
220 regioncx: &RegionInferenceContext,
221 closure_region_requirements: &Option<ClosureRegionRequirements>,
223 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
236 // Before the CFG, dump out the values for each region variable.
237 PassWhere::BeforeCFG => {
238 regioncx.dump_mir(out)?;
240 if let Some(closure_region_requirements) = closure_region_requirements {
242 writeln!(out, "| Free Region Constraints")?;
243 for_each_region_constraint(closure_region_requirements, &mut |msg| {
244 writeln!(out, "| {}", msg)
249 PassWhere::BeforeLocation(_) => {
252 PassWhere::AfterTerminator(_) => {
255 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
261 // Also dump the inference graph constraints as a graphviz file.
262 let _: io::Result<()> = try_block! {
264 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
265 regioncx.dump_graphviz_raw_constraints(&mut file)?;
268 // Also dump the inference graph constraints as a graphviz file.
269 let _: io::Result<()> = try_block! {
271 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
272 regioncx.dump_graphviz_scc_constraints(&mut file)?;
276 fn dump_annotation<'a, 'gcx, 'tcx>(
277 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
280 regioncx: &RegionInferenceContext,
281 closure_region_requirements: &Option<ClosureRegionRequirements>,
282 errors_buffer: &mut Vec<Diagnostic>,
285 let base_def_id = tcx.closure_base_def_id(mir_def_id);
286 if !tcx.has_attr(base_def_id, "rustc_regions") {
290 // When the enclosing function is tagged with `#[rustc_regions]`,
291 // we dump out various bits of state as warnings. This is useful
292 // for verifying that the compiler is behaving as expected. These
293 // warnings focus on the closure region requirements -- for
294 // viewing the intraprocedural state, the -Zdump-mir output is
297 if let Some(closure_region_requirements) = closure_region_requirements {
301 .span_note_diag(mir.span, "External requirements");
303 regioncx.annotate(&mut err);
306 "number of external vids: {}",
307 closure_region_requirements.num_external_vids
310 // Dump the region constraints we are imposing *between* those
311 // newly created variables.
312 for_each_region_constraint(closure_region_requirements, &mut |msg| {
317 err.buffer(errors_buffer);
322 .span_note_diag(mir.span, "No external requirements");
323 regioncx.annotate(&mut err);
325 err.buffer(errors_buffer);
329 fn for_each_region_constraint(
330 closure_region_requirements: &ClosureRegionRequirements,
331 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
332 ) -> io::Result<()> {
333 for req in &closure_region_requirements.outlives_requirements {
334 let subject: &dyn Debug = match &req.subject {
335 ClosureOutlivesSubject::Region(subject) => subject,
336 ClosureOutlivesSubject::Ty(ty) => ty,
340 subject, req.outlived_free_region,
346 /// Right now, we piggy back on the `ReVar` to store our NLL inference
347 /// regions. These are indexed with `RegionVid`. This method will
348 /// assert that the region is a `ReVar` and extract its internal index.
349 /// This is reasonable because in our MIR we replace all universal regions
350 /// with inference variables.
351 pub trait ToRegionVid {
352 fn to_region_vid(self) -> RegionVid;
355 impl<'tcx> ToRegionVid for &'tcx RegionKind {
356 fn to_region_vid(self) -> RegionVid {
357 if let ty::ReVar(vid) = self {
360 bug!("region is not an ReVar: {:?}", self)
365 impl ToRegionVid for RegionVid {
366 fn to_region_vid(self) -> RegionVid {