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