]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/invalidation.rs
Lower the assume intrinsic to a MIR statement
[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             // Only relevant for mir typeck
76             StatementKind::AscribeUserType(..)
77             // Doesn't have any language semantics
78             | StatementKind::Coverage(..)
79             // Takes a `bool` argument, and has no return value, thus being irrelevant for borrowck
80             | StatementKind::Assume(..)
81             // Does not actually affect borrowck
82             | StatementKind::StorageLive(..) => {}
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::Nop
92             | StatementKind::Retag { .. }
93             | StatementKind::Deinit(..)
94             | StatementKind::SetDiscriminant { .. } => {
95                 bug!("Statement not allowed in this MIR phase")
96             }
97         }
98
99         self.super_statement(statement, location);
100     }
101
102     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
103         self.check_activations(location);
104
105         match &terminator.kind {
106             TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
107                 self.consume_operand(location, discr);
108             }
109             TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => {
110                 self.access_place(
111                     location,
112                     *drop_place,
113                     (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
114                     LocalMutationIsAllowed::Yes,
115                 );
116             }
117             TerminatorKind::DropAndReplace {
118                 place: drop_place,
119                 value: ref new_value,
120                 target: _,
121                 unwind: _,
122             } => {
123                 self.mutate_place(location, *drop_place, Deep);
124                 self.consume_operand(location, new_value);
125             }
126             TerminatorKind::Call {
127                 ref func,
128                 ref args,
129                 destination,
130                 target: _,
131                 cleanup: _,
132                 from_hir_call: _,
133                 fn_span: _,
134             } => {
135                 self.consume_operand(location, func);
136                 for arg in args {
137                     self.consume_operand(location, arg);
138                 }
139                 self.mutate_place(location, *destination, Deep);
140             }
141             TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
142                 self.consume_operand(location, cond);
143                 use rustc_middle::mir::AssertKind;
144                 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
145                     self.consume_operand(location, len);
146                     self.consume_operand(location, index);
147                 }
148             }
149             TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
150                 self.consume_operand(location, value);
151
152                 // Invalidate all borrows of local places
153                 let borrow_set = self.borrow_set;
154                 let resume = self.location_table.start_index(resume.start_location());
155                 for (i, data) in borrow_set.iter_enumerated() {
156                     if borrow_of_local_data(data.borrowed_place) {
157                         self.all_facts.loan_invalidated_at.push((resume, i));
158                     }
159                 }
160
161                 self.mutate_place(location, *resume_arg, Deep);
162             }
163             TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
164                 // Invalidate all borrows of local places
165                 let borrow_set = self.borrow_set;
166                 let start = self.location_table.start_index(location);
167                 for (i, data) in borrow_set.iter_enumerated() {
168                     if borrow_of_local_data(data.borrowed_place) {
169                         self.all_facts.loan_invalidated_at.push((start, i));
170                     }
171                 }
172             }
173             TerminatorKind::InlineAsm {
174                 template: _,
175                 ref operands,
176                 options: _,
177                 line_spans: _,
178                 destination: _,
179                 cleanup: _,
180             } => {
181                 for op in operands {
182                     match *op {
183                         InlineAsmOperand::In { reg: _, ref value } => {
184                             self.consume_operand(location, value);
185                         }
186                         InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
187                             if let Some(place) = place {
188                                 self.mutate_place(location, place, Shallow(None));
189                             }
190                         }
191                         InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
192                             self.consume_operand(location, in_value);
193                             if let Some(out_place) = out_place {
194                                 self.mutate_place(location, out_place, Shallow(None));
195                             }
196                         }
197                         InlineAsmOperand::Const { value: _ }
198                         | InlineAsmOperand::SymFn { value: _ }
199                         | InlineAsmOperand::SymStatic { def_id: _ } => {}
200                     }
201                 }
202             }
203             TerminatorKind::Goto { target: _ }
204             | TerminatorKind::Abort
205             | TerminatorKind::Unreachable
206             | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
207             | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
208                 // no data used, thus irrelevant to borrowck
209             }
210         }
211
212         self.super_terminator(terminator, location);
213     }
214 }
215
216 impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
217     /// Simulates mutation of a place.
218     fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) {
219         self.access_place(
220             location,
221             place,
222             (kind, Write(WriteKind::Mutate)),
223             LocalMutationIsAllowed::ExceptUpvars,
224         );
225     }
226
227     /// Simulates consumption of an operand.
228     fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
229         match *operand {
230             Operand::Copy(place) => {
231                 self.access_place(
232                     location,
233                     place,
234                     (Deep, Read(ReadKind::Copy)),
235                     LocalMutationIsAllowed::No,
236                 );
237             }
238             Operand::Move(place) => {
239                 self.access_place(
240                     location,
241                     place,
242                     (Deep, Write(WriteKind::Move)),
243                     LocalMutationIsAllowed::Yes,
244                 );
245             }
246             Operand::Constant(_) => {}
247         }
248     }
249
250     // Simulates consumption of an rvalue
251     fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
252         match *rvalue {
253             Rvalue::Ref(_ /*rgn*/, bk, place) => {
254                 let access_kind = match bk {
255                     BorrowKind::Shallow => {
256                         (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
257                     }
258                     BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
259                     BorrowKind::Unique | BorrowKind::Mut { .. } => {
260                         let wk = WriteKind::MutableBorrow(bk);
261                         if allow_two_phase_borrow(bk) {
262                             (Deep, Reservation(wk))
263                         } else {
264                             (Deep, Write(wk))
265                         }
266                     }
267                 };
268
269                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
270             }
271
272             Rvalue::AddressOf(mutability, place) => {
273                 let access_kind = match mutability {
274                     Mutability::Mut => (
275                         Deep,
276                         Write(WriteKind::MutableBorrow(BorrowKind::Mut {
277                             allow_two_phase_borrow: false,
278                         })),
279                     ),
280                     Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
281                 };
282
283                 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
284             }
285
286             Rvalue::ThreadLocalRef(_) => {}
287
288             Rvalue::Use(ref operand)
289             | Rvalue::Repeat(ref operand, _)
290             | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
291             | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
292             | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
293                 self.consume_operand(location, operand)
294             }
295             Rvalue::CopyForDeref(ref place) => {
296                 let op = &Operand::Copy(*place);
297                 self.consume_operand(location, op);
298             }
299
300             Rvalue::Len(place) | Rvalue::Discriminant(place) => {
301                 let af = match *rvalue {
302                     Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
303                     Rvalue::Discriminant(..) => None,
304                     _ => unreachable!(),
305                 };
306                 self.access_place(
307                     location,
308                     place,
309                     (Shallow(af), Read(ReadKind::Copy)),
310                     LocalMutationIsAllowed::No,
311                 );
312             }
313
314             Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
315             | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
316                 self.consume_operand(location, operand1);
317                 self.consume_operand(location, operand2);
318             }
319
320             Rvalue::NullaryOp(_op, _ty) => {}
321
322             Rvalue::Aggregate(_, ref operands) => {
323                 for operand in operands {
324                     self.consume_operand(location, operand);
325                 }
326             }
327         }
328     }
329
330     /// Simulates an access to a place.
331     fn access_place(
332         &mut self,
333         location: Location,
334         place: Place<'tcx>,
335         kind: (AccessDepth, ReadOrWrite),
336         _is_local_mutation_allowed: LocalMutationIsAllowed,
337     ) {
338         let (sd, rw) = kind;
339         // note: not doing check_access_permissions checks because they don't generate invalidates
340         self.check_access_for_conflict(location, place, sd, rw);
341     }
342
343     fn check_access_for_conflict(
344         &mut self,
345         location: Location,
346         place: Place<'tcx>,
347         sd: AccessDepth,
348         rw: ReadOrWrite,
349     ) {
350         debug!(
351             "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
352              rw={:?})",
353             location, place, sd, rw,
354         );
355         let tcx = self.tcx;
356         let body = self.body;
357         let borrow_set = self.borrow_set;
358         let indices = self.borrow_set.indices();
359         each_borrow_involving_path(
360             self,
361             tcx,
362             body,
363             location,
364             (sd, place),
365             borrow_set,
366             indices,
367             |this, borrow_index, borrow| {
368                 match (rw, borrow.kind) {
369                     // Obviously an activation is compatible with its own
370                     // reservation (or even prior activating uses of same
371                     // borrow); so don't check if they interfere.
372                     //
373                     // NOTE: *reservations* do conflict with themselves;
374                     // thus aren't injecting unsoundness w/ this check.)
375                     (Activation(_, activating), _) if activating == borrow_index => {
376                         // Activating a borrow doesn't generate any invalidations, since we
377                         // have already taken the reservation
378                     }
379
380                     (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
381                     | (
382                         Read(ReadKind::Borrow(BorrowKind::Shallow)),
383                         BorrowKind::Unique | BorrowKind::Mut { .. },
384                     ) => {
385                         // Reads don't invalidate shared or shallow borrows
386                     }
387
388                     (Read(_), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
389                         // Reading from mere reservations of mutable-borrows is OK.
390                         if !is_active(&this.dominators, borrow, location) {
391                             // If the borrow isn't active yet, reads don't invalidate it
392                             assert!(allow_two_phase_borrow(borrow.kind));
393                             return Control::Continue;
394                         }
395
396                         // Unique and mutable borrows are invalidated by reads from any
397                         // involved path
398                         this.emit_loan_invalidated_at(borrow_index, location);
399                     }
400
401                     (Reservation(_) | Activation(_, _) | Write(_), _) => {
402                         // unique or mutable borrows are invalidated by writes.
403                         // Reservations count as writes since we need to check
404                         // that activating the borrow will be OK
405                         // FIXME(bob_twinkles) is this actually the right thing to do?
406                         this.emit_loan_invalidated_at(borrow_index, location);
407                     }
408                 }
409                 Control::Continue
410             },
411         );
412     }
413
414     /// Generates a new `loan_invalidated_at(L, B)` fact.
415     fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
416         let lidx = self.location_table.start_index(l);
417         self.all_facts.loan_invalidated_at.push((lidx, b));
418     }
419
420     fn check_activations(&mut self, location: Location) {
421         // Two-phase borrow support: For each activation that is newly
422         // generated at this statement, check if it interferes with
423         // another borrow.
424         for &borrow_index in self.borrow_set.activations_at_location(location) {
425             let borrow = &self.borrow_set[borrow_index];
426
427             // only mutable borrows should be 2-phase
428             assert!(match borrow.kind {
429                 BorrowKind::Shared | BorrowKind::Shallow => false,
430                 BorrowKind::Unique | BorrowKind::Mut { .. } => true,
431             });
432
433             self.access_place(
434                 location,
435                 borrow.borrowed_place,
436                 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
437                 LocalMutationIsAllowed::No,
438             );
439
440             // We do not need to call `check_if_path_or_subpath_is_moved`
441             // again, as we already called it when we made the
442             // initial reservation.
443         }
444     }
445 }