rustc_mir_dataflow/impls/
storage_liveness.rs

1use std::borrow::Cow;
2use std::cell::RefCell;
3
4use rustc_index::bit_set::DenseBitSet;
5use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
6use rustc_middle::mir::*;
7
8use super::MaybeBorrowedLocals;
9use crate::{Analysis, GenKill, ResultsCursor};
10
11/// The set of locals in a MIR body that do not have `StorageLive`/`StorageDead` annotations.
12///
13/// These locals have fixed storage for the duration of the body.
14pub fn always_storage_live_locals(body: &Body<'_>) -> DenseBitSet<Local> {
15    let mut always_live_locals = DenseBitSet::new_filled(body.local_decls.len());
16
17    for block in &*body.basic_blocks {
18        for statement in &block.statements {
19            if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = statement.kind {
20                always_live_locals.remove(l);
21            }
22        }
23    }
24
25    always_live_locals
26}
27
28pub struct MaybeStorageLive<'a> {
29    always_live_locals: Cow<'a, DenseBitSet<Local>>,
30}
31
32impl<'a> MaybeStorageLive<'a> {
33    pub fn new(always_live_locals: Cow<'a, DenseBitSet<Local>>) -> Self {
34        MaybeStorageLive { always_live_locals }
35    }
36}
37
38impl<'a, 'tcx> Analysis<'tcx> for MaybeStorageLive<'a> {
39    type Domain = DenseBitSet<Local>;
40
41    const NAME: &'static str = "maybe_storage_live";
42
43    fn bottom_value(&self, body: &Body<'tcx>) -> Self::Domain {
44        // bottom = dead
45        DenseBitSet::new_empty(body.local_decls.len())
46    }
47
48    fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
49        state.union(&*self.always_live_locals);
50
51        for arg in body.args_iter() {
52            state.insert(arg);
53        }
54    }
55
56    fn apply_primary_statement_effect(
57        &self,
58        state: &mut Self::Domain,
59        stmt: &Statement<'tcx>,
60        _: Location,
61    ) {
62        match stmt.kind {
63            StatementKind::StorageLive(l) => state.gen_(l),
64            StatementKind::StorageDead(l) => state.kill(l),
65            _ => (),
66        }
67    }
68}
69
70pub struct MaybeStorageDead<'a> {
71    always_live_locals: Cow<'a, DenseBitSet<Local>>,
72}
73
74impl<'a> MaybeStorageDead<'a> {
75    pub fn new(always_live_locals: Cow<'a, DenseBitSet<Local>>) -> Self {
76        MaybeStorageDead { always_live_locals }
77    }
78}
79
80impl<'a, 'tcx> Analysis<'tcx> for MaybeStorageDead<'a> {
81    type Domain = DenseBitSet<Local>;
82
83    const NAME: &'static str = "maybe_storage_dead";
84
85    fn bottom_value(&self, body: &Body<'tcx>) -> Self::Domain {
86        // bottom = live
87        DenseBitSet::new_empty(body.local_decls.len())
88    }
89
90    fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
91        assert_eq!(body.local_decls.len(), self.always_live_locals.domain_size());
92        // Do not iterate on return place and args, as they are trivially always live.
93        for local in body.vars_and_temps_iter() {
94            if !self.always_live_locals.contains(local) {
95                state.insert(local);
96            }
97        }
98    }
99
100    fn apply_primary_statement_effect(
101        &self,
102        state: &mut Self::Domain,
103        stmt: &Statement<'tcx>,
104        _: Location,
105    ) {
106        match stmt.kind {
107            StatementKind::StorageLive(l) => state.kill(l),
108            StatementKind::StorageDead(l) => state.gen_(l),
109            _ => (),
110        }
111    }
112}
113
114type BorrowedLocalsResults<'mir, 'tcx> = ResultsCursor<'mir, 'tcx, MaybeBorrowedLocals>;
115
116/// Dataflow analysis that determines whether each local requires storage at a
117/// given location; i.e. whether its storage can go away without being observed.
118pub struct MaybeRequiresStorage<'mir, 'tcx> {
119    borrowed_locals: RefCell<BorrowedLocalsResults<'mir, 'tcx>>,
120}
121
122impl<'mir, 'tcx> MaybeRequiresStorage<'mir, 'tcx> {
123    pub fn new(borrowed_locals: BorrowedLocalsResults<'mir, 'tcx>) -> Self {
124        MaybeRequiresStorage { borrowed_locals: RefCell::new(borrowed_locals) }
125    }
126}
127
128impl<'tcx> Analysis<'tcx> for MaybeRequiresStorage<'_, 'tcx> {
129    type Domain = DenseBitSet<Local>;
130
131    const NAME: &'static str = "requires_storage";
132
133    fn bottom_value(&self, body: &Body<'tcx>) -> Self::Domain {
134        // bottom = dead
135        DenseBitSet::new_empty(body.local_decls.len())
136    }
137
138    fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
139        // The resume argument is live on function entry (we don't care about
140        // the `self` argument)
141        for arg in body.args_iter().skip(1) {
142            state.insert(arg);
143        }
144    }
145
146    fn apply_early_statement_effect(
147        &self,
148        state: &mut Self::Domain,
149        stmt: &Statement<'tcx>,
150        loc: Location,
151    ) {
152        // If a place is borrowed in a statement, it needs storage for that statement.
153        MaybeBorrowedLocals::transfer_function(state).visit_statement(stmt, loc);
154
155        match &stmt.kind {
156            StatementKind::StorageDead(l) => state.kill(*l),
157
158            // If a place is assigned to in a statement, it needs storage for that statement.
159            StatementKind::Assign(box (place, _))
160            | StatementKind::SetDiscriminant { box place, .. } => {
161                state.gen_(place.local);
162            }
163
164            // Nothing to do for these. Match exhaustively so this fails to compile when new
165            // variants are added.
166            StatementKind::AscribeUserType(..)
167            | StatementKind::PlaceMention(..)
168            | StatementKind::Coverage(..)
169            | StatementKind::FakeRead(..)
170            | StatementKind::ConstEvalCounter
171            | StatementKind::Nop
172            | StatementKind::Retag(..)
173            | StatementKind::Intrinsic(..)
174            | StatementKind::BackwardIncompatibleDropHint { .. }
175            | StatementKind::StorageLive(..) => {}
176        }
177    }
178
179    fn apply_primary_statement_effect(
180        &self,
181        state: &mut Self::Domain,
182        _: &Statement<'tcx>,
183        loc: Location,
184    ) {
185        // If we move from a place then it only stops needing storage *after*
186        // that statement.
187        self.check_for_move(state, loc);
188    }
189
190    fn apply_early_terminator_effect(
191        &self,
192        state: &mut Self::Domain,
193        terminator: &Terminator<'tcx>,
194        loc: Location,
195    ) {
196        // If a place is borrowed in a terminator, it needs storage for that terminator.
197        MaybeBorrowedLocals::transfer_function(state).visit_terminator(terminator, loc);
198
199        match &terminator.kind {
200            TerminatorKind::Call { destination, .. } => {
201                state.gen_(destination.local);
202            }
203
204            // Note that we do *not* gen the `resume_arg` of `Yield` terminators. The reason for
205            // that is that a `yield` will return from the function, and `resume_arg` is written
206            // only when the coroutine is later resumed. Unlike `Call`, this doesn't require the
207            // place to have storage *before* the yield, only after.
208            TerminatorKind::Yield { .. } => {}
209
210            TerminatorKind::InlineAsm { operands, .. } => {
211                for op in operands {
212                    match op {
213                        InlineAsmOperand::Out { place, .. }
214                        | InlineAsmOperand::InOut { out_place: place, .. } => {
215                            if let Some(place) = place {
216                                state.gen_(place.local);
217                            }
218                        }
219                        InlineAsmOperand::In { .. }
220                        | InlineAsmOperand::Const { .. }
221                        | InlineAsmOperand::SymFn { .. }
222                        | InlineAsmOperand::SymStatic { .. }
223                        | InlineAsmOperand::Label { .. } => {}
224                    }
225                }
226            }
227
228            // Nothing to do for these. Match exhaustively so this fails to compile when new
229            // variants are added.
230            TerminatorKind::UnwindTerminate(_)
231            | TerminatorKind::Assert { .. }
232            | TerminatorKind::Drop { .. }
233            | TerminatorKind::FalseEdge { .. }
234            | TerminatorKind::FalseUnwind { .. }
235            | TerminatorKind::CoroutineDrop
236            | TerminatorKind::Goto { .. }
237            | TerminatorKind::UnwindResume
238            | TerminatorKind::Return
239            | TerminatorKind::TailCall { .. }
240            | TerminatorKind::SwitchInt { .. }
241            | TerminatorKind::Unreachable => {}
242        }
243    }
244
245    fn apply_primary_terminator_effect<'t>(
246        &self,
247        state: &mut Self::Domain,
248        terminator: &'t Terminator<'tcx>,
249        loc: Location,
250    ) -> TerminatorEdges<'t, 'tcx> {
251        match terminator.kind {
252            // For call terminators the destination requires storage for the call
253            // and after the call returns successfully, but not after a panic.
254            // Since `propagate_call_unwind` doesn't exist, we have to kill the
255            // destination here, and then gen it again in `call_return_effect`.
256            TerminatorKind::Call { destination, .. } => {
257                state.kill(destination.local);
258            }
259
260            // The same applies to InlineAsm outputs.
261            TerminatorKind::InlineAsm { ref operands, .. } => {
262                CallReturnPlaces::InlineAsm(operands).for_each(|place| state.kill(place.local));
263            }
264
265            // Nothing to do for these. Match exhaustively so this fails to compile when new
266            // variants are added.
267            TerminatorKind::Yield { .. }
268            | TerminatorKind::UnwindTerminate(_)
269            | TerminatorKind::Assert { .. }
270            | TerminatorKind::Drop { .. }
271            | TerminatorKind::FalseEdge { .. }
272            | TerminatorKind::FalseUnwind { .. }
273            | TerminatorKind::CoroutineDrop
274            | TerminatorKind::Goto { .. }
275            | TerminatorKind::UnwindResume
276            | TerminatorKind::Return
277            | TerminatorKind::TailCall { .. }
278            | TerminatorKind::SwitchInt { .. }
279            | TerminatorKind::Unreachable => {}
280        }
281
282        self.check_for_move(state, loc);
283        terminator.edges()
284    }
285
286    fn apply_call_return_effect(
287        &self,
288        state: &mut Self::Domain,
289        _block: BasicBlock,
290        return_places: CallReturnPlaces<'_, 'tcx>,
291    ) {
292        return_places.for_each(|place| state.gen_(place.local));
293    }
294}
295
296impl<'tcx> MaybeRequiresStorage<'_, 'tcx> {
297    /// Kill locals that are fully moved and have not been borrowed.
298    fn check_for_move(&self, state: &mut <Self as Analysis<'tcx>>::Domain, loc: Location) {
299        let mut borrowed_locals = self.borrowed_locals.borrow_mut();
300        let body = borrowed_locals.body();
301        let mut visitor = MoveVisitor { state, borrowed_locals: &mut borrowed_locals };
302        visitor.visit_location(body, loc);
303    }
304}
305
306struct MoveVisitor<'a, 'mir, 'tcx> {
307    borrowed_locals: &'a mut BorrowedLocalsResults<'mir, 'tcx>,
308    state: &'a mut DenseBitSet<Local>,
309}
310
311impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, 'tcx> {
312    fn visit_local(&mut self, local: Local, context: PlaceContext, loc: Location) {
313        if PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) == context {
314            self.borrowed_locals.seek_before_primary_effect(loc);
315            if !self.borrowed_locals.get().contains(local) {
316                self.state.kill(local);
317            }
318        }
319    }
320}