1 //! An analysis to determine which locals require allocas and
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;
11 use rustc::ty::layout::{LayoutOf, HasTyCtxt};
12 use syntax_pos::DUMMY_SP;
13 use super::FunctionCx;
16 pub fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
17 fx: &FunctionCx<'a, 'tcx, Bx>,
18 ) -> BitSet<mir::Local> {
20 let mut analyzer = LocalAnalyzer::new(fx);
22 analyzer.visit_body(mir);
24 for (index, (ty, span)) in mir.local_decls.iter()
25 .map(|l| (l.ty, l.source_info.span))
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.
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));
47 analyzer.non_ssa_locals
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>,
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 {
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)
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();
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() {
87 fn not_ssa(&mut self, local: mir::Local) {
88 debug!("marking {:?} as non-SSA", local);
89 self.non_ssa_locals.insert(local);
92 fn assign(&mut self, local: mir::Local, location: Location) {
93 if self.first_assignment(local).is_some() {
96 self.first_assignment[local] = location;
102 place_ref: &mir::PlaceRef<'_, 'tcx>,
103 context: PlaceContext,
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,
117 mir::Place::ty_from(place_ref.base, proj_base, self.fx.mir, cx.tcx());
118 let base_ty = self.fx.monomorphize(&base_ty);
120 // ZSTs don't require any actual memory access.
121 let elem_ty = base_ty
122 .projection_ty(cx.tcx(), elem)
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
130 if cx.spanned_layout_of(elem_ty, span).is_zst() {
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.
142 base: place_ref.base,
143 projection: proj_base,
153 // A deref projection only reads the pointer, never needs the place.
154 if let mir::ProjectionElem::Deref = elem {
157 base: place_ref.base,
158 projection: proj_base,
160 PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
167 // FIXME this is super_place code, is repeated here to avoid cloning place or changing
169 let mut context = context;
171 if !place_ref.projection.is_empty() {
172 context = if context.is_mutating_use() {
173 PlaceContext::MutatingUse(MutatingUseContext::Projection)
175 PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
179 self.visit_place_base(place_ref.base, context, location);
180 self.visit_projection(place_ref.base, place_ref.projection, context, location);
185 impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx>
186 for LocalAnalyzer<'mir, 'a, 'tcx, Bx>
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);
195 base: mir::PlaceBase::Local(index),
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) {
206 PlaceContext::MutatingUse(MutatingUseContext::Store),
211 self.visit_rvalue(rvalue, location);
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),
221 } => match c.literal.ty.sty {
222 ty::FnDef(did, _) => Some((did, args)),
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] {
235 PlaceContext::MutatingUse(MutatingUseContext::Drop),
242 self.super_terminator_kind(kind, location);
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);
253 fn visit_local(&mut self,
255 context: PlaceContext,
256 location: Location) {
258 PlaceContext::MutatingUse(MutatingUseContext::Call) => {
259 self.assign(local, location);
262 PlaceContext::NonUse(_) |
263 PlaceContext::MutatingUse(MutatingUseContext::Retag) => {}
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)
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) => {
294 PlaceContext::MutatingUse(MutatingUseContext::Drop) => {
295 let ty = self.fx.mir.local_decls[local].ty;
296 let ty = self.fx.monomorphize(&ty);
298 // Only need the place if we're actually dropping it.
299 if self.fx.cx.type_needs_drop(ty) {
307 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
308 pub enum CleanupKind {
311 Internal { funclet: mir::BasicBlock }
315 pub fn funclet_bb(self, for_bb: mir::BasicBlock) -> Option<mir::BasicBlock> {
317 CleanupKind::NotCleanup => None,
318 CleanupKind::Funclet => Some(for_bb),
319 CleanupKind::Internal { funclet } => Some(funclet),
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 { .. } => {
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",
348 result[unwind] = CleanupKind::Funclet;
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());
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 {:?}",
366 Some(s) => if s != succ {
367 span_bug!(mir.span, "funclet {:?} has 2 parents - {:?} and {:?}",
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,
380 debug!("cleanup_kinds: {:?}/{:?}/{:?} propagating funclet {:?}",
381 bb, data, result[bb], funclet);
383 for &succ in data.terminator().successors() {
384 let kind = result[succ];
385 debug!("cleanup_kinds: propagating {:?} to {:?}/{:?}",
386 funclet, succ, kind);
388 CleanupKind::NotCleanup => {
389 result[succ] = CleanupKind::Internal { funclet };
391 CleanupKind::Funclet => {
393 set_successor(funclet, succ);
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.
401 debug!("promoting {:?} to a funclet and updating {:?}", succ,
403 result[succ] = CleanupKind::Funclet;
404 set_successor(succ_funclet, succ);
405 set_successor(funclet, succ);
413 let mut result = IndexVec::from_elem(CleanupKind::NotCleanup, mir.basic_blocks());
415 discover_masters(&mut result, mir);
416 propagate(&mut result, mir);
417 debug!("cleanup_kinds: result={:?}", result);