1 use rustc_data_structures::graph::dominators::Dominators;
2 use rustc_middle::mir::visit::Visitor;
3 use rustc_middle::mir::{BasicBlock, Body, Location, Place, Rvalue};
4 use rustc_middle::mir::{BorrowKind, Mutability, Operand};
5 use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
6 use rustc_middle::mir::{Statement, StatementKind};
7 use rustc_middle::ty::TyCtxt;
10 borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, path_utils::*, AccessDepth,
11 Activation, ArtificialField, BorrowIndex, Deep, LocalMutationIsAllowed, Read, ReadKind,
12 ReadOrWrite, Reservation, Shallow, Write, WriteKind,
15 pub(super) fn generate_invalidates<'tcx>(
17 all_facts: &mut Option<AllFacts>,
18 location_table: &LocationTable,
20 borrow_set: &BorrowSet<'tcx>,
22 if all_facts.is_none() {
23 // Nothing to do if we don't have any facts
27 if let Some(all_facts) = all_facts {
28 let _prof_timer = tcx.prof.generic_activity("polonius_fact_generation");
29 let dominators = body.basic_blocks.dominators();
30 let mut ig = InvalidationGenerator {
42 struct InvalidationGenerator<'cx, 'tcx> {
44 all_facts: &'cx mut AllFacts,
45 location_table: &'cx LocationTable,
46 body: &'cx Body<'tcx>,
47 dominators: Dominators<BasicBlock>,
48 borrow_set: &'cx BorrowSet<'tcx>,
51 /// Visits the whole MIR and generates `invalidates()` facts.
52 /// Most of the code implementing this was stolen from `borrow_check/mod.rs`.
53 impl<'cx, 'tcx> Visitor<'tcx> for InvalidationGenerator<'cx, 'tcx> {
54 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
55 self.check_activations(location);
57 match &statement.kind {
58 StatementKind::Assign(box (lhs, rhs)) => {
59 self.consume_rvalue(location, rhs);
61 self.mutate_place(location, *lhs, Shallow(None));
63 StatementKind::FakeRead(box (_, _)) => {
64 // Only relevant for initialized/liveness/safety checks.
66 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
71 self.consume_operand(location, src);
72 self.consume_operand(location, dst);
73 self.consume_operand(location, count);
76 | StatementKind::Coverage(..)
77 | StatementKind::AscribeUserType(..)
78 | StatementKind::Retag { .. }
79 | StatementKind::StorageLive(..) => {
80 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
83 StatementKind::StorageDead(local) => {
87 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
88 LocalMutationIsAllowed::Yes,
91 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
92 bug!("Statement not allowed in this MIR phase")
96 self.super_statement(statement, location);
99 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
100 self.check_activations(location);
102 match &terminator.kind {
103 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
104 self.consume_operand(location, discr);
106 TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => {
110 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
111 LocalMutationIsAllowed::Yes,
114 TerminatorKind::DropAndReplace {
116 value: ref new_value,
120 self.mutate_place(location, *drop_place, Deep);
121 self.consume_operand(location, new_value);
123 TerminatorKind::Call {
132 self.consume_operand(location, func);
134 self.consume_operand(location, arg);
136 self.mutate_place(location, *destination, Deep);
138 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
139 self.consume_operand(location, cond);
140 use rustc_middle::mir::AssertKind;
141 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
142 self.consume_operand(location, len);
143 self.consume_operand(location, index);
146 TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
147 self.consume_operand(location, value);
149 // Invalidate all borrows of local places
150 let borrow_set = self.borrow_set;
151 let resume = self.location_table.start_index(resume.start_location());
152 for (i, data) in borrow_set.iter_enumerated() {
153 if borrow_of_local_data(data.borrowed_place) {
154 self.all_facts.loan_invalidated_at.push((resume, i));
158 self.mutate_place(location, *resume_arg, Deep);
160 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
161 // Invalidate all borrows of local places
162 let borrow_set = self.borrow_set;
163 let start = self.location_table.start_index(location);
164 for (i, data) in borrow_set.iter_enumerated() {
165 if borrow_of_local_data(data.borrowed_place) {
166 self.all_facts.loan_invalidated_at.push((start, i));
170 TerminatorKind::InlineAsm {
180 InlineAsmOperand::In { reg: _, ref value } => {
181 self.consume_operand(location, value);
183 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
184 if let Some(place) = place {
185 self.mutate_place(location, place, Shallow(None));
188 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
189 self.consume_operand(location, in_value);
190 if let Some(out_place) = out_place {
191 self.mutate_place(location, out_place, Shallow(None));
194 InlineAsmOperand::Const { value: _ }
195 | InlineAsmOperand::SymFn { value: _ }
196 | InlineAsmOperand::SymStatic { def_id: _ } => {}
200 TerminatorKind::Goto { target: _ }
201 | TerminatorKind::Abort
202 | TerminatorKind::Unreachable
203 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
204 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
205 // no data used, thus irrelevant to borrowck
209 self.super_terminator(terminator, location);
213 impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
214 /// Simulates mutation of a place.
215 fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) {
219 (kind, Write(WriteKind::Mutate)),
220 LocalMutationIsAllowed::ExceptUpvars,
224 /// Simulates consumption of an operand.
225 fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
227 Operand::Copy(place) => {
231 (Deep, Read(ReadKind::Copy)),
232 LocalMutationIsAllowed::No,
235 Operand::Move(place) => {
239 (Deep, Write(WriteKind::Move)),
240 LocalMutationIsAllowed::Yes,
243 Operand::Constant(_) => {}
247 // Simulates consumption of an rvalue
248 fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
250 Rvalue::Ref(_ /*rgn*/, bk, place) => {
251 let access_kind = match bk {
252 BorrowKind::Shallow => {
253 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
255 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
256 BorrowKind::Unique | BorrowKind::Mut { .. } => {
257 let wk = WriteKind::MutableBorrow(bk);
258 if allow_two_phase_borrow(bk) {
259 (Deep, Reservation(wk))
266 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
269 Rvalue::AddressOf(mutability, place) => {
270 let access_kind = match mutability {
273 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
274 allow_two_phase_borrow: false,
277 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
280 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
283 Rvalue::ThreadLocalRef(_) => {}
285 Rvalue::Use(ref operand)
286 | Rvalue::Repeat(ref operand, _)
287 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
288 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
289 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
290 self.consume_operand(location, operand)
292 Rvalue::CopyForDeref(ref place) => {
293 let op = &Operand::Copy(*place);
294 self.consume_operand(location, op);
297 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
298 let af = match *rvalue {
299 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
300 Rvalue::Discriminant(..) => None,
306 (Shallow(af), Read(ReadKind::Copy)),
307 LocalMutationIsAllowed::No,
311 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
312 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
313 self.consume_operand(location, operand1);
314 self.consume_operand(location, operand2);
317 Rvalue::NullaryOp(_op, _ty) => {}
319 Rvalue::Aggregate(_, ref operands) => {
320 for operand in operands {
321 self.consume_operand(location, operand);
327 /// Simulates an access to a place.
332 kind: (AccessDepth, ReadOrWrite),
333 _is_local_mutation_allowed: LocalMutationIsAllowed,
336 // note: not doing check_access_permissions checks because they don't generate invalidates
337 self.check_access_for_conflict(location, place, sd, rw);
340 fn check_access_for_conflict(
348 "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
350 location, place, sd, rw,
353 let body = self.body;
354 let borrow_set = self.borrow_set;
355 let indices = self.borrow_set.indices();
356 each_borrow_involving_path(
364 |this, borrow_index, borrow| {
365 match (rw, borrow.kind) {
366 // Obviously an activation is compatible with its own
367 // reservation (or even prior activating uses of same
368 // borrow); so don't check if they interfere.
370 // NOTE: *reservations* do conflict with themselves;
371 // thus aren't injecting unsoundness w/ this check.)
372 (Activation(_, activating), _) if activating == borrow_index => {
373 // Activating a borrow doesn't generate any invalidations, since we
374 // have already taken the reservation
377 (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
379 Read(ReadKind::Borrow(BorrowKind::Shallow)),
380 BorrowKind::Unique | BorrowKind::Mut { .. },
382 // Reads don't invalidate shared or shallow borrows
385 (Read(_), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
386 // Reading from mere reservations of mutable-borrows is OK.
387 if !is_active(&this.dominators, borrow, location) {
388 // If the borrow isn't active yet, reads don't invalidate it
389 assert!(allow_two_phase_borrow(borrow.kind));
390 return Control::Continue;
393 // Unique and mutable borrows are invalidated by reads from any
395 this.emit_loan_invalidated_at(borrow_index, location);
398 (Reservation(_) | Activation(_, _) | Write(_), _) => {
399 // unique or mutable borrows are invalidated by writes.
400 // Reservations count as writes since we need to check
401 // that activating the borrow will be OK
402 // FIXME(bob_twinkles) is this actually the right thing to do?
403 this.emit_loan_invalidated_at(borrow_index, location);
411 /// Generates a new `loan_invalidated_at(L, B)` fact.
412 fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
413 let lidx = self.location_table.start_index(l);
414 self.all_facts.loan_invalidated_at.push((lidx, b));
417 fn check_activations(&mut self, location: Location) {
418 // Two-phase borrow support: For each activation that is newly
419 // generated at this statement, check if it interferes with
421 for &borrow_index in self.borrow_set.activations_at_location(location) {
422 let borrow = &self.borrow_set[borrow_index];
424 // only mutable borrows should be 2-phase
425 assert!(match borrow.kind {
426 BorrowKind::Shared | BorrowKind::Shallow => false,
427 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
432 borrow.borrowed_place,
433 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
434 LocalMutationIsAllowed::No,
437 // We do not need to call `check_if_path_or_subpath_is_moved`
438 // again, as we already called it when we made the
439 // initial reservation.