]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/invalidation.rs
Rollup merge of #98583 - joshtriplett:stabilize-windows-symlink-types, r=thomcc
[rust.git] / compiler / rustc_borrowck / src / invalidation.rs
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;
8
9 use crate::{
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,
13 };
14
15 pub(super) fn generate_invalidates<'tcx>(
16     tcx: TyCtxt<'tcx>,
17     all_facts: &mut Option<AllFacts>,
18     location_table: &LocationTable,
19     body: &Body<'tcx>,
20     borrow_set: &BorrowSet<'tcx>,
21 ) {
22     if all_facts.is_none() {
23         // Nothing to do if we don't have any facts
24         return;
25     }
26
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 {
31             all_facts,
32             borrow_set,
33             tcx,
34             location_table,
35             body: &body,
36             dominators,
37         };
38         ig.visit_body(body);
39     }
40 }
41
42 struct InvalidationGenerator<'cx, 'tcx> {
43     tcx: TyCtxt<'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>,
49 }
50
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);
56
57         match &statement.kind {
58             StatementKind::Assign(box (lhs, rhs)) => {
59                 self.consume_rvalue(location, rhs);
60
61                 self.mutate_place(location, *lhs, Shallow(None));
62             }
63             StatementKind::FakeRead(box (_, _)) => {
64                 // Only relevant for initialized/liveness/safety checks.
65             }
66             StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
67                 ref src,
68                 ref dst,
69                 ref count,
70             }) => {
71                 self.consume_operand(location, src);
72                 self.consume_operand(location, dst);
73                 self.consume_operand(location, count);
74             }
75             StatementKind::Nop
76             | StatementKind::Coverage(..)
77             | StatementKind::AscribeUserType(..)
78             | StatementKind::Retag { .. }
79             | StatementKind::StorageLive(..) => {
80                 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
81                 // to borrow check.
82             }
83             StatementKind::StorageDead(local) => {
84                 self.access_place(
85                     location,
86                     Place::from(*local),
87                     (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
88                     LocalMutationIsAllowed::Yes,
89                 );
90             }
91             StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
92                 bug!("Statement not allowed in this MIR phase")
93             }
94         }
95
96         self.super_statement(statement, location);
97     }
98
99     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
100         self.check_activations(location);
101
102         match &terminator.kind {
103             TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
104                 self.consume_operand(location, discr);
105             }
106             TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => {
107                 self.access_place(
108                     location,
109                     *drop_place,
110                     (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
111                     LocalMutationIsAllowed::Yes,
112                 );
113             }
114             TerminatorKind::DropAndReplace {
115                 place: drop_place,
116                 value: ref new_value,
117                 target: _,
118                 unwind: _,
119             } => {
120                 self.mutate_place(location, *drop_place, Deep);
121                 self.consume_operand(location, new_value);
122             }
123             TerminatorKind::Call {
124                 ref func,
125                 ref args,
126                 destination,
127                 target: _,
128                 cleanup: _,
129                 from_hir_call: _,
130                 fn_span: _,
131             } => {
132                 self.consume_operand(location, func);
133                 for arg in args {
134                     self.consume_operand(location, arg);
135                 }
136                 self.mutate_place(location, *destination, Deep);
137             }
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);
144                 }
145             }
146             TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
147                 self.consume_operand(location, value);
148
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));
155                     }
156                 }
157
158                 self.mutate_place(location, *resume_arg, Deep);
159             }
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));
167                     }
168                 }
169             }
170             TerminatorKind::InlineAsm {
171                 template: _,
172                 ref operands,
173                 options: _,
174                 line_spans: _,
175                 destination: _,
176                 cleanup: _,
177             } => {
178                 for op in operands {
179                     match *op {
180                         InlineAsmOperand::In { reg: _, ref value } => {
181                             self.consume_operand(location, value);
182                         }
183                         InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
184                             if let Some(place) = place {
185                                 self.mutate_place(location, place, Shallow(None));
186                             }
187                         }
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));
192                             }
193                         }
194                         InlineAsmOperand::Const { value: _ }
195                         | InlineAsmOperand::SymFn { value: _ }
196                         | InlineAsmOperand::SymStatic { def_id: _ } => {}
197                     }
198                 }
199             }
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
206             }
207         }
208
209         self.super_terminator(terminator, location);
210     }
211 }
212
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) {
216         self.access_place(
217             location,
218             place,
219             (kind, Write(WriteKind::Mutate)),
220             LocalMutationIsAllowed::ExceptUpvars,
221         );
222     }
223
224     /// Simulates consumption of an operand.
225     fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
226         match *operand {
227             Operand::Copy(place) => {
228                 self.access_place(
229                     location,
230                     place,
231                     (Deep, Read(ReadKind::Copy)),
232                     LocalMutationIsAllowed::No,
233                 );
234             }
235             Operand::Move(place) => {
236                 self.access_place(
237                     location,
238                     place,
239                     (Deep, Write(WriteKind::Move)),
240                     LocalMutationIsAllowed::Yes,
241                 );
242             }
243             Operand::Constant(_) => {}
244         }
245     }
246
247     // Simulates consumption of an rvalue
248     fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
249         match *rvalue {
250             Rvalue::Ref(_ /*rgn*/, bk, place) => {
251                 let access_kind = match bk {
252                     BorrowKind::Shallow => {
253                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
254                     }
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))
260                         } else {
261                             (Deep, Write(wk))
262                         }
263                     }
264                 };
265
266                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
267             }
268
269             Rvalue::AddressOf(mutability, place) => {
270                 let access_kind = match mutability {
271                     Mutability::Mut => (
272                         Deep,
273                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
274                             allow_two_phase_borrow: false,
275                         })),
276                     ),
277                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
278                 };
279
280                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
281             }
282
283             Rvalue::ThreadLocalRef(_) => {}
284
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)
291             }
292             Rvalue::CopyForDeref(ref place) => {
293                 let op = &Operand::Copy(*place);
294                 self.consume_operand(location, op);
295             }
296
297             Rvalue::Len(place) | Rvalue::Discriminant(place) => {
298                 let af = match *rvalue {
299                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
300                     Rvalue::Discriminant(..) => None,
301                     _ => unreachable!(),
302                 };
303                 self.access_place(
304                     location,
305                     place,
306                     (Shallow(af), Read(ReadKind::Copy)),
307                     LocalMutationIsAllowed::No,
308                 );
309             }
310
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);
315             }
316
317             Rvalue::NullaryOp(_op, _ty) => {}
318
319             Rvalue::Aggregate(_, ref operands) => {
320                 for operand in operands {
321                     self.consume_operand(location, operand);
322                 }
323             }
324         }
325     }
326
327     /// Simulates an access to a place.
328     fn access_place(
329         &mut self,
330         location: Location,
331         place: Place<'tcx>,
332         kind: (AccessDepth, ReadOrWrite),
333         _is_local_mutation_allowed: LocalMutationIsAllowed,
334     ) {
335         let (sd, rw) = kind;
336         // note: not doing check_access_permissions checks because they don't generate invalidates
337         self.check_access_for_conflict(location, place, sd, rw);
338     }
339
340     fn check_access_for_conflict(
341         &mut self,
342         location: Location,
343         place: Place<'tcx>,
344         sd: AccessDepth,
345         rw: ReadOrWrite,
346     ) {
347         debug!(
348             "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
349              rw={:?})",
350             location, place, sd, rw,
351         );
352         let tcx = self.tcx;
353         let body = self.body;
354         let borrow_set = self.borrow_set;
355         let indices = self.borrow_set.indices();
356         each_borrow_involving_path(
357             self,
358             tcx,
359             body,
360             location,
361             (sd, place),
362             borrow_set,
363             indices,
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.
369                     //
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
375                     }
376
377                     (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
378                     | (
379                         Read(ReadKind::Borrow(BorrowKind::Shallow)),
380                         BorrowKind::Unique | BorrowKind::Mut { .. },
381                     ) => {
382                         // Reads don't invalidate shared or shallow borrows
383                     }
384
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;
391                         }
392
393                         // Unique and mutable borrows are invalidated by reads from any
394                         // involved path
395                         this.emit_loan_invalidated_at(borrow_index, location);
396                     }
397
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);
404                     }
405                 }
406                 Control::Continue
407             },
408         );
409     }
410
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));
415     }
416
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
420         // another borrow.
421         for &borrow_index in self.borrow_set.activations_at_location(location) {
422             let borrow = &self.borrow_set[borrow_index];
423
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,
428             });
429
430             self.access_place(
431                 location,
432                 borrow.borrowed_place,
433                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
434                 LocalMutationIsAllowed::No,
435             );
436
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.
440         }
441     }
442 }