1 use crate::borrow_check::borrow_set::{BorrowSet, BorrowData};
2 use crate::borrow_check::place_ext::PlaceExt;
4 use rustc::mir::{self, Location, Place, PlaceBase, Body};
6 use rustc::ty::RegionVid;
8 use rustc_data_structures::bit_set::BitSet;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
12 use crate::dataflow::{BitDenotation, BottomValue, GenKillSet};
13 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
14 use crate::borrow_check::nll::ToRegionVid;
15 use crate::borrow_check::places_conflict;
20 pub struct BorrowIndex {
25 /// `Borrows` stores the data used in the analyses that track the flow
28 /// It uniquely identifies every borrow (`Rvalue::Ref`) by a
29 /// `BorrowIndex`, and maps each such index to a `BorrowData`
30 /// describing the borrow. These indexes are used for representing the
31 /// borrows in compact bitvectors.
32 pub struct Borrows<'a, 'tcx> {
36 borrow_set: Rc<BorrowSet<'tcx>>,
37 borrows_out_of_scope_at_location: FxHashMap<Location, Vec<BorrowIndex>>,
39 /// NLL region inference context with which NLL queries should be resolved
40 _nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
50 fn precompute_borrows_out_of_scope<'tcx>(
52 regioncx: &Rc<RegionInferenceContext<'tcx>>,
53 borrows_out_of_scope_at_location: &mut FxHashMap<Location, Vec<BorrowIndex>>,
54 borrow_index: BorrowIndex,
55 borrow_region: RegionVid,
58 // We visit one BB at a time. The complication is that we may start in the
59 // middle of the first BB visited (the one containing `location`), in which
60 // case we may have to later on process the first part of that BB if there
61 // is a path back to its start.
63 // For visited BBs, we record the index of the first statement processed.
64 // (In fully processed BBs this index is 0.) Note also that we add BBs to
65 // `visited` once they are added to `stack`, before they are actually
66 // processed, because this avoids the need to look them up again on
68 let mut visited = FxHashMap::default();
69 visited.insert(location.block, location.statement_index);
71 let mut stack = vec![];
72 stack.push(StackEntry {
74 lo: location.statement_index,
75 hi: body[location.block].statements.len(),
76 first_part_only: false,
79 while let Some(StackEntry { bb, lo, hi, first_part_only }) = stack.pop() {
80 let mut finished_early = first_part_only;
82 let location = Location { block: bb, statement_index: i };
83 // If region does not contain a point at the location, then add to list and skip
84 // successor locations.
85 if !regioncx.region_contains(borrow_region, location) {
86 debug!("borrow {:?} gets killed at {:?}", borrow_index, location);
87 borrows_out_of_scope_at_location
91 finished_early = true;
97 // Add successor BBs to the work list, if necessary.
98 let bb_data = &body[bb];
99 assert!(hi == bb_data.statements.len());
100 for &succ_bb in bb_data.terminator.as_ref().unwrap().successors() {
101 visited.entry(succ_bb)
103 // `succ_bb` has been seen before. If it wasn't
104 // fully processed, add its first part to `stack`
107 stack.push(StackEntry {
111 first_part_only: true,
114 // And update this entry with 0, to represent the
115 // whole BB being processed.
119 // succ_bb hasn't been seen before. Add it to
120 // `stack` for processing.
121 stack.push(StackEntry {
124 hi: body[succ_bb].statements.len(),
125 first_part_only: false,
127 // Insert 0 for this BB, to represent the whole BB
136 impl<'a, 'tcx> Borrows<'a, 'tcx> {
139 body: &'a Body<'tcx>,
140 nonlexical_regioncx: Rc<RegionInferenceContext<'tcx>>,
141 borrow_set: &Rc<BorrowSet<'tcx>>,
143 let mut borrows_out_of_scope_at_location = FxHashMap::default();
144 for (borrow_index, borrow_data) in borrow_set.borrows.iter_enumerated() {
145 let borrow_region = borrow_data.region.to_region_vid();
146 let location = borrow_set.borrows[borrow_index].reserve_location;
148 precompute_borrows_out_of_scope(body, &nonlexical_regioncx,
149 &mut borrows_out_of_scope_at_location,
150 borrow_index, borrow_region, location);
156 borrow_set: borrow_set.clone(),
157 borrows_out_of_scope_at_location,
158 _nonlexical_regioncx: nonlexical_regioncx,
162 crate fn borrows(&self) -> &IndexVec<BorrowIndex, BorrowData<'tcx>> { &self.borrow_set.borrows }
164 pub fn location(&self, idx: BorrowIndex) -> &Location {
165 &self.borrow_set.borrows[idx].reserve_location
168 /// Add all borrows to the kill set, if those borrows are out of scope at `location`.
169 /// That means they went out of a nonlexical scope
170 fn kill_loans_out_of_scope_at_location(&self,
171 trans: &mut GenKillSet<BorrowIndex>,
172 location: Location) {
173 // NOTE: The state associated with a given `location`
174 // reflects the dataflow on entry to the statement.
175 // Iterate over each of the borrows that we've precomputed
176 // to have went out of scope at this location and kill them.
178 // We are careful always to call this function *before* we
179 // set up the gen-bits for the statement or
180 // termanator. That way, if the effect of the statement or
181 // terminator *does* introduce a new loan of the same
182 // region, then setting that gen-bit will override any
183 // potential kill introduced here.
184 if let Some(indices) = self.borrows_out_of_scope_at_location.get(&location) {
185 trans.kill_all(indices);
189 /// Kill any borrows that conflict with `place`.
190 fn kill_borrows_on_place(
192 trans: &mut GenKillSet<BorrowIndex>,
195 debug!("kill_borrows_on_place: place={:?}", place);
197 if let PlaceBase::Local(local) = place.base {
198 let other_borrows_of_local = self
203 .flat_map(|bs| bs.into_iter());
205 // If the borrowed place is a local with no projections, all other borrows of this
206 // local must conflict. This is purely an optimization so we don't have to call
207 // `places_conflict` for every borrow.
208 if place.projection.is_none() {
209 trans.kill_all(other_borrows_of_local);
213 // By passing `PlaceConflictBias::NoOverlap`, we conservatively assume that any given
214 // pair of array indices are unequal, so that when `places_conflict` returns true, we
215 // will be assured that two places being compared definitely denotes the same sets of
217 let definitely_conflicting_borrows = other_borrows_of_local
219 places_conflict::places_conflict(
222 &self.borrow_set.borrows[i].borrowed_place,
224 places_conflict::PlaceConflictBias::NoOverlap)
227 trans.kill_all(definitely_conflicting_borrows);
232 impl<'a, 'tcx> BitDenotation<'tcx> for Borrows<'a, 'tcx> {
233 type Idx = BorrowIndex;
234 fn name() -> &'static str { "borrows" }
235 fn bits_per_block(&self) -> usize {
236 self.borrow_set.borrows.len() * 2
239 fn start_block_effect(&self, _entry_set: &mut BitSet<Self::Idx>) {
240 // no borrows of code region_scopes have been taken prior to
241 // function execution, so this method has no effect.
244 fn before_statement_effect(&self,
245 trans: &mut GenKillSet<Self::Idx>,
246 location: Location) {
247 debug!("Borrows::before_statement_effect trans: {:?} location: {:?}",
249 self.kill_loans_out_of_scope_at_location(trans, location);
252 fn statement_effect(&self,
253 trans: &mut GenKillSet<Self::Idx>,
254 location: Location) {
255 debug!("Borrows::statement_effect: trans={:?} location={:?}",
258 let block = &self.body.basic_blocks().get(location.block).unwrap_or_else(|| {
259 panic!("could not find block at location {:?}", location);
261 let stmt = block.statements.get(location.statement_index).unwrap_or_else(|| {
262 panic!("could not find statement at location {:?}");
265 debug!("Borrows::statement_effect: stmt={:?}", stmt);
267 mir::StatementKind::Assign(ref lhs, ref rhs) => {
268 // Make sure there are no remaining borrows for variables
269 // that are assigned over.
270 self.kill_borrows_on_place(trans, lhs);
272 if let mir::Rvalue::Ref(_, _, ref place) = **rhs {
273 if place.ignore_borrow(
276 &self.borrow_set.locals_state_at_exit,
280 let index = self.borrow_set.location_map.get(&location).unwrap_or_else(|| {
281 panic!("could not find BorrowIndex for location {:?}", location);
288 mir::StatementKind::StorageDead(local) => {
289 // Make sure there are no remaining borrows for locals that
290 // are gone out of scope.
291 self.kill_borrows_on_place(trans, &Place::from(local));
294 mir::StatementKind::InlineAsm(ref asm) => {
295 for (output, kind) in asm.outputs.iter().zip(&asm.asm.outputs) {
296 if !kind.is_indirect && !kind.is_rw {
297 self.kill_borrows_on_place(trans, output);
302 mir::StatementKind::FakeRead(..) |
303 mir::StatementKind::SetDiscriminant { .. } |
304 mir::StatementKind::StorageLive(..) |
305 mir::StatementKind::Retag { .. } |
306 mir::StatementKind::AscribeUserType(..) |
307 mir::StatementKind::Nop => {}
312 fn before_terminator_effect(&self,
313 trans: &mut GenKillSet<Self::Idx>,
314 location: Location) {
315 debug!("Borrows::before_terminator_effect: trans={:?} location={:?}",
317 self.kill_loans_out_of_scope_at_location(trans, location);
320 fn terminator_effect(&self,
321 _: &mut GenKillSet<Self::Idx>,
324 fn propagate_call_return(
326 _in_out: &mut BitSet<BorrowIndex>,
327 _call_bb: mir::BasicBlock,
328 _dest_bb: mir::BasicBlock,
329 _dest_place: &mir::Place<'tcx>,
334 impl<'a, 'tcx> BottomValue for Borrows<'a, 'tcx> {
335 /// bottom = nothing is reserved or activated yet;
336 const BOTTOM_VALUE: bool = false;