]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_borrowck/src/type_check/liveness/trace.rs
New upstream version 1.57.0+dfsg1
[rustc.git] / compiler / rustc_borrowck / src / type_check / liveness / trace.rs
CommitLineData
e74abb32 1use rustc_data_structures::fx::{FxHashMap, FxHashSet};
dfeec247 2use rustc_index::bit_set::HybridBitSet;
74b04a01 3use rustc_infer::infer::canonical::QueryRegionConstraints;
f9f354fc 4use rustc_middle::mir::{BasicBlock, Body, ConstraintCategory, Local, Location};
ba9703b0
XL
5use rustc_middle::ty::{Ty, TypeFoldable};
6use rustc_trait_selection::traits::query::dropck_outlives::DropckOutlivesResult;
7use rustc_trait_selection::traits::query::type_op::outlives::DropckOutlives;
94222f64 8use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
b7449926 9use std::rc::Rc;
b7449926 10
c295e0f8
XL
11use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
12use rustc_mir_dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex};
13use rustc_mir_dataflow::ResultsCursor;
60c5eb7d 14
c295e0f8 15use crate::{
60c5eb7d
XL
16 region_infer::values::{self, PointIndex, RegionValueElements},
17 type_check::liveness::local_use_map::LocalUseMap,
18 type_check::liveness::polonius,
19 type_check::NormalizeLocation,
20 type_check::TypeChecker,
21};
22
b7449926
XL
23/// This is the heart of the liveness computation. For each variable X
24/// that requires a liveness computation, it walks over all the uses
25/// of X and does a reverse depth-first search ("trace") through the
26/// MIR. This search stops when we find a definition of that variable.
27/// The points visited in this search is the USE-LIVE set for the variable;
28/// of those points is added to all the regions that appear in the variable's
29/// type.
30///
31/// We then also walks through each *drop* of those variables and does
32/// another search, stopping when we reach a use or definition. This
33/// is the DROP-LIVE set of points. Each of the points in the
34/// DROP-LIVE set are to the liveness sets for regions found in the
35/// `dropck_outlives` result of the variable's type (in particular,
36/// this respects `#[may_dangle]` annotations).
37pub(super) fn trace(
dc9dc135 38 typeck: &mut TypeChecker<'_, 'tcx>,
f9f354fc 39 body: &Body<'tcx>,
b7449926 40 elements: &Rc<RegionValueElements>,
74b04a01 41 flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
b7449926 42 move_data: &MoveData<'tcx>,
532ac7d7 43 live_locals: Vec<Local>,
e74abb32 44 polonius_drop_used: Option<Vec<(Local, Location)>>,
b7449926
XL
45) {
46 debug!("trace()");
47
dc9dc135 48 let local_use_map = &LocalUseMap::build(&live_locals, elements, body);
b7449926
XL
49
50 let cx = LivenessContext {
51 typeck,
dc9dc135 52 body,
b7449926
XL
53 flow_inits,
54 elements,
55 local_use_map,
56 move_data,
b7449926
XL
57 drop_data: FxHashMap::default(),
58 };
59
e74abb32
XL
60 let mut results = LivenessResults::new(cx);
61
62 if let Some(drop_used) = polonius_drop_used {
63 results.add_extra_drop_facts(drop_used, live_locals.iter().copied().collect())
64 }
65
66 results.compute_for_all_locals(live_locals);
b7449926
XL
67}
68
69/// Contextual state for the type-liveness generator.
dc9dc135 70struct LivenessContext<'me, 'typeck, 'flow, 'tcx> {
b7449926 71 /// Current type-checker, giving us our inference context etc.
dc9dc135 72 typeck: &'me mut TypeChecker<'typeck, 'tcx>,
b7449926
XL
73
74 /// Defines the `PointIndex` mapping
75 elements: &'me RegionValueElements,
76
77 /// MIR we are analyzing.
f9f354fc 78 body: &'me Body<'tcx>,
b7449926
XL
79
80 /// Mapping to/from the various indices used for initialization tracking.
81 move_data: &'me MoveData<'tcx>,
82
83 /// Cache for the results of `dropck_outlives` query.
84 drop_data: FxHashMap<Ty<'tcx>, DropData<'tcx>>,
85
86 /// Results of dataflow tracking which variables (and paths) have been
87 /// initialized.
74b04a01 88 flow_inits: &'me mut ResultsCursor<'flow, 'tcx, MaybeInitializedPlaces<'flow, 'tcx>>,
b7449926
XL
89
90 /// Index indicating where each variable is assigned, used, or
91 /// dropped.
532ac7d7 92 local_use_map: &'me LocalUseMap,
b7449926
XL
93}
94
95struct DropData<'tcx> {
96 dropck_result: DropckOutlivesResult<'tcx>,
dc9dc135 97 region_constraint_data: Option<Rc<QueryRegionConstraints<'tcx>>>,
b7449926
XL
98}
99
dc9dc135
XL
100struct LivenessResults<'me, 'typeck, 'flow, 'tcx> {
101 cx: LivenessContext<'me, 'typeck, 'flow, 'tcx>,
b7449926
XL
102
103 /// Set of points that define the current local.
0bf4aa26 104 defs: HybridBitSet<PointIndex>,
b7449926
XL
105
106 /// Points where the current variable is "use live" -- meaning
107 /// that there is a future "full use" that may use its value.
0bf4aa26 108 use_live_at: HybridBitSet<PointIndex>,
b7449926
XL
109
110 /// Points where the current variable is "drop live" -- meaning
111 /// that there is no future "full use" that may use its value, but
112 /// there is a future drop.
0bf4aa26 113 drop_live_at: HybridBitSet<PointIndex>,
b7449926
XL
114
115 /// Locations where drops may occur.
116 drop_locations: Vec<Location>,
117
118 /// Stack used when doing (reverse) DFS.
119 stack: Vec<PointIndex>,
120}
121
dc9dc135
XL
122impl LivenessResults<'me, 'typeck, 'flow, 'tcx> {
123 fn new(cx: LivenessContext<'me, 'typeck, 'flow, 'tcx>) -> Self {
b7449926
XL
124 let num_points = cx.elements.num_points();
125 LivenessResults {
126 cx,
0bf4aa26
XL
127 defs: HybridBitSet::new_empty(num_points),
128 use_live_at: HybridBitSet::new_empty(num_points),
129 drop_live_at: HybridBitSet::new_empty(num_points),
b7449926
XL
130 drop_locations: vec![],
131 stack: vec![],
132 }
133 }
134
532ac7d7
XL
135 fn compute_for_all_locals(&mut self, live_locals: Vec<Local>) {
136 for local in live_locals {
b7449926 137 self.reset_local_state();
532ac7d7
XL
138 self.add_defs_for(local);
139 self.compute_use_live_points_for(local);
140 self.compute_drop_live_points_for(local);
b7449926 141
dc9dc135 142 let local_ty = self.cx.body.local_decls[local].ty;
b7449926
XL
143
144 if !self.use_live_at.is_empty() {
145 self.cx.add_use_live_facts_for(local_ty, &self.use_live_at);
146 }
147
148 if !self.drop_live_at.is_empty() {
149 self.cx.add_drop_live_facts_for(
150 local,
151 local_ty,
152 &self.drop_locations,
153 &self.drop_live_at,
154 );
155 }
156 }
157 }
158
e74abb32
XL
159 /// Add extra drop facts needed for Polonius.
160 ///
161 /// Add facts for all locals with free regions, since regions may outlive
162 /// the function body only at certain nodes in the CFG.
163 fn add_extra_drop_facts(
164 &mut self,
165 drop_used: Vec<(Local, Location)>,
166 live_locals: FxHashSet<Local>,
167 ) {
168 let locations = HybridBitSet::new_empty(self.cx.elements.num_points());
169
170 for (local, location) in drop_used {
171 if !live_locals.contains(&local) {
172 let local_ty = self.cx.body.local_decls[local].ty;
94222f64 173 if local_ty.has_free_regions(self.cx.typeck.tcx()) {
dfeec247 174 self.cx.add_drop_live_facts_for(local, local_ty, &[location], &locations);
e74abb32
XL
175 }
176 }
177 }
178 }
179
b7449926
XL
180 /// Clear the value of fields that are "per local variable".
181 fn reset_local_state(&mut self) {
182 self.defs.clear();
183 self.use_live_at.clear();
184 self.drop_live_at.clear();
185 self.drop_locations.clear();
186 assert!(self.stack.is_empty());
187 }
188
189 /// Adds the definitions of `local` into `self.defs`.
532ac7d7
XL
190 fn add_defs_for(&mut self, local: Local) {
191 for def in self.cx.local_use_map.defs(local) {
b7449926
XL
192 debug!("- defined at {:?}", def);
193 self.defs.insert(def);
194 }
195 }
196
9fa01778 197 /// Computes all points where local is "use live" -- meaning its
b7449926 198 /// current value may be used later (except by a drop). This is
532ac7d7 199 /// done by walking backwards from each use of `local` until we
b7449926
XL
200 /// find a `def` of local.
201 ///
532ac7d7
XL
202 /// Requires `add_defs_for(local)` to have been executed.
203 fn compute_use_live_points_for(&mut self, local: Local) {
204 debug!("compute_use_live_points_for(local={:?})", local);
b7449926 205
532ac7d7 206 self.stack.extend(self.cx.local_use_map.uses(local));
b7449926
XL
207 while let Some(p) = self.stack.pop() {
208 if self.defs.contains(p) {
209 continue;
210 }
211
212 if self.use_live_at.insert(p) {
416331ca 213 self.cx.elements.push_predecessors(self.cx.body, p, &mut self.stack)
b7449926
XL
214 }
215 }
216 }
217
9fa01778 218 /// Computes all points where local is "drop live" -- meaning its
b7449926
XL
219 /// current value may be dropped later (but not used). This is
220 /// done by iterating over the drops of `local` where `local` (or
221 /// some subpart of `local`) is initialized. For each such drop,
222 /// we walk backwards until we find a point where `local` is
223 /// either defined or use-live.
224 ///
225 /// Requires `compute_use_live_points_for` and `add_defs_for` to
226 /// have been executed.
532ac7d7
XL
227 fn compute_drop_live_points_for(&mut self, local: Local) {
228 debug!("compute_drop_live_points_for(local={:?})", local);
b7449926 229
b7449926
XL
230 let mpi = self.cx.move_data.rev_lookup.find_local(local);
231 debug!("compute_drop_live_points_for: mpi = {:?}", mpi);
232
233 // Find the drops where `local` is initialized.
532ac7d7 234 for drop_point in self.cx.local_use_map.drops(local) {
b7449926 235 let location = self.cx.elements.to_location(drop_point);
dc9dc135 236 debug_assert_eq!(self.cx.body.terminator_loc(location.block), location,);
b7449926
XL
237
238 if self.cx.initialized_at_terminator(location.block, mpi) {
239 if self.drop_live_at.insert(drop_point) {
240 self.drop_locations.push(location);
241 self.stack.push(drop_point);
242 }
243 }
244 }
245
416331ca 246 debug!("compute_drop_live_points_for: drop_locations={:?}", self.drop_locations);
b7449926
XL
247
248 // Reverse DFS. But for drops, we do it a bit differently.
249 // The stack only ever stores *terminators of blocks*. Within
250 // a block, we walk back the statements in an inner loop.
60c5eb7d 251 while let Some(term_point) = self.stack.pop() {
b7449926
XL
252 self.compute_drop_live_points_for_block(mpi, term_point);
253 }
254 }
255
256 /// Executes one iteration of the drop-live analysis loop.
257 ///
258 /// The parameter `mpi` is the `MovePathIndex` of the local variable
259 /// we are currently analyzing.
260 ///
261 /// The point `term_point` represents some terminator in the MIR,
262 /// where the local `mpi` is drop-live on entry to that terminator.
263 ///
264 /// This method adds all drop-live points within the block and --
265 /// where applicable -- pushes the terminators of preceding blocks
266 /// onto `self.stack`.
267 fn compute_drop_live_points_for_block(&mut self, mpi: MovePathIndex, term_point: PointIndex) {
268 debug!(
269 "compute_drop_live_points_for_block(mpi={:?}, term_point={:?})",
270 self.cx.move_data.move_paths[mpi].place,
271 self.cx.elements.to_location(term_point),
272 );
273
274 // We are only invoked with terminators where `mpi` is
275 // drop-live on entry.
276 debug_assert!(self.drop_live_at.contains(term_point));
277
278 // Otherwise, scan backwards through the statements in the
279 // block. One of them may be either a definition or use
280 // live point.
281 let term_location = self.cx.elements.to_location(term_point);
416331ca 282 debug_assert_eq!(self.cx.body.terminator_loc(term_location.block), term_location,);
b7449926
XL
283 let block = term_location.block;
284 let entry_point = self.cx.elements.entry_point(term_location.block);
285 for p in (entry_point..term_point).rev() {
416331ca 286 debug!("compute_drop_live_points_for_block: p = {:?}", self.cx.elements.to_location(p));
b7449926
XL
287
288 if self.defs.contains(p) {
289 debug!("compute_drop_live_points_for_block: def site");
290 return;
291 }
292
293 if self.use_live_at.contains(p) {
294 debug!("compute_drop_live_points_for_block: use-live at {:?}", p);
295 return;
296 }
297
298 if !self.drop_live_at.insert(p) {
299 debug!("compute_drop_live_points_for_block: already drop-live");
300 return;
301 }
302 }
303
60c5eb7d 304 let body = self.cx.body;
f9f354fc 305 for &pred_block in body.predecessors()[block].iter() {
416331ca 306 debug!("compute_drop_live_points_for_block: pred_block = {:?}", pred_block,);
b7449926
XL
307
308 // Check whether the variable is (at least partially)
309 // initialized at the exit of this predecessor. If so, we
310 // want to enqueue it on our list. If not, go check the
311 // next block.
312 //
313 // Note that we only need to check whether `live_local`
314 // became de-initialized at basic block boundaries. If it
315 // were to become de-initialized within the block, that
316 // would have been a "use-live" transition in the earlier
317 // loop, and we'd have returned already.
318 //
319 // NB. It's possible that the pred-block ends in a call
320 // which stores to the variable; in that case, the
321 // variable may be uninitialized "at exit" because this
322 // call only considers the *unconditional effects* of the
323 // terminator. *But*, in that case, the terminator is also
324 // a *definition* of the variable, in which case we want
325 // to stop the search anyhow. (But see Note 1 below.)
326 if !self.cx.initialized_at_exit(pred_block, mpi) {
327 debug!("compute_drop_live_points_for_block: not initialized");
328 continue;
329 }
330
dc9dc135 331 let pred_term_loc = self.cx.body.terminator_loc(pred_block);
b7449926
XL
332 let pred_term_point = self.cx.elements.point_from_location(pred_term_loc);
333
334 // If the terminator of this predecessor either *assigns*
335 // our value or is a "normal use", then stop.
336 if self.defs.contains(pred_term_point) {
416331ca 337 debug!("compute_drop_live_points_for_block: defined at {:?}", pred_term_loc);
b7449926
XL
338 continue;
339 }
340
341 if self.use_live_at.contains(pred_term_point) {
416331ca 342 debug!("compute_drop_live_points_for_block: use-live at {:?}", pred_term_loc);
b7449926
XL
343 continue;
344 }
345
346 // Otherwise, we are drop-live on entry to the terminator,
347 // so walk it.
348 if self.drop_live_at.insert(pred_term_point) {
349 debug!("compute_drop_live_points_for_block: pushed to stack");
350 self.stack.push(pred_term_point);
351 }
352 }
353
354 // Note 1. There is a weird scenario that you might imagine
355 // being problematic here, but which actually cannot happen.
356 // The problem would be if we had a variable that *is* initialized
357 // (but dead) on entry to the terminator, and where the current value
358 // will be dropped in the case of unwind. In that case, we ought to
359 // consider `X` to be drop-live in between the last use and call.
360 // Here is the example:
361 //
362 // ```
363 // BB0 {
364 // X = ...
365 // use(X); // last use
366 // ... // <-- X ought to be drop-live here
367 // X = call() goto BB1 unwind BB2
368 // }
369 //
370 // BB1 {
371 // DROP(X)
372 // }
373 //
374 // BB2 {
375 // DROP(X)
376 // }
377 // ```
378 //
379 // However, the current code would, when walking back from BB2,
380 // simply stop and never explore BB0. This seems bad! But it turns
381 // out this code is flawed anyway -- note that the existing value of
382 // `X` would leak in the case where unwinding did *not* occur.
383 //
384 // What we *actually* generate is a store to a temporary
385 // for the call (`TMP = call()...`) and then a
386 // `DropAndReplace` to swap that with `X`
387 // (`DropAndReplace` has very particular semantics).
388 }
389}
390
dc9dc135 391impl LivenessContext<'_, '_, '_, 'tcx> {
74b04a01
XL
392 /// Returns `true` if the local variable (or some part of it) is initialized at the current
393 /// cursor position. Callers should call one of the `seek` methods immediately before to point
394 /// the cursor to the desired location.
395 fn initialized_at_curr_loc(&self, mpi: MovePathIndex) -> bool {
396 let state = self.flow_inits.get();
397 if state.contains(mpi) {
398 return true;
399 }
400
401 let move_paths = &self.flow_inits.analysis().move_data().move_paths;
402 move_paths[mpi].find_descendant(&move_paths, |mpi| state.contains(mpi)).is_some()
403 }
404
9fa01778 405 /// Returns `true` if the local variable (or some part of it) is initialized in
b7449926
XL
406 /// the terminator of `block`. We need to check this to determine if a
407 /// DROP of some local variable will have an effect -- note that
408 /// drops, as they may unwind, are always terminators.
409 fn initialized_at_terminator(&mut self, block: BasicBlock, mpi: MovePathIndex) -> bool {
f9f354fc 410 self.flow_inits.seek_before_primary_effect(self.body.terminator_loc(block));
74b04a01 411 self.initialized_at_curr_loc(mpi)
b7449926
XL
412 }
413
9fa01778 414 /// Returns `true` if the path `mpi` (or some part of it) is initialized at
b7449926
XL
415 /// the exit of `block`.
416 ///
417 /// **Warning:** Does not account for the result of `Call`
418 /// instructions.
419 fn initialized_at_exit(&mut self, block: BasicBlock, mpi: MovePathIndex) -> bool {
f9f354fc 420 self.flow_inits.seek_after_primary_effect(self.body.terminator_loc(block));
74b04a01 421 self.initialized_at_curr_loc(mpi)
b7449926
XL
422 }
423
9fa01778 424 /// Stores the result that all regions in `value` are live for the
b7449926
XL
425 /// points `live_at`.
426 fn add_use_live_facts_for(
427 &mut self,
428 value: impl TypeFoldable<'tcx>,
0bf4aa26 429 live_at: &HybridBitSet<PointIndex>,
b7449926
XL
430 ) {
431 debug!("add_use_live_facts_for(value={:?})", value);
432
e1599b0c 433 Self::make_all_regions_live(self.elements, &mut self.typeck, value, live_at)
b7449926
XL
434 }
435
436 /// Some variable with type `live_ty` is "drop live" at `location`
437 /// -- i.e., it may be dropped later. This means that *some* of
438 /// the regions in its type must be live at `location`. The
439 /// precise set will depend on the dropck constraints, and in
440 /// particular this takes `#[may_dangle]` into account.
441 fn add_drop_live_facts_for(
442 &mut self,
443 dropped_local: Local,
444 dropped_ty: Ty<'tcx>,
445 drop_locations: &[Location],
0bf4aa26 446 live_at: &HybridBitSet<PointIndex>,
b7449926
XL
447 ) {
448 debug!(
449 "add_drop_live_constraint(\
450 dropped_local={:?}, \
451 dropped_ty={:?}, \
452 drop_locations={:?}, \
453 live_at={:?})",
454 dropped_local,
455 dropped_ty,
456 drop_locations,
457 values::location_set_str(self.elements, live_at.iter()),
458 );
459
460 let drop_data = self.drop_data.entry(dropped_ty).or_insert_with({
461 let typeck = &mut self.typeck;
462 move || Self::compute_drop_data(typeck, dropped_ty)
463 });
464
465 if let Some(data) = &drop_data.region_constraint_data {
466 for &drop_location in drop_locations {
416331ca
XL
467 self.typeck.push_region_constraints(
468 drop_location.to_locations(),
469 ConstraintCategory::Boring,
470 data,
471 );
b7449926
XL
472 }
473 }
474
475 drop_data.dropck_result.report_overflows(
476 self.typeck.infcx.tcx,
dc9dc135 477 self.body.source_info(*drop_locations.first().unwrap()).span,
b7449926
XL
478 dropped_ty,
479 );
480
481 // All things in the `outlives` array may be touched by
482 // the destructor and must be live at this point.
483 for &kind in &drop_data.dropck_result.kinds {
e1599b0c 484 Self::make_all_regions_live(self.elements, &mut self.typeck, kind, live_at);
416331ca 485
74b04a01 486 polonius::add_drop_of_var_derefs_origin(&mut self.typeck, dropped_local, &kind);
b7449926
XL
487 }
488 }
489
490 fn make_all_regions_live(
491 elements: &RegionValueElements,
dc9dc135 492 typeck: &mut TypeChecker<'_, 'tcx>,
b7449926 493 value: impl TypeFoldable<'tcx>,
0bf4aa26 494 live_at: &HybridBitSet<PointIndex>,
b7449926
XL
495 ) {
496 debug!("make_all_regions_live(value={:?})", value);
497 debug!(
498 "make_all_regions_live: live_at={}",
499 values::location_set_str(elements, live_at.iter()),
500 );
501
502 let tcx = typeck.tcx();
503 tcx.for_each_free_region(&value, |live_region| {
416331ca
XL
504 let live_region_vid =
505 typeck.borrowck_context.universal_regions.to_region_vid(live_region);
506 typeck
507 .borrowck_context
b7449926
XL
508 .constraints
509 .liveness_constraints
510 .add_elements(live_region_vid, live_at);
b7449926
XL
511 });
512 }
513
514 fn compute_drop_data(
dc9dc135 515 typeck: &mut TypeChecker<'_, 'tcx>,
b7449926
XL
516 dropped_ty: Ty<'tcx>,
517 ) -> DropData<'tcx> {
518 debug!("compute_drop_data(dropped_ty={:?})", dropped_ty,);
519
520 let param_env = typeck.param_env;
94222f64 521 let TypeOpOutput { output, constraints, .. } =
416331ca
XL
522 param_env.and(DropckOutlives::new(dropped_ty)).fully_perform(typeck.infcx).unwrap();
523
94222f64 524 DropData { dropck_result: output, region_constraint_data: constraints }
b7449926
XL
525 }
526}