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::MirTypeckRegionConstraints;
15 use borrow_check::nll::region_infer::values::RegionValueElements;
16 use dataflow::indexes::BorrowIndex;
17 use dataflow::move_paths::MoveData;
18 use dataflow::FlowAtLocation;
19 use dataflow::MaybeInitializedPlaces;
20 use rustc::hir::def_id::DefId;
21 use rustc::infer::InferCtxt;
22 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir, Local};
23 use rustc::ty::{self, RegionKind, RegionVid};
24 use rustc::util::nodemap::FxHashMap;
25 use std::collections::BTreeSet;
29 use std::path::PathBuf;
31 use std::str::FromStr;
32 use transform::MirSource;
33 use util::liveness::{IdentityMap, LivenessResults, LocalSet};
35 use self::mir_util::PassWhere;
36 use polonius_engine::{Algorithm, Output};
38 use util::pretty::{self, ALIGN};
40 mod constraint_generation;
41 pub mod explain_borrow;
44 crate mod region_infer;
47 mod universal_regions;
51 use self::facts::AllFacts;
52 use self::region_infer::RegionInferenceContext;
53 use self::universal_regions::UniversalRegions;
55 /// Rewrites the regions in the MIR to use NLL variables, also
56 /// scraping out the set of universal regions (e.g., region parameters)
57 /// declared on the function. That set will need to be given to
58 /// `compute_regions`.
59 pub(in borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
60 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
62 param_env: ty::ParamEnv<'tcx>,
64 ) -> UniversalRegions<'tcx> {
65 debug!("replace_regions_in_mir(def_id={:?})", def_id);
67 // Compute named region information. This also renumbers the inputs/outputs.
68 let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
70 // Replace all remaining regions with fresh inference variables.
71 renumber::renumber_mir(infcx, mir);
73 let source = MirSource::item(def_id);
74 mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
79 /// Computes the (non-lexical) regions from the input MIR.
81 /// This may result in errors being reported.
82 pub(in borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
83 infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
85 universal_regions: UniversalRegions<'tcx>,
87 location_table: &LocationTable,
88 param_env: ty::ParamEnv<'gcx>,
89 flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
90 move_data: &MoveData<'tcx>,
91 borrow_set: &BorrowSet<'tcx>,
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 elements = &Rc::new(RegionValueElements::new(mir, universal_regions.len()));
105 // Run the MIR type-checker.
106 let liveness = &LivenessResults::compute(mir, &IdentityMap::new(mir));
107 let constraint_sets = type_check::type_check(
122 if let Some(all_facts) = &mut all_facts {
125 .extend(universal_regions.universal_regions());
128 // Create the region inference context, taking ownership of the
129 // region inference data that was contained in `infcx`, and the
130 // base constraints generated by the type-check.
131 let var_origins = infcx.take_region_var_origins();
132 let MirTypeckRegionConstraints {
133 liveness_constraints,
134 outlives_constraints,
137 let mut regioncx = RegionInferenceContext::new(
141 outlives_constraints,
143 liveness_constraints,
147 // Generate various additional constraints.
148 constraint_generation::generate_constraints(
156 invalidation::generate_invalidates(
165 // Dump facts if requested.
166 let polonius_output = all_facts.and_then(|all_facts| {
167 if infcx.tcx.sess.opts.debugging_opts.nll_facts {
168 let def_path = infcx.tcx.hir.def_path(def_id);
170 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
171 all_facts.write_to_dir(dir_path, location_table).unwrap();
174 if infcx.tcx.sess.opts.debugging_opts.polonius {
175 let algorithm = env::var("POLONIUS_ALGORITHM")
176 .unwrap_or(String::from("DatafrogOpt"));
177 let algorithm = Algorithm::from_str(&algorithm).unwrap();
178 debug!("compute_regions: using polonius algorithm {:?}", algorithm);
179 Some(Rc::new(Output::compute(
189 // Solve the region constraints.
190 let closure_region_requirements = regioncx.solve(infcx, &mir, def_id);
192 // Dump MIR results into a file, if that is enabled. This let us
193 // write unit-tests, as well as helping with debugging.
197 MirSource::item(def_id),
200 &closure_region_requirements,
203 // We also have a `#[rustc_nll]` annotation that causes us to dump
205 dump_annotation(infcx, &mir, def_id, ®ioncx, &closure_region_requirements);
207 (regioncx, polonius_output, closure_region_requirements)
210 fn dump_mir_results<'a, 'gcx, 'tcx>(
211 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
212 liveness: &LivenessResults<Local>,
215 regioncx: &RegionInferenceContext,
216 closure_region_requirements: &Option<ClosureRegionRequirements>,
218 if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
222 let map = &IdentityMap::new(mir);
224 let regular_liveness_per_location: FxHashMap<_, _> = mir
228 let mut results = vec![];
231 .simulate_block(&mir, bb, map, |location, local_set| {
232 results.push((location, local_set.clone()));
238 let drop_liveness_per_location: FxHashMap<_, _> = mir
242 let mut results = vec![];
245 .simulate_block(&mir, bb, map, |location, local_set| {
246 results.push((location, local_set.clone()));
261 // Before the CFG, dump out the values for each region variable.
262 PassWhere::BeforeCFG => {
263 regioncx.dump_mir(out)?;
265 if let Some(closure_region_requirements) = closure_region_requirements {
267 writeln!(out, "| Free Region Constraints")?;
268 for_each_region_constraint(closure_region_requirements, &mut |msg| {
269 writeln!(out, "| {}", msg)
274 PassWhere::BeforeLocation(location) => {
275 let s = live_variable_set(
276 ®ular_liveness_per_location[&location],
277 &drop_liveness_per_location[&location],
281 "{:ALIGN$} | Live variables on entry to {:?}: {}",
289 // After each basic block, dump out the values
290 // that are live on exit from the basic block.
291 PassWhere::AfterTerminator(bb) => {
292 let s = live_variable_set(&liveness.regular.outs[bb], &liveness.drop.outs[bb]);
293 writeln!(out, " | Live variables on exit from {:?}: {}", bb, s)?;
296 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
302 // Also dump the inference graph constraints as a graphviz file.
303 let _: io::Result<()> = do catch {
305 pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
306 regioncx.dump_graphviz_raw_constraints(&mut file)?;
309 // Also dump the inference graph constraints as a graphviz file.
310 let _: io::Result<()> = do catch {
312 pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
313 regioncx.dump_graphviz_scc_constraints(&mut file)?;
317 fn dump_annotation<'a, 'gcx, 'tcx>(
318 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
321 regioncx: &RegionInferenceContext,
322 closure_region_requirements: &Option<ClosureRegionRequirements>,
325 let base_def_id = tcx.closure_base_def_id(mir_def_id);
326 if !tcx.has_attr(base_def_id, "rustc_regions") {
330 // When the enclosing function is tagged with `#[rustc_regions]`,
331 // we dump out various bits of state as warnings. This is useful
332 // for verifying that the compiler is behaving as expected. These
333 // warnings focus on the closure region requirements -- for
334 // viewing the intraprocedural state, the -Zdump-mir output is
337 if let Some(closure_region_requirements) = closure_region_requirements {
341 .span_note_diag(mir.span, "External requirements");
343 regioncx.annotate(&mut err);
346 "number of external vids: {}",
347 closure_region_requirements.num_external_vids
350 // Dump the region constraints we are imposing *between* those
351 // newly created variables.
352 for_each_region_constraint(closure_region_requirements, &mut |msg| {
362 .span_note_diag(mir.span, "No external requirements");
363 regioncx.annotate(&mut err);
368 fn for_each_region_constraint(
369 closure_region_requirements: &ClosureRegionRequirements,
370 with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
371 ) -> io::Result<()> {
372 for req in &closure_region_requirements.outlives_requirements {
373 let subject: &dyn Debug = match &req.subject {
374 ClosureOutlivesSubject::Region(subject) => subject,
375 ClosureOutlivesSubject::Ty(ty) => ty,
379 subject, req.outlived_free_region,
385 /// Right now, we piggy back on the `ReVar` to store our NLL inference
386 /// regions. These are indexed with `RegionVid`. This method will
387 /// assert that the region is a `ReVar` and extract its internal index.
388 /// This is reasonable because in our MIR we replace all universal regions
389 /// with inference variables.
390 pub trait ToRegionVid {
391 fn to_region_vid(self) -> RegionVid;
394 impl<'tcx> ToRegionVid for &'tcx RegionKind {
395 fn to_region_vid(self) -> RegionVid {
396 if let ty::ReVar(vid) = self {
399 bug!("region is not an ReVar: {:?}", self)
404 impl ToRegionVid for RegionVid {
405 fn to_region_vid(self) -> RegionVid {
410 fn live_variable_set(regular: &LocalSet<Local>, drops: &LocalSet<Local>) -> String {
411 // sort and deduplicate:
412 let all_locals: BTreeSet<_> = regular.iter().chain(drops.iter()).collect();
414 // construct a string with each local, including `(drop)` if it is
415 // only dropped, versus a regular use.
416 let mut string = String::new();
417 for local in all_locals {
418 string.push_str(&format!("{:?}", local));
420 if !regular.contains(&local) {
421 assert!(drops.contains(&local));
422 string.push_str(" (drop)");
425 string.push_str(", ");
428 let len = if string.is_empty() {
434 format!("[{}]", &string[..len])