1 use rustc::mir::visit::Visitor;
2 use rustc::mir::TerminatorKind;
3 use rustc::mir::{BasicBlock, Body, Location, Place, ReadOnlyBodyAndCache, Rvalue};
4 use rustc::mir::{BorrowKind, Mutability, Operand};
5 use rustc::mir::{Statement, StatementKind};
7 use rustc_data_structures::graph::dominators::Dominators;
9 use crate::dataflow::indexes::BorrowIndex;
11 use crate::borrow_check::{
12 borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, path_utils::*, AccessDepth,
13 Activation, ArtificialField, Deep, JustWrite, LocalMutationIsAllowed, MutateMode, Read,
14 ReadKind, ReadOrWrite, Reservation, Shallow, Write, WriteAndRead, WriteKind,
17 pub(super) fn generate_invalidates<'tcx>(
19 all_facts: &mut Option<AllFacts>,
20 location_table: &LocationTable,
21 body: ReadOnlyBodyAndCache<'_, 'tcx>,
22 borrow_set: &BorrowSet<'tcx>,
24 if all_facts.is_none() {
25 // Nothing to do if we don't have any facts
29 if let Some(all_facts) = all_facts {
30 let _prof_timer = tcx.prof.generic_activity("polonius_fact_generation");
31 let dominators = body.dominators();
32 let mut ig = InvalidationGenerator {
44 struct InvalidationGenerator<'cx, 'tcx> {
46 all_facts: &'cx mut AllFacts,
47 location_table: &'cx LocationTable,
48 body: &'cx Body<'tcx>,
49 dominators: Dominators<BasicBlock>,
50 borrow_set: &'cx BorrowSet<'tcx>,
53 /// Visits the whole MIR and generates `invalidates()` facts.
54 /// Most of the code implementing this was stolen from `borrow_check/mod.rs`.
55 impl<'cx, 'tcx> Visitor<'tcx> for InvalidationGenerator<'cx, 'tcx> {
56 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
57 self.check_activations(location);
59 match statement.kind {
60 StatementKind::Assign(box (ref lhs, ref rhs)) => {
61 self.consume_rvalue(location, rhs);
63 self.mutate_place(location, lhs, Shallow(None), JustWrite);
65 StatementKind::FakeRead(_, _) => {
66 // Only relavent for initialized/liveness/safety checks.
68 StatementKind::SetDiscriminant { ref place, variant_index: _ } => {
69 self.mutate_place(location, place, Shallow(None), JustWrite);
71 StatementKind::InlineAsm(ref asm) => {
72 for (o, output) in asm.asm.outputs.iter().zip(asm.outputs.iter()) {
74 // FIXME(eddyb) indirect inline asm outputs should
75 // be encoded through MIR place derefs instead.
79 (Deep, Read(ReadKind::Copy)),
80 LocalMutationIsAllowed::No,
86 if o.is_rw { Deep } else { Shallow(None) },
87 if o.is_rw { WriteAndRead } else { JustWrite },
91 for (_, input) in asm.inputs.iter() {
92 self.consume_operand(location, input);
96 | StatementKind::AscribeUserType(..)
97 | StatementKind::Retag { .. }
98 | StatementKind::StorageLive(..) => {
99 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
102 StatementKind::StorageDead(local) => {
106 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
107 LocalMutationIsAllowed::Yes,
112 self.super_statement(statement, location);
115 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
116 self.check_activations(location);
119 TerminatorKind::SwitchInt { ref discr, switch_ty: _, values: _, targets: _ } => {
120 self.consume_operand(location, discr);
122 TerminatorKind::Drop { location: ref drop_place, target: _, unwind: _ } => {
126 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
127 LocalMutationIsAllowed::Yes,
130 TerminatorKind::DropAndReplace {
131 location: ref drop_place,
132 value: ref new_value,
136 self.mutate_place(location, drop_place, Deep, JustWrite);
137 self.consume_operand(location, new_value);
139 TerminatorKind::Call {
146 self.consume_operand(location, func);
148 self.consume_operand(location, arg);
150 if let Some((ref dest, _ /*bb*/)) = *destination {
151 self.mutate_place(location, dest, Deep, JustWrite);
154 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
155 self.consume_operand(location, cond);
156 use rustc::mir::AssertKind;
157 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
158 self.consume_operand(location, len);
159 self.consume_operand(location, index);
162 TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
163 self.consume_operand(location, value);
165 // Invalidate all borrows of local places
166 let borrow_set = self.borrow_set.clone();
167 let resume = self.location_table.start_index(resume.start_location());
168 for i in borrow_set.borrows.indices() {
169 if borrow_of_local_data(&borrow_set.borrows[i].borrowed_place) {
170 self.all_facts.invalidates.push((resume, i));
174 self.mutate_place(location, resume_arg, Deep, JustWrite);
176 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
177 // Invalidate all borrows of local places
178 let borrow_set = self.borrow_set.clone();
179 let start = self.location_table.start_index(location);
180 for i in borrow_set.borrows.indices() {
181 if borrow_of_local_data(&borrow_set.borrows[i].borrowed_place) {
182 self.all_facts.invalidates.push((start, i));
186 TerminatorKind::Goto { target: _ }
187 | TerminatorKind::Abort
188 | TerminatorKind::Unreachable
189 | TerminatorKind::FalseEdges { real_target: _, imaginary_target: _ }
190 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
191 // no data used, thus irrelevant to borrowck
195 self.super_terminator_kind(kind, location);
199 impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
200 /// Simulates mutation of a place.
211 (kind, Write(WriteKind::Mutate)),
212 LocalMutationIsAllowed::ExceptUpvars,
216 /// Simulates consumption of an operand.
217 fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
219 Operand::Copy(ref place) => {
223 (Deep, Read(ReadKind::Copy)),
224 LocalMutationIsAllowed::No,
227 Operand::Move(ref place) => {
231 (Deep, Write(WriteKind::Move)),
232 LocalMutationIsAllowed::Yes,
235 Operand::Constant(_) => {}
239 // Simulates consumption of an rvalue
240 fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
242 Rvalue::Ref(_ /*rgn*/, bk, ref place) => {
243 let access_kind = match bk {
244 BorrowKind::Shallow => {
245 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
247 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
248 BorrowKind::Unique | BorrowKind::Mut { .. } => {
249 let wk = WriteKind::MutableBorrow(bk);
250 if allow_two_phase_borrow(bk) {
251 (Deep, Reservation(wk))
258 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
261 Rvalue::AddressOf(mutability, ref place) => {
262 let access_kind = match mutability {
265 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
266 allow_two_phase_borrow: false,
269 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
272 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
275 Rvalue::Use(ref operand)
276 | Rvalue::Repeat(ref operand, _)
277 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
278 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) => {
279 self.consume_operand(location, operand)
282 Rvalue::Len(ref place) | Rvalue::Discriminant(ref place) => {
283 let af = match *rvalue {
284 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
285 Rvalue::Discriminant(..) => None,
291 (Shallow(af), Read(ReadKind::Copy)),
292 LocalMutationIsAllowed::No,
296 Rvalue::BinaryOp(_bin_op, ref operand1, ref operand2)
297 | Rvalue::CheckedBinaryOp(_bin_op, ref operand1, ref operand2) => {
298 self.consume_operand(location, operand1);
299 self.consume_operand(location, operand2);
302 Rvalue::NullaryOp(_op, _ty) => {}
304 Rvalue::Aggregate(_, ref operands) => {
305 for operand in operands {
306 self.consume_operand(location, operand);
312 /// Simulates an access to a place.
317 kind: (AccessDepth, ReadOrWrite),
318 _is_local_mutation_allowed: LocalMutationIsAllowed,
321 // note: not doing check_access_permissions checks because they don't generate invalidates
322 self.check_access_for_conflict(location, place, sd, rw);
325 fn check_access_for_conflict(
333 "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
335 location, place, sd, rw,
338 let body = self.body;
339 let borrow_set = self.borrow_set.clone();
340 let indices = self.borrow_set.borrows.indices();
341 each_borrow_involving_path(
349 |this, borrow_index, borrow| {
350 match (rw, borrow.kind) {
351 // Obviously an activation is compatible with its own
352 // reservation (or even prior activating uses of same
353 // borrow); so don't check if they interfere.
355 // NOTE: *reservations* do conflict with themselves;
356 // thus aren't injecting unsoundenss w/ this check.)
357 (Activation(_, activating), _) if activating == borrow_index => {
358 // Activating a borrow doesn't generate any invalidations, since we
359 // have already taken the reservation
362 (Read(_), BorrowKind::Shallow)
363 | (Read(_), BorrowKind::Shared)
364 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique)
365 | (Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Mut { .. }) => {
366 // Reads don't invalidate shared or shallow borrows
369 (Read(_), BorrowKind::Unique) | (Read(_), BorrowKind::Mut { .. }) => {
370 // Reading from mere reservations of mutable-borrows is OK.
371 if !is_active(&this.dominators, borrow, location) {
372 // If the borrow isn't active yet, reads don't invalidate it
373 assert!(allow_two_phase_borrow(borrow.kind));
374 return Control::Continue;
377 // Unique and mutable borrows are invalidated by reads from any
379 this.generate_invalidates(borrow_index, location);
382 (Reservation(_), _) | (Activation(_, _), _) | (Write(_), _) => {
383 // unique or mutable borrows are invalidated by writes.
384 // Reservations count as writes since we need to check
385 // that activating the borrow will be OK
386 // FIXME(bob_twinkles) is this actually the right thing to do?
387 this.generate_invalidates(borrow_index, location);
395 /// Generates a new `invalidates(L, B)` fact.
396 fn generate_invalidates(&mut self, b: BorrowIndex, l: Location) {
397 let lidx = self.location_table.start_index(l);
398 self.all_facts.invalidates.push((lidx, b));
401 fn check_activations(&mut self, location: Location) {
402 // Two-phase borrow support: For each activation that is newly
403 // generated at this statement, check if it interferes with
405 for &borrow_index in self.borrow_set.activations_at_location(location) {
406 let borrow = &self.borrow_set[borrow_index];
408 // only mutable borrows should be 2-phase
409 assert!(match borrow.kind {
410 BorrowKind::Shared | BorrowKind::Shallow => false,
411 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
416 &borrow.borrowed_place,
417 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
418 LocalMutationIsAllowed::No,
421 // We do not need to call `check_if_path_or_subpath_is_moved`
422 // again, as we already called it when we made the
423 // initial reservation.