]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/analyze.rs
Rollup merge of #40783 - stepancheg:cursor-new-0, r=aturon
[rust.git] / src / librustc_trans / mir / analyze.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! An analysis to determine which locals require allocas and
12 //! which do not.
13
14 use rustc_data_structures::bitvec::BitVector;
15 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
16 use rustc::middle::const_val::ConstVal;
17 use rustc::mir::{self, Location, TerminatorKind, Literal};
18 use rustc::mir::visit::{Visitor, LvalueContext};
19 use rustc::mir::traversal;
20 use common;
21 use super::MirContext;
22 use super::rvalue;
23
24 pub fn lvalue_locals<'a, 'tcx>(mircx: &MirContext<'a, 'tcx>) -> BitVector {
25     let mir = mircx.mir;
26     let mut analyzer = LocalAnalyzer::new(mircx);
27
28     analyzer.visit_mir(mir);
29
30     for (index, ty) in mir.local_decls.iter().map(|l| l.ty).enumerate() {
31         let ty = mircx.monomorphize(&ty);
32         debug!("local {} has type {:?}", index, ty);
33         if ty.is_scalar() ||
34             ty.is_box() ||
35             ty.is_region_ptr() ||
36             ty.is_simd() ||
37             common::type_is_zero_size(mircx.ccx, ty)
38         {
39             // These sorts of types are immediates that we can store
40             // in an ValueRef without an alloca.
41             assert!(common::type_is_immediate(mircx.ccx, ty) ||
42                     common::type_is_fat_ptr(mircx.ccx, ty));
43         } else if common::type_is_imm_pair(mircx.ccx, ty) {
44             // We allow pairs and uses of any of their 2 fields.
45         } else {
46             // These sorts of types require an alloca. Note that
47             // type_is_immediate() may *still* be true, particularly
48             // for newtypes, but we currently force some types
49             // (e.g. structs) into an alloca unconditionally, just so
50             // that we don't have to deal with having two pathways
51             // (gep vs extractvalue etc).
52             analyzer.mark_as_lvalue(mir::Local::new(index));
53         }
54     }
55
56     analyzer.lvalue_locals
57 }
58
59 struct LocalAnalyzer<'mir, 'a: 'mir, 'tcx: 'a> {
60     cx: &'mir MirContext<'a, 'tcx>,
61     lvalue_locals: BitVector,
62     seen_assigned: BitVector
63 }
64
65 impl<'mir, 'a, 'tcx> LocalAnalyzer<'mir, 'a, 'tcx> {
66     fn new(mircx: &'mir MirContext<'a, 'tcx>) -> LocalAnalyzer<'mir, 'a, 'tcx> {
67         LocalAnalyzer {
68             cx: mircx,
69             lvalue_locals: BitVector::new(mircx.mir.local_decls.len()),
70             seen_assigned: BitVector::new(mircx.mir.local_decls.len())
71         }
72     }
73
74     fn mark_as_lvalue(&mut self, local: mir::Local) {
75         debug!("marking {:?} as lvalue", local);
76         self.lvalue_locals.insert(local.index());
77     }
78
79     fn mark_assigned(&mut self, local: mir::Local) {
80         if !self.seen_assigned.insert(local.index()) {
81             self.mark_as_lvalue(local);
82         }
83     }
84 }
85
86 impl<'mir, 'a, 'tcx> Visitor<'tcx> for LocalAnalyzer<'mir, 'a, 'tcx> {
87     fn visit_assign(&mut self,
88                     block: mir::BasicBlock,
89                     lvalue: &mir::Lvalue<'tcx>,
90                     rvalue: &mir::Rvalue<'tcx>,
91                     location: Location) {
92         debug!("visit_assign(block={:?}, lvalue={:?}, rvalue={:?})", block, lvalue, rvalue);
93
94         if let mir::Lvalue::Local(index) = *lvalue {
95             self.mark_assigned(index);
96             if !rvalue::rvalue_creates_operand(rvalue) {
97                 self.mark_as_lvalue(index);
98             }
99         } else {
100             self.visit_lvalue(lvalue, LvalueContext::Store, location);
101         }
102
103         self.visit_rvalue(rvalue, location);
104     }
105
106     fn visit_terminator_kind(&mut self,
107                              block: mir::BasicBlock,
108                              kind: &mir::TerminatorKind<'tcx>,
109                              location: Location) {
110         match *kind {
111             mir::TerminatorKind::Call {
112                 func: mir::Operand::Constant(mir::Constant {
113                     literal: Literal::Value {
114                         value: ConstVal::Function(def_id, _), ..
115                     }, ..
116                 }),
117                 ref args, ..
118             } if Some(def_id) == self.cx.ccx.tcx().lang_items.box_free_fn() => {
119                 // box_free(x) shares with `drop x` the property that it
120                 // is not guaranteed to be statically dominated by the
121                 // definition of x, so x must always be in an alloca.
122                 if let mir::Operand::Consume(ref lvalue) = args[0] {
123                     self.visit_lvalue(lvalue, LvalueContext::Drop, location);
124                 }
125             }
126             _ => {}
127         }
128
129         self.super_terminator_kind(block, kind, location);
130     }
131
132     fn visit_lvalue(&mut self,
133                     lvalue: &mir::Lvalue<'tcx>,
134                     context: LvalueContext<'tcx>,
135                     location: Location) {
136         debug!("visit_lvalue(lvalue={:?}, context={:?})", lvalue, context);
137
138         // Allow uses of projections of immediate pair fields.
139         if let mir::Lvalue::Projection(ref proj) = *lvalue {
140             if let mir::Lvalue::Local(_) = proj.base {
141                 let ty = proj.base.ty(self.cx.mir, self.cx.ccx.tcx());
142
143                 let ty = self.cx.monomorphize(&ty.to_ty(self.cx.ccx.tcx()));
144                 if common::type_is_imm_pair(self.cx.ccx, ty) {
145                     if let mir::ProjectionElem::Field(..) = proj.elem {
146                         if let LvalueContext::Consume = context {
147                             return;
148                         }
149                     }
150                 }
151             }
152         }
153
154         if let mir::Lvalue::Local(index) = *lvalue {
155             match context {
156                 LvalueContext::Call => {
157                     self.mark_assigned(index);
158                 }
159
160                 LvalueContext::StorageLive |
161                 LvalueContext::StorageDead |
162                 LvalueContext::Inspect |
163                 LvalueContext::Consume => {}
164
165                 LvalueContext::Store |
166                 LvalueContext::Borrow { .. } |
167                 LvalueContext::Projection(..) => {
168                     self.mark_as_lvalue(index);
169                 }
170
171                 LvalueContext::Drop => {
172                     let ty = lvalue.ty(self.cx.mir, self.cx.ccx.tcx());
173                     let ty = self.cx.monomorphize(&ty.to_ty(self.cx.ccx.tcx()));
174
175                     // Only need the lvalue if we're actually dropping it.
176                     if self.cx.ccx.shared().type_needs_drop(ty) {
177                         self.mark_as_lvalue(index);
178                     }
179                 }
180             }
181         }
182
183         // A deref projection only reads the pointer, never needs the lvalue.
184         if let mir::Lvalue::Projection(ref proj) = *lvalue {
185             if let mir::ProjectionElem::Deref = proj.elem {
186                 return self.visit_lvalue(&proj.base, LvalueContext::Consume, location);
187             }
188         }
189
190         self.super_lvalue(lvalue, context, location);
191     }
192 }
193
194 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
195 pub enum CleanupKind {
196     NotCleanup,
197     Funclet,
198     Internal { funclet: mir::BasicBlock }
199 }
200
201 pub fn cleanup_kinds<'a, 'tcx>(mir: &mir::Mir<'tcx>) -> IndexVec<mir::BasicBlock, CleanupKind> {
202     fn discover_masters<'tcx>(result: &mut IndexVec<mir::BasicBlock, CleanupKind>,
203                               mir: &mir::Mir<'tcx>) {
204         for (bb, data) in mir.basic_blocks().iter_enumerated() {
205             match data.terminator().kind {
206                 TerminatorKind::Goto { .. } |
207                 TerminatorKind::Resume |
208                 TerminatorKind::Return |
209                 TerminatorKind::Unreachable |
210                 TerminatorKind::SwitchInt { .. } => {
211                     /* nothing to do */
212                 }
213                 TerminatorKind::Call { cleanup: unwind, .. } |
214                 TerminatorKind::Assert { cleanup: unwind, .. } |
215                 TerminatorKind::DropAndReplace { unwind, .. } |
216                 TerminatorKind::Drop { unwind, .. } => {
217                     if let Some(unwind) = unwind {
218                         debug!("cleanup_kinds: {:?}/{:?} registering {:?} as funclet",
219                                bb, data, unwind);
220                         result[unwind] = CleanupKind::Funclet;
221                     }
222                 }
223             }
224         }
225     }
226
227     fn propagate<'tcx>(result: &mut IndexVec<mir::BasicBlock, CleanupKind>,
228                        mir: &mir::Mir<'tcx>) {
229         let mut funclet_succs = IndexVec::from_elem(None, mir.basic_blocks());
230
231         let mut set_successor = |funclet: mir::BasicBlock, succ| {
232             match funclet_succs[funclet] {
233                 ref mut s @ None => {
234                     debug!("set_successor: updating successor of {:?} to {:?}",
235                            funclet, succ);
236                     *s = Some(succ);
237                 },
238                 Some(s) => if s != succ {
239                     span_bug!(mir.span, "funclet {:?} has 2 parents - {:?} and {:?}",
240                               funclet, s, succ);
241                 }
242             }
243         };
244
245         for (bb, data) in traversal::reverse_postorder(mir) {
246             let funclet = match result[bb] {
247                 CleanupKind::NotCleanup => continue,
248                 CleanupKind::Funclet => bb,
249                 CleanupKind::Internal { funclet } => funclet,
250             };
251
252             debug!("cleanup_kinds: {:?}/{:?}/{:?} propagating funclet {:?}",
253                    bb, data, result[bb], funclet);
254
255             for &succ in data.terminator().successors().iter() {
256                 let kind = result[succ];
257                 debug!("cleanup_kinds: propagating {:?} to {:?}/{:?}",
258                        funclet, succ, kind);
259                 match kind {
260                     CleanupKind::NotCleanup => {
261                         result[succ] = CleanupKind::Internal { funclet: funclet };
262                     }
263                     CleanupKind::Funclet => {
264                         set_successor(funclet, succ);
265                     }
266                     CleanupKind::Internal { funclet: succ_funclet } => {
267                         if funclet != succ_funclet {
268                             // `succ` has 2 different funclet going into it, so it must
269                             // be a funclet by itself.
270
271                             debug!("promoting {:?} to a funclet and updating {:?}", succ,
272                                    succ_funclet);
273                             result[succ] = CleanupKind::Funclet;
274                             set_successor(succ_funclet, succ);
275                             set_successor(funclet, succ);
276                         }
277                     }
278                 }
279             }
280         }
281     }
282
283     let mut result = IndexVec::from_elem(CleanupKind::NotCleanup, mir.basic_blocks());
284
285     discover_masters(&mut result, mir);
286     propagate(&mut result, mir);
287     debug!("cleanup_kinds: result={:?}", result);
288     result
289 }