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