rustc_codegen_ssa/mir/
analyze.rs

1//! An analysis to determine which locals require allocas and
2//! which do not.
3
4use rustc_data_structures::graph::dominators::Dominators;
5use rustc_index::bit_set::DenseBitSet;
6use rustc_index::{IndexSlice, IndexVec};
7use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
8use rustc_middle::mir::{self, DefLocation, Location, TerminatorKind, traversal};
9use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
10use rustc_middle::{bug, span_bug};
11use tracing::debug;
12
13use super::FunctionCx;
14use crate::traits::*;
15
16pub(crate) fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
17    fx: &FunctionCx<'a, 'tcx, Bx>,
18    traversal_order: &[mir::BasicBlock],
19) -> DenseBitSet<mir::Local> {
20    let mir = fx.mir;
21    let dominators = mir.basic_blocks.dominators();
22    let locals = mir
23        .local_decls
24        .iter()
25        .map(|decl| {
26            let ty = fx.monomorphize(decl.ty);
27            let layout = fx.cx.spanned_layout_of(ty, decl.source_info.span);
28            if layout.is_zst() { LocalKind::ZST } else { LocalKind::Unused }
29        })
30        .collect();
31
32    let mut analyzer = LocalAnalyzer { fx, dominators, locals };
33
34    // Arguments get assigned to by means of the function being called
35    for arg in mir.args_iter() {
36        analyzer.define(arg, DefLocation::Argument);
37    }
38
39    // If there exists a local definition that dominates all uses of that local,
40    // the definition should be visited first. Traverse blocks in an order that
41    // is a topological sort of dominance partial order.
42    for bb in traversal_order.iter().copied() {
43        let data = &mir.basic_blocks[bb];
44        analyzer.visit_basic_block_data(bb, data);
45    }
46
47    let mut non_ssa_locals = DenseBitSet::new_empty(analyzer.locals.len());
48    for (local, kind) in analyzer.locals.iter_enumerated() {
49        if matches!(kind, LocalKind::Memory) {
50            non_ssa_locals.insert(local);
51        }
52    }
53
54    non_ssa_locals
55}
56
57#[derive(Copy, Clone, PartialEq, Eq)]
58enum LocalKind {
59    ZST,
60    /// A local that requires an alloca.
61    Memory,
62    /// A scalar or a scalar pair local that is neither defined nor used.
63    Unused,
64    /// A scalar or a scalar pair local with a single definition that dominates all uses.
65    SSA(DefLocation),
66}
67
68struct LocalAnalyzer<'a, 'b, 'tcx, Bx: BuilderMethods<'b, 'tcx>> {
69    fx: &'a FunctionCx<'b, 'tcx, Bx>,
70    dominators: &'a Dominators<mir::BasicBlock>,
71    locals: IndexVec<mir::Local, LocalKind>,
72}
73
74impl<'a, 'b, 'tcx, Bx: BuilderMethods<'b, 'tcx>> LocalAnalyzer<'a, 'b, 'tcx, Bx> {
75    fn define(&mut self, local: mir::Local, location: DefLocation) {
76        let fx = self.fx;
77        let kind = &mut self.locals[local];
78        let decl = &fx.mir.local_decls[local];
79        match *kind {
80            LocalKind::ZST => {}
81            LocalKind::Memory => {}
82            LocalKind::Unused => {
83                let ty = fx.monomorphize(decl.ty);
84                let layout = fx.cx.spanned_layout_of(ty, decl.source_info.span);
85                *kind =
86                    if fx.cx.is_backend_immediate(layout) || fx.cx.is_backend_scalar_pair(layout) {
87                        LocalKind::SSA(location)
88                    } else {
89                        LocalKind::Memory
90                    };
91            }
92            LocalKind::SSA(_) => *kind = LocalKind::Memory,
93        }
94    }
95
96    fn process_place(
97        &mut self,
98        place_ref: &mir::PlaceRef<'tcx>,
99        context: PlaceContext,
100        location: Location,
101    ) {
102        let cx = self.fx.cx;
103
104        if let Some((place_base, elem)) = place_ref.last_projection() {
105            let mut base_context = if context.is_mutating_use() {
106                PlaceContext::MutatingUse(MutatingUseContext::Projection)
107            } else {
108                PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
109            };
110
111            // Allow uses of projections that are ZSTs or from scalar fields.
112            let is_consume = matches!(
113                context,
114                PlaceContext::NonMutatingUse(
115                    NonMutatingUseContext::Copy | NonMutatingUseContext::Move,
116                )
117            );
118            if is_consume {
119                let base_ty = place_base.ty(self.fx.mir, cx.tcx());
120                let base_ty = self.fx.monomorphize(base_ty);
121
122                // ZSTs don't require any actual memory access.
123                let elem_ty = base_ty.projection_ty(cx.tcx(), self.fx.monomorphize(elem)).ty;
124                let span = self.fx.mir.local_decls[place_ref.local].source_info.span;
125                if cx.spanned_layout_of(elem_ty, span).is_zst() {
126                    return;
127                }
128
129                if let mir::ProjectionElem::Field(..) = elem {
130                    let layout = cx.spanned_layout_of(base_ty.ty, span);
131                    if cx.is_backend_immediate(layout) || cx.is_backend_scalar_pair(layout) {
132                        // Recurse with the same context, instead of `Projection`,
133                        // potentially stopping at non-operand projections,
134                        // which would trigger `not_ssa` on locals.
135                        base_context = context;
136                    }
137                }
138            }
139
140            if let mir::ProjectionElem::Deref = elem {
141                // Deref projections typically only read the pointer.
142                base_context = PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy);
143            }
144
145            self.process_place(&place_base, base_context, location);
146            // HACK(eddyb) this emulates the old `visit_projection_elem`, this
147            // entire `visit_place`-like `process_place` method should be rewritten,
148            // now that we have moved to the "slice of projections" representation.
149            if let mir::ProjectionElem::Index(local) = elem {
150                self.visit_local(
151                    local,
152                    PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
153                    location,
154                );
155            }
156        } else {
157            self.visit_local(place_ref.local, context, location);
158        }
159    }
160}
161
162impl<'a, 'b, 'tcx, Bx: BuilderMethods<'b, 'tcx>> Visitor<'tcx> for LocalAnalyzer<'a, 'b, 'tcx, Bx> {
163    fn visit_assign(
164        &mut self,
165        place: &mir::Place<'tcx>,
166        rvalue: &mir::Rvalue<'tcx>,
167        location: Location,
168    ) {
169        debug!("visit_assign(place={:?}, rvalue={:?})", place, rvalue);
170
171        if let Some(local) = place.as_local() {
172            self.define(local, DefLocation::Assignment(location));
173            if self.locals[local] != LocalKind::Memory {
174                if !self.fx.rvalue_creates_operand(rvalue) {
175                    self.locals[local] = LocalKind::Memory;
176                }
177            }
178        } else {
179            self.visit_place(place, PlaceContext::MutatingUse(MutatingUseContext::Store), location);
180        }
181
182        self.visit_rvalue(rvalue, location);
183    }
184
185    fn visit_place(&mut self, place: &mir::Place<'tcx>, context: PlaceContext, location: Location) {
186        debug!("visit_place(place={:?}, context={:?})", place, context);
187        self.process_place(&place.as_ref(), context, location);
188    }
189
190    fn visit_local(&mut self, local: mir::Local, context: PlaceContext, location: Location) {
191        match context {
192            PlaceContext::MutatingUse(MutatingUseContext::Call) => {
193                let call = location.block;
194                let TerminatorKind::Call { target, .. } =
195                    self.fx.mir.basic_blocks[call].terminator().kind
196                else {
197                    bug!()
198                };
199                self.define(local, DefLocation::CallReturn { call, target });
200            }
201
202            PlaceContext::NonUse(_)
203            | PlaceContext::NonMutatingUse(NonMutatingUseContext::PlaceMention)
204            | PlaceContext::MutatingUse(MutatingUseContext::Retag) => {}
205
206            PlaceContext::NonMutatingUse(
207                NonMutatingUseContext::Copy
208                | NonMutatingUseContext::Move
209                // Inspect covers things like `PtrMetadata` and `Discriminant`
210                // which we can treat similar to `Copy` use for the purpose of
211                // whether we can use SSA variables for things.
212                | NonMutatingUseContext::Inspect,
213            ) => match &mut self.locals[local] {
214                LocalKind::ZST => {}
215                LocalKind::Memory => {}
216                LocalKind::SSA(def) if def.dominates(location, self.dominators) => {}
217                // Reads from uninitialized variables (e.g., in dead code, after
218                // optimizations) require locals to be in (uninitialized) memory.
219                // N.B., there can be uninitialized reads of a local visited after
220                // an assignment to that local, if they happen on disjoint paths.
221                kind @ (LocalKind::Unused | LocalKind::SSA(_)) => {
222                    *kind = LocalKind::Memory;
223                }
224            },
225
226            PlaceContext::MutatingUse(
227                MutatingUseContext::Store
228                | MutatingUseContext::Deinit
229                | MutatingUseContext::SetDiscriminant
230                | MutatingUseContext::AsmOutput
231                | MutatingUseContext::Borrow
232                | MutatingUseContext::RawBorrow
233                | MutatingUseContext::Projection,
234            )
235            | PlaceContext::NonMutatingUse(
236                NonMutatingUseContext::SharedBorrow
237                | NonMutatingUseContext::FakeBorrow
238                | NonMutatingUseContext::RawBorrow
239                | NonMutatingUseContext::Projection,
240            ) => {
241                self.locals[local] = LocalKind::Memory;
242            }
243
244            PlaceContext::MutatingUse(MutatingUseContext::Drop) => {
245                let kind = &mut self.locals[local];
246                if *kind != LocalKind::Memory {
247                    let ty = self.fx.mir.local_decls[local].ty;
248                    let ty = self.fx.monomorphize(ty);
249                    if self.fx.cx.type_needs_drop(ty) {
250                        // Only need the place if we're actually dropping it.
251                        *kind = LocalKind::Memory;
252                    }
253                }
254            }
255
256            PlaceContext::MutatingUse(MutatingUseContext::Yield) => bug!(),
257        }
258    }
259}
260
261#[derive(Copy, Clone, Debug, PartialEq, Eq)]
262pub(crate) enum CleanupKind {
263    NotCleanup,
264    Funclet,
265    Internal { funclet: mir::BasicBlock },
266}
267
268impl CleanupKind {
269    pub(crate) fn funclet_bb(self, for_bb: mir::BasicBlock) -> Option<mir::BasicBlock> {
270        match self {
271            CleanupKind::NotCleanup => None,
272            CleanupKind::Funclet => Some(for_bb),
273            CleanupKind::Internal { funclet } => Some(funclet),
274        }
275    }
276}
277
278/// MSVC requires unwinding code to be split to a tree of *funclets*, where each funclet can only
279/// branch to itself or to its parent. Luckily, the code we generates matches this pattern.
280/// Recover that structure in an analyze pass.
281pub(crate) fn cleanup_kinds(mir: &mir::Body<'_>) -> IndexVec<mir::BasicBlock, CleanupKind> {
282    fn discover_masters<'tcx>(
283        result: &mut IndexSlice<mir::BasicBlock, CleanupKind>,
284        mir: &mir::Body<'tcx>,
285    ) {
286        for (bb, data) in mir.basic_blocks.iter_enumerated() {
287            match data.terminator().kind {
288                TerminatorKind::Goto { .. }
289                | TerminatorKind::UnwindResume
290                | TerminatorKind::UnwindTerminate(_)
291                | TerminatorKind::Return
292                | TerminatorKind::TailCall { .. }
293                | TerminatorKind::CoroutineDrop
294                | TerminatorKind::Unreachable
295                | TerminatorKind::SwitchInt { .. }
296                | TerminatorKind::Yield { .. }
297                | TerminatorKind::FalseEdge { .. }
298                | TerminatorKind::FalseUnwind { .. } => { /* nothing to do */ }
299                TerminatorKind::Call { unwind, .. }
300                | TerminatorKind::InlineAsm { unwind, .. }
301                | TerminatorKind::Assert { unwind, .. }
302                | TerminatorKind::Drop { unwind, .. } => {
303                    if let mir::UnwindAction::Cleanup(unwind) = unwind {
304                        debug!(
305                            "cleanup_kinds: {:?}/{:?} registering {:?} as funclet",
306                            bb, data, unwind
307                        );
308                        result[unwind] = CleanupKind::Funclet;
309                    }
310                }
311            }
312        }
313    }
314
315    fn propagate<'tcx>(
316        result: &mut IndexSlice<mir::BasicBlock, CleanupKind>,
317        mir: &mir::Body<'tcx>,
318    ) {
319        let mut funclet_succs = IndexVec::from_elem(None, &mir.basic_blocks);
320
321        let mut set_successor = |funclet: mir::BasicBlock, succ| match funclet_succs[funclet] {
322            ref mut s @ None => {
323                debug!("set_successor: updating successor of {:?} to {:?}", funclet, succ);
324                *s = Some(succ);
325            }
326            Some(s) => {
327                if s != succ {
328                    span_bug!(
329                        mir.span,
330                        "funclet {:?} has 2 parents - {:?} and {:?}",
331                        funclet,
332                        s,
333                        succ
334                    );
335                }
336            }
337        };
338
339        for (bb, data) in traversal::reverse_postorder(mir) {
340            let funclet = match result[bb] {
341                CleanupKind::NotCleanup => continue,
342                CleanupKind::Funclet => bb,
343                CleanupKind::Internal { funclet } => funclet,
344            };
345
346            debug!(
347                "cleanup_kinds: {:?}/{:?}/{:?} propagating funclet {:?}",
348                bb, data, result[bb], funclet
349            );
350
351            for succ in data.terminator().successors() {
352                let kind = result[succ];
353                debug!("cleanup_kinds: propagating {:?} to {:?}/{:?}", funclet, succ, kind);
354                match kind {
355                    CleanupKind::NotCleanup => {
356                        result[succ] = CleanupKind::Internal { funclet };
357                    }
358                    CleanupKind::Funclet => {
359                        if funclet != succ {
360                            set_successor(funclet, succ);
361                        }
362                    }
363                    CleanupKind::Internal { funclet: succ_funclet } => {
364                        if funclet != succ_funclet {
365                            // `succ` has 2 different funclet going into it, so it must
366                            // be a funclet by itself.
367
368                            debug!(
369                                "promoting {:?} to a funclet and updating {:?}",
370                                succ, succ_funclet
371                            );
372                            result[succ] = CleanupKind::Funclet;
373                            set_successor(succ_funclet, succ);
374                            set_successor(funclet, succ);
375                        }
376                    }
377                }
378            }
379        }
380    }
381
382    let mut result = IndexVec::from_elem(CleanupKind::NotCleanup, &mir.basic_blocks);
383
384    discover_masters(&mut result, mir);
385    propagate(&mut result, mir);
386    debug!("cleanup_kinds: result={:?}", result);
387    result
388}