rustc_borrowck/
nll.rs

1//! The entry point of the NLL borrow checker.
2
3use std::io;
4use std::path::PathBuf;
5use std::rc::Rc;
6use std::str::FromStr;
7
8use polonius_engine::{Algorithm, AllFacts, Output};
9use rustc_data_structures::frozen::Frozen;
10use rustc_index::IndexSlice;
11use rustc_middle::mir::pretty::{PrettyPrintMirOptions, dump_mir_with_options};
12use rustc_middle::mir::{Body, PassWhere, Promoted, create_dump_file, dump_enabled, dump_mir};
13use rustc_middle::ty::print::with_no_trimmed_paths;
14use rustc_middle::ty::{self, TyCtxt};
15use rustc_mir_dataflow::move_paths::MoveData;
16use rustc_mir_dataflow::points::DenseLocationMap;
17use rustc_session::config::MirIncludeSpans;
18use rustc_span::sym;
19use tracing::{debug, instrument};
20
21use crate::borrow_set::BorrowSet;
22use crate::consumers::RustcFacts;
23use crate::diagnostics::RegionErrors;
24use crate::handle_placeholders::compute_sccs_applying_placeholder_outlives_constraints;
25use crate::polonius::legacy::{
26    PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput,
27};
28use crate::polonius::{PoloniusContext, PoloniusDiagnosticsContext};
29use crate::region_infer::RegionInferenceContext;
30use crate::type_check::MirTypeckRegionConstraints;
31use crate::type_check::free_region_relations::UniversalRegionRelations;
32use crate::universal_regions::UniversalRegions;
33use crate::{
34    BorrowCheckRootCtxt, BorrowckInferCtxt, ClosureOutlivesSubject, ClosureRegionRequirements,
35    polonius, renumber,
36};
37
38/// The output of `nll::compute_regions`. This includes the computed `RegionInferenceContext`, any
39/// closure requirements to propagate, and any generated errors.
40pub(crate) struct NllOutput<'tcx> {
41    pub regioncx: RegionInferenceContext<'tcx>,
42    pub polonius_input: Option<Box<PoloniusFacts>>,
43    pub polonius_output: Option<Box<PoloniusOutput>>,
44    pub opt_closure_req: Option<ClosureRegionRequirements<'tcx>>,
45    pub nll_errors: RegionErrors<'tcx>,
46
47    /// When using `-Zpolonius=next`: the data used to compute errors and diagnostics, e.g.
48    /// localized typeck and liveness constraints.
49    pub polonius_diagnostics: Option<PoloniusDiagnosticsContext>,
50}
51
52/// Rewrites the regions in the MIR to use NLL variables, also scraping out the set of universal
53/// regions (e.g., region parameters) declared on the function. That set will need to be given to
54/// `compute_regions`.
55#[instrument(skip(infcx, body, promoted), level = "debug")]
56pub(crate) fn replace_regions_in_mir<'tcx>(
57    infcx: &BorrowckInferCtxt<'tcx>,
58    body: &mut Body<'tcx>,
59    promoted: &mut IndexSlice<Promoted, Body<'tcx>>,
60) -> UniversalRegions<'tcx> {
61    let def = body.source.def_id().expect_local();
62
63    debug!(?def);
64
65    // Compute named region information. This also renumbers the inputs/outputs.
66    let universal_regions = UniversalRegions::new(infcx, def);
67
68    // Replace all remaining regions with fresh inference variables.
69    renumber::renumber_mir(infcx, body, promoted);
70
71    dump_mir(infcx.tcx, false, "renumber", &0, body, |_, _| Ok(()));
72
73    universal_regions
74}
75
76/// Computes the (non-lexical) regions from the input MIR.
77///
78/// This may result in errors being reported.
79pub(crate) fn compute_regions<'tcx>(
80    root_cx: &mut BorrowCheckRootCtxt<'tcx>,
81    infcx: &BorrowckInferCtxt<'tcx>,
82    body: &Body<'tcx>,
83    location_table: &PoloniusLocationTable,
84    move_data: &MoveData<'tcx>,
85    borrow_set: &BorrowSet<'tcx>,
86    location_map: Rc<DenseLocationMap>,
87    universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
88    constraints: MirTypeckRegionConstraints<'tcx>,
89    mut polonius_facts: Option<AllFacts<RustcFacts>>,
90    polonius_context: Option<PoloniusContext>,
91) -> NllOutput<'tcx> {
92    let polonius_output = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_output())
93        || infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled();
94
95    let lowered_constraints = compute_sccs_applying_placeholder_outlives_constraints(
96        constraints,
97        &universal_region_relations,
98        infcx,
99    );
100
101    // If requested, emit legacy polonius facts.
102    polonius::legacy::emit_facts(
103        &mut polonius_facts,
104        infcx.tcx,
105        location_table,
106        body,
107        borrow_set,
108        move_data,
109        &universal_region_relations,
110        &lowered_constraints,
111    );
112
113    let mut regioncx = RegionInferenceContext::new(
114        infcx,
115        lowered_constraints,
116        universal_region_relations,
117        location_map,
118    );
119
120    // If requested for `-Zpolonius=next`, convert NLL constraints to localized outlives constraints
121    // and use them to compute loan liveness.
122    let polonius_diagnostics = polonius_context.map(|polonius_context| {
123        polonius_context.compute_loan_liveness(infcx.tcx, &mut regioncx, body, borrow_set)
124    });
125
126    // If requested: dump NLL facts, and run legacy polonius analysis.
127    let polonius_output = polonius_facts.as_ref().and_then(|polonius_facts| {
128        if infcx.tcx.sess.opts.unstable_opts.nll_facts {
129            let def_id = body.source.def_id();
130            let def_path = infcx.tcx.def_path(def_id);
131            let dir_path = PathBuf::from(&infcx.tcx.sess.opts.unstable_opts.nll_facts_dir)
132                .join(def_path.to_filename_friendly_no_crate());
133            polonius_facts.write_to_dir(dir_path, location_table).unwrap();
134        }
135
136        if polonius_output {
137            let algorithm = infcx.tcx.env_var("POLONIUS_ALGORITHM").unwrap_or("Hybrid");
138            let algorithm = Algorithm::from_str(algorithm).unwrap();
139            debug!("compute_regions: using polonius algorithm {:?}", algorithm);
140            let _prof_timer = infcx.tcx.prof.generic_activity("polonius_analysis");
141            Some(Box::new(Output::compute(polonius_facts, algorithm, false)))
142        } else {
143            None
144        }
145    });
146
147    // Solve the region constraints.
148    let (closure_region_requirements, nll_errors) =
149        regioncx.solve(infcx, body, polonius_output.clone());
150
151    NllOutput {
152        regioncx,
153        polonius_input: polonius_facts.map(Box::new),
154        polonius_output,
155        opt_closure_req: closure_region_requirements,
156        nll_errors,
157        polonius_diagnostics,
158    }
159}
160
161/// `-Zdump-mir=nll` dumps MIR annotated with NLL specific information:
162/// - free regions
163/// - inferred region values
164/// - region liveness
165/// - inference constraints and their causes
166///
167/// As well as graphviz `.dot` visualizations of:
168/// - the region constraints graph
169/// - the region SCC graph
170pub(super) fn dump_nll_mir<'tcx>(
171    infcx: &BorrowckInferCtxt<'tcx>,
172    body: &Body<'tcx>,
173    regioncx: &RegionInferenceContext<'tcx>,
174    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
175    borrow_set: &BorrowSet<'tcx>,
176) {
177    let tcx = infcx.tcx;
178    if !dump_enabled(tcx, "nll", body.source.def_id()) {
179        return;
180    }
181
182    // We want the NLL extra comments printed by default in NLL MIR dumps (they were removed in
183    // #112346). Specifying `-Z mir-include-spans` on the CLI still has priority: for example,
184    // they're always disabled in mir-opt tests to make working with blessed dumps easier.
185    let options = PrettyPrintMirOptions {
186        include_extra_comments: matches!(
187            infcx.tcx.sess.opts.unstable_opts.mir_include_spans,
188            MirIncludeSpans::On | MirIncludeSpans::Nll
189        ),
190    };
191    dump_mir_with_options(
192        tcx,
193        false,
194        "nll",
195        &0,
196        body,
197        |pass_where, out| {
198            emit_nll_mir(tcx, regioncx, closure_region_requirements, borrow_set, pass_where, out)
199        },
200        options,
201    );
202
203    // Also dump the region constraint graph as a graphviz file.
204    let _: io::Result<()> = try {
205        let mut file = create_dump_file(tcx, "regioncx.all.dot", false, "nll", &0, body)?;
206        regioncx.dump_graphviz_raw_constraints(tcx, &mut file)?;
207    };
208
209    // Also dump the region constraint SCC graph as a graphviz file.
210    let _: io::Result<()> = try {
211        let mut file = create_dump_file(tcx, "regioncx.scc.dot", false, "nll", &0, body)?;
212        regioncx.dump_graphviz_scc_constraints(tcx, &mut file)?;
213    };
214}
215
216/// Produces the actual NLL MIR sections to emit during the dumping process.
217pub(crate) fn emit_nll_mir<'tcx>(
218    tcx: TyCtxt<'tcx>,
219    regioncx: &RegionInferenceContext<'tcx>,
220    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
221    borrow_set: &BorrowSet<'tcx>,
222    pass_where: PassWhere,
223    out: &mut dyn io::Write,
224) -> io::Result<()> {
225    match pass_where {
226        // Before the CFG, dump out the values for each region variable.
227        PassWhere::BeforeCFG => {
228            regioncx.dump_mir(tcx, out)?;
229            writeln!(out, "|")?;
230
231            if let Some(closure_region_requirements) = closure_region_requirements {
232                writeln!(out, "| Free Region Constraints")?;
233                for_each_region_constraint(tcx, closure_region_requirements, &mut |msg| {
234                    writeln!(out, "| {msg}")
235                })?;
236                writeln!(out, "|")?;
237            }
238
239            if borrow_set.len() > 0 {
240                writeln!(out, "| Borrows")?;
241                for (borrow_idx, borrow_data) in borrow_set.iter_enumerated() {
242                    writeln!(
243                        out,
244                        "| {:?}: issued at {:?} in {:?}",
245                        borrow_idx, borrow_data.reserve_location, borrow_data.region
246                    )?;
247                }
248                writeln!(out, "|")?;
249            }
250        }
251
252        PassWhere::BeforeLocation(_) => {}
253
254        PassWhere::AfterTerminator(_) => {}
255
256        PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
257    }
258    Ok(())
259}
260
261#[allow(rustc::diagnostic_outside_of_impl)]
262#[allow(rustc::untranslatable_diagnostic)]
263pub(super) fn dump_annotation<'tcx, 'infcx>(
264    infcx: &'infcx BorrowckInferCtxt<'tcx>,
265    body: &Body<'tcx>,
266    regioncx: &RegionInferenceContext<'tcx>,
267    closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>,
268) {
269    let tcx = infcx.tcx;
270    let base_def_id = tcx.typeck_root_def_id(body.source.def_id());
271    if !tcx.has_attr(base_def_id, sym::rustc_regions) {
272        return;
273    }
274
275    // When the enclosing function is tagged with `#[rustc_regions]`,
276    // we dump out various bits of state as warnings. This is useful
277    // for verifying that the compiler is behaving as expected. These
278    // warnings focus on the closure region requirements -- for
279    // viewing the intraprocedural state, the -Zdump-mir output is
280    // better.
281
282    let def_span = tcx.def_span(body.source.def_id());
283    let err = if let Some(closure_region_requirements) = closure_region_requirements {
284        let mut err = infcx.dcx().struct_span_note(def_span, "external requirements");
285
286        regioncx.annotate(tcx, &mut err);
287
288        err.note(format!(
289            "number of external vids: {}",
290            closure_region_requirements.num_external_vids
291        ));
292
293        // Dump the region constraints we are imposing *between* those
294        // newly created variables.
295        for_each_region_constraint(tcx, closure_region_requirements, &mut |msg| {
296            err.note(msg);
297            Ok(())
298        })
299        .unwrap();
300
301        err
302    } else {
303        let mut err = infcx.dcx().struct_span_note(def_span, "no external requirements");
304        regioncx.annotate(tcx, &mut err);
305        err
306    };
307
308    // FIXME(@lcnr): We currently don't dump the inferred hidden types here.
309    err.emit();
310}
311
312fn for_each_region_constraint<'tcx>(
313    tcx: TyCtxt<'tcx>,
314    closure_region_requirements: &ClosureRegionRequirements<'tcx>,
315    with_msg: &mut dyn FnMut(String) -> io::Result<()>,
316) -> io::Result<()> {
317    for req in &closure_region_requirements.outlives_requirements {
318        let subject = match req.subject {
319            ClosureOutlivesSubject::Region(subject) => format!("{subject:?}"),
320            ClosureOutlivesSubject::Ty(ty) => {
321                with_no_trimmed_paths!(format!(
322                    "{}",
323                    ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid))
324                ))
325            }
326        };
327        with_msg(format!("where {}: {:?}", subject, req.outlived_free_region,))?;
328    }
329    Ok(())
330}
331
332pub(crate) trait ConstraintDescription {
333    fn description(&self) -> &'static str;
334}