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