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.
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.
11 use borrow_check::place_ext::PlaceExt;
12 use borrow_check::nll::ToRegionVid;
13 use dataflow::indexes::BorrowIndex;
14 use dataflow::move_paths::MoveData;
15 use rustc::mir::traversal;
16 use rustc::mir::visit::{
17 PlaceContext, Visitor, NonUseContext, MutatingUseContext, NonMutatingUseContext
19 use rustc::mir::{self, Location, Mir, Local};
20 use rustc::ty::{RegionVid, TyCtxt};
21 use rustc::util::nodemap::{FxHashMap, FxHashSet};
22 use rustc_data_structures::indexed_vec::IndexVec;
23 use rustc_data_structures::bit_set::BitSet;
27 crate struct BorrowSet<'tcx> {
28 /// The fundamental map relating bitvector indexes to the borrows
30 crate borrows: IndexVec<BorrowIndex, BorrowData<'tcx>>,
32 /// Each borrow is also uniquely identified in the MIR by the
33 /// `Location` of the assignment statement in which it appears on
34 /// the right hand side; we map each such location to the
35 /// corresponding `BorrowIndex`.
36 crate location_map: FxHashMap<Location, BorrowIndex>,
38 /// Locations which activate borrows.
39 /// NOTE: A given location may activate more than one borrow in the future
40 /// when more general two-phase borrow support is introduced, but for now we
41 /// only need to store one borrow index
42 crate activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
44 /// Map from local to all the borrows on that local
45 crate local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
47 crate locals_state_at_exit: LocalsStateAtExit,
50 impl<'tcx> Index<BorrowIndex> for BorrowSet<'tcx> {
51 type Output = BorrowData<'tcx>;
53 fn index(&self, index: BorrowIndex) -> &BorrowData<'tcx> {
58 /// Location where a two phase borrow is activated, if a borrow
59 /// is in fact a two phase borrow.
60 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
61 crate enum TwoPhaseActivation {
64 ActivatedAt(Location),
68 crate struct BorrowData<'tcx> {
69 /// Location where the borrow reservation starts.
70 /// In many cases, this will be equal to the activation location but not always.
71 crate reserve_location: Location,
72 /// Location where the borrow is activated.
73 crate activation_location: TwoPhaseActivation,
74 /// What kind of borrow this is
75 crate kind: mir::BorrowKind,
76 /// The region for which this borrow is live
77 crate region: RegionVid,
78 /// Place from which we are borrowing
79 crate borrowed_place: mir::Place<'tcx>,
80 /// Place to which the borrow was stored
81 crate assigned_place: mir::Place<'tcx>,
84 impl<'tcx> fmt::Display for BorrowData<'tcx> {
85 fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
86 let kind = match self.kind {
87 mir::BorrowKind::Shared => "",
88 mir::BorrowKind::Shallow => "shallow ",
89 mir::BorrowKind::Unique => "uniq ",
90 mir::BorrowKind::Mut { .. } => "mut ",
92 write!(w, "&{:?} {}{:?}", self.region, kind, self.borrowed_place)
96 crate enum LocalsStateAtExit {
98 SomeAreInvalidated { has_storage_dead_or_moved: BitSet<Local> }
101 impl LocalsStateAtExit {
103 locals_are_invalidated_at_exit: bool,
105 move_data: &MoveData<'tcx>
107 struct HasStorageDead(BitSet<Local>);
109 impl<'tcx> Visitor<'tcx> for HasStorageDead {
110 fn visit_local(&mut self, local: &Local, ctx: PlaceContext<'tcx>, _: Location) {
111 if ctx == PlaceContext::NonUse(NonUseContext::StorageDead) {
112 self.0.insert(*local);
117 if locals_are_invalidated_at_exit {
118 LocalsStateAtExit::AllAreInvalidated
120 let mut has_storage_dead = HasStorageDead(BitSet::new_empty(mir.local_decls.len()));
121 has_storage_dead.visit_mir(mir);
122 let mut has_storage_dead_or_moved = has_storage_dead.0;
123 for move_out in &move_data.moves {
124 if let Some(index) = move_data.base_local(move_out.path) {
125 has_storage_dead_or_moved.insert(index);
129 LocalsStateAtExit::SomeAreInvalidated{ has_storage_dead_or_moved }
134 impl<'tcx> BorrowSet<'tcx> {
136 tcx: TyCtxt<'_, '_, 'tcx>,
138 locals_are_invalidated_at_exit: bool,
139 move_data: &MoveData<'tcx>
142 let mut visitor = GatherBorrows {
145 idx_vec: IndexVec::new(),
146 location_map: Default::default(),
147 activation_map: Default::default(),
148 local_map: Default::default(),
149 pending_activations: Default::default(),
150 locals_state_at_exit:
151 LocalsStateAtExit::build(locals_are_invalidated_at_exit, mir, move_data),
154 for (block, block_data) in traversal::preorder(mir) {
155 visitor.visit_basic_block_data(block, block_data);
159 borrows: visitor.idx_vec,
160 location_map: visitor.location_map,
161 activation_map: visitor.activation_map,
162 local_map: visitor.local_map,
163 locals_state_at_exit: visitor.locals_state_at_exit,
167 crate fn activations_at_location(&self, location: Location) -> &[BorrowIndex] {
170 .map(|activations| &activations[..])
175 struct GatherBorrows<'a, 'gcx: 'tcx, 'tcx: 'a> {
176 tcx: TyCtxt<'a, 'gcx, 'tcx>,
178 idx_vec: IndexVec<BorrowIndex, BorrowData<'tcx>>,
179 location_map: FxHashMap<Location, BorrowIndex>,
180 activation_map: FxHashMap<Location, Vec<BorrowIndex>>,
181 local_map: FxHashMap<mir::Local, FxHashSet<BorrowIndex>>,
183 /// When we encounter a 2-phase borrow statement, it will always
184 /// be assigning into a temporary TEMP:
188 /// We add TEMP into this map with `b`, where `b` is the index of
189 /// the borrow. When we find a later use of this activation, we
190 /// remove from the map (and add to the "tombstone" set below).
191 pending_activations: FxHashMap<mir::Local, BorrowIndex>,
193 locals_state_at_exit: LocalsStateAtExit,
196 impl<'a, 'gcx, 'tcx> Visitor<'tcx> for GatherBorrows<'a, 'gcx, 'tcx> {
199 block: mir::BasicBlock,
200 assigned_place: &mir::Place<'tcx>,
201 rvalue: &mir::Rvalue<'tcx>,
202 location: mir::Location,
204 if let mir::Rvalue::Ref(region, kind, ref borrowed_place) = *rvalue {
205 if borrowed_place.ignore_borrow(
206 self.tcx, self.mir, &self.locals_state_at_exit) {
210 let region = region.to_region_vid();
212 let borrow = BorrowData {
215 reserve_location: location,
216 activation_location: TwoPhaseActivation::NotTwoPhase,
217 borrowed_place: borrowed_place.clone(),
218 assigned_place: assigned_place.clone(),
220 let idx = self.idx_vec.push(borrow);
221 self.location_map.insert(location, idx);
223 self.insert_as_pending_if_two_phase(location, &assigned_place, kind, idx);
225 if let Some(local) = borrowed_place.root_local() {
226 self.local_map.entry(local).or_default().insert(idx);
230 self.super_assign(block, assigned_place, rvalue, location)
236 context: PlaceContext<'tcx>,
239 if !context.is_use() {
243 // We found a use of some temporary TMP
244 // check whether we (earlier) saw a 2-phase borrow like
247 if let Some(&borrow_index) = self.pending_activations.get(temp) {
248 let borrow_data = &mut self.idx_vec[borrow_index];
250 // Watch out: the use of TMP in the borrow itself
251 // doesn't count as an activation. =)
252 if borrow_data.reserve_location == location &&
253 context == PlaceContext::MutatingUse(MutatingUseContext::Store)
258 if let TwoPhaseActivation::ActivatedAt(other_location) =
259 borrow_data.activation_location {
261 self.mir.source_info(location).span,
262 "found two uses for 2-phase borrow temporary {:?}: \
270 // Otherwise, this is the unique later use
272 borrow_data.activation_location = match context {
273 // The use of TMP in a shared borrow does not
274 // count as an actual activation.
275 PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow(..)) |
276 PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow(..)) =>
277 TwoPhaseActivation::NotActivated,
279 // Double check: This borrow is indeed a two-phase borrow (that is,
280 // we are 'transitioning' from `NotActivated` to `ActivatedAt`) and
281 // we've not found any other activations (checked above).
283 borrow_data.activation_location,
284 TwoPhaseActivation::NotActivated,
285 "never found an activation for this borrow!",
292 TwoPhaseActivation::ActivatedAt(location)
298 fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
299 if let mir::Rvalue::Ref(region, kind, ref place) = *rvalue {
300 // double-check that we already registered a BorrowData for this
302 let borrow_index = self.location_map[&location];
303 let borrow_data = &self.idx_vec[borrow_index];
304 assert_eq!(borrow_data.reserve_location, location);
305 assert_eq!(borrow_data.kind, kind);
306 assert_eq!(borrow_data.region, region.to_region_vid());
307 assert_eq!(borrow_data.borrowed_place, *place);
310 return self.super_rvalue(rvalue, location);
315 block: mir::BasicBlock,
316 statement: &mir::Statement<'tcx>,
319 return self.super_statement(block, statement, location);
323 impl<'a, 'gcx, 'tcx> GatherBorrows<'a, 'gcx, 'tcx> {
324 /// Returns true if the borrow represented by `kind` is
325 /// allowed to be split into separate Reservation and
326 /// Activation phases.
327 fn allow_two_phase_borrow(&self, kind: mir::BorrowKind) -> bool {
328 self.tcx.two_phase_borrows()
329 && (kind.allows_two_phase_borrow()
330 || self.tcx.sess.opts.debugging_opts.two_phase_beyond_autoref)
333 /// If this is a two-phase borrow, then we will record it
334 /// as "pending" until we find the activating use.
335 fn insert_as_pending_if_two_phase(
337 start_location: Location,
338 assigned_place: &mir::Place<'tcx>,
339 kind: mir::BorrowKind,
340 borrow_index: BorrowIndex,
343 "Borrows::insert_as_pending_if_two_phase({:?}, {:?}, {:?})",
344 start_location, assigned_place, borrow_index,
347 if !self.allow_two_phase_borrow(kind) {
348 debug!(" -> {:?}", start_location);
352 // When we encounter a 2-phase borrow statement, it will always
353 // be assigning into a temporary TEMP:
357 // so extract `temp`.
358 let temp = if let &mir::Place::Local(temp) = assigned_place {
362 self.mir.source_info(start_location).span,
363 "expected 2-phase borrow to assign to a local, not `{:?}`",
368 // Consider the borrow not activated to start. When we find an activation, we'll update
371 let borrow_data = &mut self.idx_vec[borrow_index];
372 borrow_data.activation_location = TwoPhaseActivation::NotActivated;
375 // Insert `temp` into the list of pending activations. From
376 // now on, we'll be on the lookout for a use of it. Note that
377 // we are guaranteed that this use will come after the
379 let old_value = self.pending_activations.insert(temp, borrow_index);
380 if let Some(old_index) = old_value {
381 span_bug!(self.mir.source_info(start_location).span,
382 "found already pending activation for temp: {:?} \
383 at borrow_index: {:?} with associated data {:?}",
384 temp, old_index, self.idx_vec[old_index]);