]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/analyze.rs
Use slice patterns to match projection base
[rust.git] / src / librustc_codegen_ssa / mir / analyze.rs
1 //! An analysis to determine which locals require allocas and
2 //! which do not.
3
4 use rustc_data_structures::bit_set::BitSet;
5 use rustc_data_structures::graph::dominators::Dominators;
6 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
7 use rustc::mir::{self, Location, TerminatorKind};
8 use rustc::mir::visit::{Visitor, PlaceContext, MutatingUseContext, NonMutatingUseContext};
9 use rustc::mir::traversal;
10 use rustc::ty;
11 use rustc::ty::layout::{LayoutOf, HasTyCtxt};
12 use syntax_pos::DUMMY_SP;
13 use super::FunctionCx;
14 use crate::traits::*;
15
16 pub fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
17     fx: &FunctionCx<'a, 'tcx, Bx>,
18 ) -> BitSet<mir::Local> {
19     let mir = fx.mir;
20     let mut analyzer = LocalAnalyzer::new(fx);
21
22     analyzer.visit_body(mir);
23
24     for (index, (ty, span)) in mir.local_decls.iter()
25         .map(|l| (l.ty, l.source_info.span))
26         .enumerate()
27     {
28         let ty = fx.monomorphize(&ty);
29         debug!("local {} has type {:?}", index, ty);
30         let layout = fx.cx.spanned_layout_of(ty, span);
31         if fx.cx.is_backend_immediate(layout) {
32             // These sorts of types are immediates that we can store
33             // in an Value without an alloca.
34         } else if fx.cx.is_backend_scalar_pair(layout) {
35             // We allow pairs and uses of any of their 2 fields.
36         } else {
37             // These sorts of types require an alloca. Note that
38             // is_llvm_immediate() may *still* be true, particularly
39             // for newtypes, but we currently force some types
40             // (e.g., structs) into an alloca unconditionally, just so
41             // that we don't have to deal with having two pathways
42             // (gep vs extractvalue etc).
43             analyzer.not_ssa(mir::Local::new(index));
44         }
45     }
46
47     analyzer.non_ssa_locals
48 }
49
50 struct LocalAnalyzer<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
51     fx: &'mir FunctionCx<'a, 'tcx, Bx>,
52     dominators: Dominators<mir::BasicBlock>,
53     non_ssa_locals: BitSet<mir::Local>,
54     // The location of the first visited direct assignment to each
55     // local, or an invalid location (out of bounds `block` index).
56     first_assignment: IndexVec<mir::Local, Location>,
57 }
58
59 impl<Bx: BuilderMethods<'a, 'tcx>> LocalAnalyzer<'mir, 'a, 'tcx, Bx> {
60     fn new(fx: &'mir FunctionCx<'a, 'tcx, Bx>) -> Self {
61         let invalid_location =
62             mir::BasicBlock::new(fx.mir.basic_blocks().len()).start_location();
63         let mut analyzer = LocalAnalyzer {
64             fx,
65             dominators: fx.mir.dominators(),
66             non_ssa_locals: BitSet::new_empty(fx.mir.local_decls.len()),
67             first_assignment: IndexVec::from_elem(invalid_location, &fx.mir.local_decls)
68         };
69
70         // Arguments get assigned to by means of the function being called
71         for arg in fx.mir.args_iter() {
72             analyzer.first_assignment[arg] = mir::START_BLOCK.start_location();
73         }
74
75         analyzer
76     }
77
78     fn first_assignment(&self, local: mir::Local) -> Option<Location> {
79         let location = self.first_assignment[local];
80         if location.block.index() < self.fx.mir.basic_blocks().len() {
81             Some(location)
82         } else {
83             None
84         }
85     }
86
87     fn not_ssa(&mut self, local: mir::Local) {
88         debug!("marking {:?} as non-SSA", local);
89         self.non_ssa_locals.insert(local);
90     }
91
92     fn assign(&mut self, local: mir::Local, location: Location) {
93         if self.first_assignment(local).is_some() {
94             self.not_ssa(local);
95         } else {
96             self.first_assignment[local] = location;
97         }
98     }
99
100     fn process_place(
101         &mut self,
102         place_ref: &mir::PlaceRef<'_, 'tcx>,
103         context: PlaceContext,
104         location: Location,
105     ) {
106         let cx = self.fx.cx;
107
108         if let [proj_base @ .., elem] = place_ref.projection {
109             // Allow uses of projections that are ZSTs or from scalar fields.
110             let is_consume = match context {
111                 PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) |
112                 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) => true,
113                 _ => false
114             };
115             if is_consume {
116                 let base_ty =
117                     mir::Place::ty_from(place_ref.base, proj_base, self.fx.mir, cx.tcx());
118                 let base_ty = self.fx.monomorphize(&base_ty);
119
120                 // ZSTs don't require any actual memory access.
121                 let elem_ty = base_ty
122                     .projection_ty(cx.tcx(), elem)
123                     .ty;
124                 let elem_ty = self.fx.monomorphize(&elem_ty);
125                 let span = if let mir::PlaceBase::Local(index) = place_ref.base {
126                     self.fx.mir.local_decls[*index].source_info.span
127                 } else {
128                     DUMMY_SP
129                 };
130                 if cx.spanned_layout_of(elem_ty, span).is_zst() {
131                     return;
132                 }
133
134                 if let mir::ProjectionElem::Field(..) = elem {
135                     let layout = cx.spanned_layout_of(base_ty.ty, span);
136                     if cx.is_backend_immediate(layout) || cx.is_backend_scalar_pair(layout) {
137                         // Recurse with the same context, instead of `Projection`,
138                         // potentially stopping at non-operand projections,
139                         // which would trigger `not_ssa` on locals.
140                         self.process_place(
141                             &mir::PlaceRef {
142                                 base: place_ref.base,
143                                 projection: proj_base,
144                             },
145                             context,
146                             location,
147                         );
148                         return;
149                     }
150                 }
151             }
152
153             // A deref projection only reads the pointer, never needs the place.
154             if let mir::ProjectionElem::Deref = elem {
155                 self.process_place(
156                     &mir::PlaceRef {
157                         base: place_ref.base,
158                         projection: proj_base,
159                     },
160                     PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
161                     location
162                 );
163                 return;
164             }
165         }
166
167         // FIXME this is super_place code, is repeated here to avoid cloning place or changing
168         // visit_place API
169         let mut context = context;
170
171         if !place_ref.projection.is_empty() {
172             context = if context.is_mutating_use() {
173                 PlaceContext::MutatingUse(MutatingUseContext::Projection)
174             } else {
175                 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
176             };
177         }
178
179         self.visit_place_base(place_ref.base, context, location);
180         self.visit_projection(place_ref.base, place_ref.projection, context, location);
181     }
182
183 }
184
185 impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx>
186     for LocalAnalyzer<'mir, 'a, 'tcx, Bx>
187 {
188     fn visit_assign(&mut self,
189                     place: &mir::Place<'tcx>,
190                     rvalue: &mir::Rvalue<'tcx>,
191                     location: Location) {
192         debug!("visit_assign(place={:?}, rvalue={:?})", place, rvalue);
193
194         if let mir::Place {
195             base: mir::PlaceBase::Local(index),
196             projection: box [],
197         } = *place {
198             self.assign(index, location);
199             let decl_span = self.fx.mir.local_decls[index].source_info.span;
200             if !self.fx.rvalue_creates_operand(rvalue, decl_span) {
201                 self.not_ssa(index);
202             }
203         } else {
204             self.visit_place(
205                 place,
206                 PlaceContext::MutatingUse(MutatingUseContext::Store),
207                 location
208             );
209         }
210
211         self.visit_rvalue(rvalue, location);
212     }
213
214     fn visit_terminator_kind(&mut self,
215                              kind: &mir::TerminatorKind<'tcx>,
216                              location: Location) {
217         let check = match *kind {
218             mir::TerminatorKind::Call {
219                 func: mir::Operand::Constant(ref c),
220                 ref args, ..
221             } => match c.literal.ty.sty {
222                 ty::FnDef(did, _) => Some((did, args)),
223                 _ => None,
224             },
225             _ => None,
226         };
227         if let Some((def_id, args)) = check {
228             if Some(def_id) == self.fx.cx.tcx().lang_items().box_free_fn() {
229                 // box_free(x) shares with `drop x` the property that it
230                 // is not guaranteed to be statically dominated by the
231                 // definition of x, so x must always be in an alloca.
232                 if let mir::Operand::Move(ref place) = args[0] {
233                     self.visit_place(
234                         place,
235                         PlaceContext::MutatingUse(MutatingUseContext::Drop),
236                         location
237                     );
238                 }
239             }
240         }
241
242         self.super_terminator_kind(kind, location);
243     }
244
245     fn visit_place(&mut self,
246                    place: &mir::Place<'tcx>,
247                    context: PlaceContext,
248                    location: Location) {
249         debug!("visit_place(place={:?}, context={:?})", place, context);
250         self.process_place(&place.as_ref(), context, location);
251     }
252
253     fn visit_local(&mut self,
254                    &local: &mir::Local,
255                    context: PlaceContext,
256                    location: Location) {
257         match context {
258             PlaceContext::MutatingUse(MutatingUseContext::Call) => {
259                 self.assign(local, location);
260             }
261
262             PlaceContext::NonUse(_) |
263             PlaceContext::MutatingUse(MutatingUseContext::Retag) => {}
264
265             PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) |
266             PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) => {
267                 // Reads from uninitialized variables (e.g., in dead code, after
268                 // optimizations) require locals to be in (uninitialized) memory.
269                 // N.B., there can be uninitialized reads of a local visited after
270                 // an assignment to that local, if they happen on disjoint paths.
271                 let ssa_read = match self.first_assignment(local) {
272                     Some(assignment_location) => {
273                         assignment_location.dominates(location, &self.dominators)
274                     }
275                     None => false
276                 };
277                 if !ssa_read {
278                     self.not_ssa(local);
279                 }
280             }
281
282             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect) |
283             PlaceContext::MutatingUse(MutatingUseContext::Store) |
284             PlaceContext::MutatingUse(MutatingUseContext::AsmOutput) |
285             PlaceContext::MutatingUse(MutatingUseContext::Borrow) |
286             PlaceContext::MutatingUse(MutatingUseContext::Projection) |
287             PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow) |
288             PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow) |
289             PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow) |
290             PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection) => {
291                 self.not_ssa(local);
292             }
293
294             PlaceContext::MutatingUse(MutatingUseContext::Drop) => {
295                 let ty = self.fx.mir.local_decls[local].ty;
296                 let ty = self.fx.monomorphize(&ty);
297
298                 // Only need the place if we're actually dropping it.
299                 if self.fx.cx.type_needs_drop(ty) {
300                     self.not_ssa(local);
301                 }
302             }
303         }
304     }
305 }
306
307 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
308 pub enum CleanupKind {
309     NotCleanup,
310     Funclet,
311     Internal { funclet: mir::BasicBlock }
312 }
313
314 impl CleanupKind {
315     pub fn funclet_bb(self, for_bb: mir::BasicBlock) -> Option<mir::BasicBlock> {
316         match self {
317             CleanupKind::NotCleanup => None,
318             CleanupKind::Funclet => Some(for_bb),
319             CleanupKind::Internal { funclet } => Some(funclet),
320         }
321     }
322 }
323
324 pub fn cleanup_kinds(mir: &mir::Body<'_>) -> IndexVec<mir::BasicBlock, CleanupKind> {
325     fn discover_masters<'tcx>(result: &mut IndexVec<mir::BasicBlock, CleanupKind>,
326                               mir: &mir::Body<'tcx>) {
327         for (bb, data) in mir.basic_blocks().iter_enumerated() {
328             match data.terminator().kind {
329                 TerminatorKind::Goto { .. } |
330                 TerminatorKind::Resume |
331                 TerminatorKind::Abort |
332                 TerminatorKind::Return |
333                 TerminatorKind::GeneratorDrop |
334                 TerminatorKind::Unreachable |
335                 TerminatorKind::SwitchInt { .. } |
336                 TerminatorKind::Yield { .. } |
337                 TerminatorKind::FalseEdges { .. } |
338                 TerminatorKind::FalseUnwind { .. } => {
339                     /* nothing to do */
340                 }
341                 TerminatorKind::Call { cleanup: unwind, .. } |
342                 TerminatorKind::Assert { cleanup: unwind, .. } |
343                 TerminatorKind::DropAndReplace { unwind, .. } |
344                 TerminatorKind::Drop { unwind, .. } => {
345                     if let Some(unwind) = unwind {
346                         debug!("cleanup_kinds: {:?}/{:?} registering {:?} as funclet",
347                                bb, data, unwind);
348                         result[unwind] = CleanupKind::Funclet;
349                     }
350                 }
351             }
352         }
353     }
354
355     fn propagate<'tcx>(result: &mut IndexVec<mir::BasicBlock, CleanupKind>,
356                        mir: &mir::Body<'tcx>) {
357         let mut funclet_succs = IndexVec::from_elem(None, mir.basic_blocks());
358
359         let mut set_successor = |funclet: mir::BasicBlock, succ| {
360             match funclet_succs[funclet] {
361                 ref mut s @ None => {
362                     debug!("set_successor: updating successor of {:?} to {:?}",
363                            funclet, succ);
364                     *s = Some(succ);
365                 },
366                 Some(s) => if s != succ {
367                     span_bug!(mir.span, "funclet {:?} has 2 parents - {:?} and {:?}",
368                               funclet, s, succ);
369                 }
370             }
371         };
372
373         for (bb, data) in traversal::reverse_postorder(mir) {
374             let funclet = match result[bb] {
375                 CleanupKind::NotCleanup => continue,
376                 CleanupKind::Funclet => bb,
377                 CleanupKind::Internal { funclet } => funclet,
378             };
379
380             debug!("cleanup_kinds: {:?}/{:?}/{:?} propagating funclet {:?}",
381                    bb, data, result[bb], funclet);
382
383             for &succ in data.terminator().successors() {
384                 let kind = result[succ];
385                 debug!("cleanup_kinds: propagating {:?} to {:?}/{:?}",
386                        funclet, succ, kind);
387                 match kind {
388                     CleanupKind::NotCleanup => {
389                         result[succ] = CleanupKind::Internal { funclet };
390                     }
391                     CleanupKind::Funclet => {
392                         if funclet != succ {
393                             set_successor(funclet, succ);
394                         }
395                     }
396                     CleanupKind::Internal { funclet: succ_funclet } => {
397                         if funclet != succ_funclet {
398                             // `succ` has 2 different funclet going into it, so it must
399                             // be a funclet by itself.
400
401                             debug!("promoting {:?} to a funclet and updating {:?}", succ,
402                                    succ_funclet);
403                             result[succ] = CleanupKind::Funclet;
404                             set_successor(succ_funclet, succ);
405                             set_successor(funclet, succ);
406                         }
407                     }
408                 }
409             }
410         }
411     }
412
413     let mut result = IndexVec::from_elem(CleanupKind::NotCleanup, mir.basic_blocks());
414
415     discover_masters(&mut result, mir);
416     propagate(&mut result, mir);
417     debug!("cleanup_kinds: result={:?}", result);
418     result
419 }