]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/borrow_set.rs
Rollup merge of #54257 - alexcrichton:wasm-math-symbols, r=TimNN
[rust.git] / src / librustc_mir / borrow_check / borrow_set.rs
1 // Copyright 2012-2017 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 use borrow_check::place_ext::PlaceExt;
12 use dataflow::indexes::BorrowIndex;
13 use dataflow::move_paths::MoveData;
14 use rustc::mir::traversal;
15 use rustc::mir::visit::{PlaceContext, Visitor};
16 use rustc::mir::{self, Location, Mir, Place, Local};
17 use rustc::ty::{Region, TyCtxt};
18 use rustc::util::nodemap::{FxHashMap, FxHashSet};
19 use rustc_data_structures::indexed_vec::IndexVec;
20 use rustc_data_structures::bit_set::BitSet;
21 use std::fmt;
22 use std::hash::Hash;
23 use std::ops::Index;
24
25 crate struct BorrowSet<'tcx> {
26     /// The fundamental map relating bitvector indexes to the borrows
27     /// in the MIR.
28     crate borrows: IndexVec<BorrowIndex, BorrowData<'tcx>>,
29
30     /// Each borrow is also uniquely identified in the MIR by the
31     /// `Location` of the assignment statement in which it appears on
32     /// the right hand side; we map each such location to the
33     /// corresponding `BorrowIndex`.
34     crate location_map: FxHashMap<Location, BorrowIndex>,
35
36     /// Locations which activate borrows.
37     /// NOTE: A given location may activate more than one borrow in the future
38     /// when more general two-phase borrow support is introduced, but for now we
39     /// only need to store one borrow index
40     crate activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
41
42     /// Every borrow has a region; this maps each such regions back to
43     /// its borrow-indexes.
44     crate region_map: FxHashMap<Region<'tcx>, FxHashSet<BorrowIndex>>,
45
46     /// Map from local to all the borrows on that local
47     crate local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
48
49     crate locals_state_at_exit: LocalsStateAtExit,
50 }
51
52 impl<'tcx> Index<BorrowIndex> for BorrowSet<'tcx> {
53     type Output = BorrowData<'tcx>;
54
55     fn index(&self, index: BorrowIndex) -> &BorrowData<'tcx> {
56         &self.borrows[index]
57     }
58 }
59
60 /// Location where a two phase borrow is activated, if a borrow
61 /// is in fact a two phase borrow.
62 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
63 crate enum TwoPhaseActivation {
64     NotTwoPhase,
65     NotActivated,
66     ActivatedAt(Location),
67 }
68
69 #[derive(Debug)]
70 crate struct BorrowData<'tcx> {
71     /// Location where the borrow reservation starts.
72     /// In many cases, this will be equal to the activation location but not always.
73     crate reserve_location: Location,
74     /// Location where the borrow is activated.
75     crate activation_location: TwoPhaseActivation,
76     /// What kind of borrow this is
77     crate kind: mir::BorrowKind,
78     /// The region for which this borrow is live
79     crate region: Region<'tcx>,
80     /// Place from which we are borrowing
81     crate borrowed_place: mir::Place<'tcx>,
82     /// Place to which the borrow was stored
83     crate assigned_place: mir::Place<'tcx>,
84 }
85
86 impl<'tcx> fmt::Display for BorrowData<'tcx> {
87     fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
88         let kind = match self.kind {
89             mir::BorrowKind::Shared => "",
90             mir::BorrowKind::Unique => "uniq ",
91             mir::BorrowKind::Mut { .. } => "mut ",
92         };
93         let region = self.region.to_string();
94         let region = if region.len() > 0 {
95             format!("{} ", region)
96         } else {
97             region
98         };
99         write!(w, "&{}{}{:?}", region, kind, self.borrowed_place)
100     }
101 }
102
103 crate enum LocalsStateAtExit {
104     AllAreInvalidated,
105     SomeAreInvalidated { has_storage_dead_or_moved: BitSet<Local> }
106 }
107
108 impl LocalsStateAtExit {
109     fn build(
110         locals_are_invalidated_at_exit: bool,
111         mir: &Mir<'tcx>,
112         move_data: &MoveData<'tcx>
113     ) -> Self {
114         struct HasStorageDead(BitSet<Local>);
115
116         impl<'tcx> Visitor<'tcx> for HasStorageDead {
117             fn visit_local(&mut self, local: &Local, ctx: PlaceContext<'tcx>, _: Location) {
118                 if ctx == PlaceContext::StorageDead {
119                     self.0.insert(*local);
120                 }
121             }
122         }
123
124         if locals_are_invalidated_at_exit {
125             LocalsStateAtExit::AllAreInvalidated
126         } else {
127             let mut has_storage_dead = HasStorageDead(BitSet::new_empty(mir.local_decls.len()));
128             has_storage_dead.visit_mir(mir);
129             let mut has_storage_dead_or_moved = has_storage_dead.0;
130             for move_out in &move_data.moves {
131                 if let Some(index) = move_data.base_local(move_out.path) {
132                     has_storage_dead_or_moved.insert(index);
133
134                 }
135             }
136             LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved }
137         }
138     }
139 }
140
141 impl<'tcx> BorrowSet<'tcx> {
142     pub fn build(
143         tcx: TyCtxt<'_, '_, 'tcx>,
144         mir: &Mir<'tcx>,
145         locals_are_invalidated_at_exit: bool,
146         move_data: &MoveData<'tcx>
147     ) -> Self {
148
149         let mut visitor = GatherBorrows {
150             tcx,
151             mir,
152             idx_vec: IndexVec::new(),
153             location_map: FxHashMap(),
154             activation_map: FxHashMap(),
155             region_map: FxHashMap(),
156             local_map: FxHashMap(),
157             pending_activations: FxHashMap(),
158             locals_state_at_exit:
159                 LocalsStateAtExit::build(locals_are_invalidated_at_exit, mir, move_data),
160         };
161
162         for (block, block_data) in traversal::preorder(mir) {
163             visitor.visit_basic_block_data(block, block_data);
164         }
165
166         BorrowSet {
167             borrows: visitor.idx_vec,
168             location_map: visitor.location_map,
169             activation_map: visitor.activation_map,
170             region_map: visitor.region_map,
171             local_map: visitor.local_map,
172             locals_state_at_exit: visitor.locals_state_at_exit,
173         }
174     }
175
176     crate fn activations_at_location(&self, location: Location) -> &[BorrowIndex] {
177         self.activation_map
178             .get(&location)
179             .map(|activations| &activations[..])
180             .unwrap_or(&[])
181     }
182 }
183
184 struct GatherBorrows<'a, 'gcx: 'tcx, 'tcx: 'a> {
185     tcx: TyCtxt<'a, 'gcx, 'tcx>,
186     mir: &'a Mir<'tcx>,
187     idx_vec: IndexVec<BorrowIndex, BorrowData<'tcx>>,
188     location_map: FxHashMap<Location, BorrowIndex>,
189     activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
190     region_map: FxHashMap<Region<'tcx>, FxHashSet<BorrowIndex>>,
191     local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
192
193     /// When we encounter a 2-phase borrow statement, it will always
194     /// be assigning into a temporary TEMP:
195     ///
196     ///    TEMP = &foo
197     ///
198     /// We add TEMP into this map with `b`, where `b` is the index of
199     /// the borrow. When we find a later use of this activation, we
200     /// remove from the map (and add to the "tombstone" set below).
201     pending_activations: FxHashMap<mir::Local, BorrowIndex>,
202
203     locals_state_at_exit: LocalsStateAtExit,
204 }
205
206 impl<'a, 'gcx, 'tcx> Visitor<'tcx> for GatherBorrows<'a, 'gcx, 'tcx> {
207     fn visit_assign(
208         &mut self,
209         block: mir::BasicBlock,
210         assigned_place: &mir::Place<'tcx>,
211         rvalue: &mir::Rvalue<'tcx>,
212         location: mir::Location,
213     ) {
214         if let mir::Rvalue::Ref(region, kind, ref borrowed_place) = *rvalue {
215             if borrowed_place.ignore_borrow(
216                 self.tcx, self.mir, &self.locals_state_at_exit) {
217                 return;
218             }
219
220             let borrow = BorrowData {
221                 kind,
222                 region,
223                 reserve_location: location,
224                 activation_location: TwoPhaseActivation::NotTwoPhase,
225                 borrowed_place: borrowed_place.clone(),
226                 assigned_place: assigned_place.clone(),
227             };
228             let idx = self.idx_vec.push(borrow);
229             self.location_map.insert(location, idx);
230
231             self.insert_as_pending_if_two_phase(location, &assigned_place, region, kind, idx);
232
233             insert(&mut self.region_map, &region, idx);
234             if let Some(local) = borrowed_place.root_local() {
235                 insert(&mut self.local_map, &local, idx);
236             }
237         }
238
239         return self.super_assign(block, assigned_place, rvalue, location);
240
241         fn insert<'a, K, V>(map: &'a mut FxHashMap<K, FxHashSet<V>>, k: &K, v: V)
242         where
243             K: Clone + Eq + Hash,
244             V: Eq + Hash,
245         {
246             map.entry(k.clone()).or_insert(FxHashSet()).insert(v);
247         }
248     }
249
250     fn visit_place(
251         &mut self,
252         place: &mir::Place<'tcx>,
253         context: PlaceContext<'tcx>,
254         location: Location,
255     ) {
256         self.super_place(place, context, location);
257
258         // We found a use of some temporary TEMP...
259         if let Place::Local(temp) = place {
260             // ... check whether we (earlier) saw a 2-phase borrow like
261             //
262             //     TMP = &mut place
263             match self.pending_activations.get(temp) {
264                 Some(&borrow_index) => {
265                     let borrow_data = &mut self.idx_vec[borrow_index];
266
267                     // Watch out: the use of TMP in the borrow itself
268                     // doesn't count as an activation. =)
269                     if borrow_data.reserve_location == location && context == PlaceContext::Store {
270                         return;
271                     }
272
273                     if let TwoPhaseActivation::ActivatedAt(other_location) =
274                             borrow_data.activation_location {
275                         span_bug!(
276                             self.mir.source_info(location).span,
277                             "found two uses for 2-phase borrow temporary {:?}: \
278                              {:?} and {:?}",
279                             temp,
280                             location,
281                             other_location,
282                         );
283                     }
284
285                     // Otherwise, this is the unique later use
286                     // that we expect.
287                     borrow_data.activation_location = match context {
288                         // The use of TMP in a shared borrow does not
289                         // count as an actual activation.
290                         PlaceContext::Borrow { kind: mir::BorrowKind::Shared, .. } => {
291                             TwoPhaseActivation::NotActivated
292                         }
293                         _ => {
294                             // Double check: This borrow is indeed a two-phase borrow (that is,
295                             // we are 'transitioning' from `NotActivated` to `ActivatedAt`) and
296                             // we've not found any other activations (checked above).
297                             assert_eq!(
298                                 borrow_data.activation_location,
299                                 TwoPhaseActivation::NotActivated,
300                                 "never found an activation for this borrow!",
301                             );
302
303                             self.activation_map
304                                 .entry(location)
305                                 .or_default()
306                                 .push(borrow_index);
307                             TwoPhaseActivation::ActivatedAt(location)
308                         }
309                     };
310                 }
311
312                 None => {}
313             }
314         }
315     }
316
317     fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
318         if let mir::Rvalue::Ref(region, kind, ref place) = *rvalue {
319             // double-check that we already registered a BorrowData for this
320
321             let borrow_index = self.location_map[&location];
322             let borrow_data = &self.idx_vec[borrow_index];
323             assert_eq!(borrow_data.reserve_location, location);
324             assert_eq!(borrow_data.kind, kind);
325             assert_eq!(borrow_data.region, region);
326             assert_eq!(borrow_data.borrowed_place, *place);
327         }
328
329         return self.super_rvalue(rvalue, location);
330     }
331
332     fn visit_statement(
333         &mut self,
334         block: mir::BasicBlock,
335         statement: &mir::Statement<'tcx>,
336         location: Location,
337     ) {
338         return self.super_statement(block, statement, location);
339     }
340 }
341
342 impl<'a, 'gcx, 'tcx> GatherBorrows<'a, 'gcx, 'tcx> {
343     /// Returns true if the borrow represented by `kind` is
344     /// allowed to be split into separate Reservation and
345     /// Activation phases.
346     fn allow_two_phase_borrow(&self, kind: mir::BorrowKind) -> bool {
347         self.tcx.two_phase_borrows()
348             && (kind.allows_two_phase_borrow()
349                 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
350     }
351
352     /// If this is a two-phase borrow, then we will record it
353     /// as "pending" until we find the activating use.
354     fn insert_as_pending_if_two_phase(
355         &mut self,
356         start_location: Location,
357         assigned_place: &mir::Place<'tcx>,
358         region: Region<'tcx>,
359         kind: mir::BorrowKind,
360         borrow_index: BorrowIndex,
361     ) {
362         debug!(
363             "Borrows::insert_as_pending_if_two_phase({:?}, {:?}, {:?}, {:?})",
364             start_location, assigned_place, region, borrow_index,
365         );
366
367         if !self.allow_two_phase_borrow(kind) {
368             debug!("  -> {:?}", start_location);
369             return;
370         }
371
372         // When we encounter a 2-phase borrow statement, it will always
373         // be assigning into a temporary TEMP:
374         //
375         //    TEMP = &foo
376         //
377         // so extract `temp`.
378         let temp = if let &mir::Place::Local(temp) = assigned_place {
379             temp
380         } else {
381             span_bug!(
382                 self.mir.source_info(start_location).span,
383                 "expected 2-phase borrow to assign to a local, not `{:?}`",
384                 assigned_place,
385             );
386         };
387
388         // Consider the borrow not activated to start. When we find an activation, we'll update
389         // this field.
390         {
391             let borrow_data = &mut self.idx_vec[borrow_index];
392             borrow_data.activation_location = TwoPhaseActivation::NotActivated;
393         }
394
395         // Insert `temp` into the list of pending activations. From
396         // now on, we'll be on the lookout for a use of it. Note that
397         // we are guaranteed that this use will come after the
398         // assignment.
399         let old_value = self.pending_activations.insert(temp, borrow_index);
400         if let Some(old_index) = old_value {
401             span_bug!(self.mir.source_info(start_location).span,
402                       "found already pending activation for temp: {:?} \
403                        at borrow_index: {:?} with associated data {:?}",
404                       temp, old_index, self.idx_vec[old_index]);
405         }
406     }
407 }