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