]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_borrowck/src/invalidation.rs
New upstream version 1.57.0+dfsg1
[rustc.git] / compiler / rustc_borrowck / src / invalidation.rs
CommitLineData
8faf50e0 1use rustc_data_structures::graph::dominators::Dominators;
ba9703b0 2use rustc_middle::mir::visit::Visitor;
f9f354fc 3use rustc_middle::mir::{BasicBlock, Body, Location, Place, Rvalue};
ba9703b0 4use rustc_middle::mir::{BorrowKind, Mutability, Operand};
f035d41b 5use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind};
ba9703b0
XL
6use rustc_middle::mir::{Statement, StatementKind};
7use rustc_middle::ty::TyCtxt;
cdc7bbd5 8use std::iter;
94b46f34 9
c295e0f8 10use crate::{
dfeec247 11 borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, path_utils::*, AccessDepth,
c295e0f8
XL
12 Activation, ArtificialField, BorrowIndex, Deep, JustWrite, LocalMutationIsAllowed, MutateMode,
13 Read, ReadKind, ReadOrWrite, Reservation, Shallow, Write, WriteAndRead, WriteKind,
60c5eb7d
XL
14};
15
dc9dc135
XL
16pub(super) fn generate_invalidates<'tcx>(
17 tcx: TyCtxt<'tcx>,
94b46f34
XL
18 all_facts: &mut Option<AllFacts>,
19 location_table: &LocationTable,
f9f354fc 20 body: &Body<'tcx>,
94b46f34
XL
21 borrow_set: &BorrowSet<'tcx>,
22) {
0bf4aa26 23 if all_facts.is_none() {
94b46f34
XL
24 // Nothing to do if we don't have any facts
25 return;
26 }
27
94b46f34 28 if let Some(all_facts) = all_facts {
60c5eb7d 29 let _prof_timer = tcx.prof.generic_activity("polonius_fact_generation");
dc9dc135 30 let dominators = body.dominators();
94b46f34
XL
31 let mut ig = InvalidationGenerator {
32 all_facts,
33 borrow_set,
0bf4aa26 34 tcx,
94b46f34 35 location_table,
60c5eb7d 36 body: &body,
94b46f34 37 dominators,
94b46f34 38 };
f9f354fc 39 ig.visit_body(body);
94b46f34
XL
40 }
41}
42
dc9dc135
XL
43struct InvalidationGenerator<'cx, 'tcx> {
44 tcx: TyCtxt<'tcx>,
0bf4aa26
XL
45 all_facts: &'cx mut AllFacts,
46 location_table: &'cx LocationTable,
dc9dc135 47 body: &'cx Body<'tcx>,
94b46f34 48 dominators: Dominators<BasicBlock>,
0bf4aa26 49 borrow_set: &'cx BorrowSet<'tcx>,
94b46f34
XL
50}
51
9fa01778
XL
52/// Visits the whole MIR and generates `invalidates()` facts.
53/// Most of the code implementing this was stolen from `borrow_check/mod.rs`.
dc9dc135 54impl<'cx, 'tcx> Visitor<'tcx> for InvalidationGenerator<'cx, 'tcx> {
dfeec247 55 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
0731742a
XL
56 self.check_activations(location);
57
ba9703b0
XL
58 match &statement.kind {
59 StatementKind::Assign(box (lhs, rhs)) => {
dfeec247 60 self.consume_rvalue(location, rhs);
94b46f34 61
ba9703b0 62 self.mutate_place(location, *lhs, Shallow(None), JustWrite);
94b46f34 63 }
cdc7bbd5 64 StatementKind::FakeRead(box (_, _)) => {
74b04a01 65 // Only relevant for initialized/liveness/safety checks.
94b46f34 66 }
ba9703b0
XL
67 StatementKind::SetDiscriminant { place, variant_index: _ } => {
68 self.mutate_place(location, **place, Shallow(None), JustWrite);
94b46f34 69 }
ba9703b0 70 StatementKind::LlvmInlineAsm(asm) => {
cdc7bbd5 71 for (o, output) in iter::zip(&asm.asm.outputs, &*asm.outputs) {
94b46f34
XL
72 if o.is_indirect {
73 // FIXME(eddyb) indirect inline asm outputs should
532ac7d7 74 // be encoded through MIR place derefs instead.
94b46f34 75 self.access_place(
48663c56 76 location,
ba9703b0 77 *output,
94b46f34
XL
78 (Deep, Read(ReadKind::Copy)),
79 LocalMutationIsAllowed::No,
80 );
81 } else {
82 self.mutate_place(
48663c56 83 location,
ba9703b0 84 *output,
94b46f34
XL
85 if o.is_rw { Deep } else { Shallow(None) },
86 if o.is_rw { WriteAndRead } else { JustWrite },
87 );
88 }
89 }
532ac7d7 90 for (_, input) in asm.inputs.iter() {
48663c56 91 self.consume_operand(location, input);
94b46f34
XL
92 }
93 }
6a06907d
XL
94 StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
95 ref src,
96 ref dst,
97 ref count,
98 }) => {
99 self.consume_operand(location, src);
100 self.consume_operand(location, dst);
101 self.consume_operand(location, count);
102 }
dfeec247 103 StatementKind::Nop
3dfed10e 104 | StatementKind::Coverage(..)
dfeec247
XL
105 | StatementKind::AscribeUserType(..)
106 | StatementKind::Retag { .. }
107 | StatementKind::StorageLive(..) => {
a1dfa0c6 108 // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant
94b46f34
XL
109 // to borrow check.
110 }
111 StatementKind::StorageDead(local) => {
112 self.access_place(
48663c56 113 location,
ba9703b0 114 Place::from(*local),
94b46f34
XL
115 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
116 LocalMutationIsAllowed::Yes,
117 );
118 }
119 }
120
48663c56 121 self.super_statement(statement, location);
94b46f34
XL
122 }
123
f035d41b 124 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
0731742a
XL
125 self.check_activations(location);
126
f035d41b 127 match &terminator.kind {
29967ef6 128 TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => {
48663c56 129 self.consume_operand(location, discr);
94b46f34 130 }
f035d41b 131 TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => {
0bf4aa26 132 self.access_place(
48663c56 133 location,
ba9703b0 134 *drop_place,
0bf4aa26
XL
135 (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)),
136 LocalMutationIsAllowed::Yes,
137 );
94b46f34
XL
138 }
139 TerminatorKind::DropAndReplace {
f035d41b 140 place: drop_place,
94b46f34
XL
141 value: ref new_value,
142 target: _,
143 unwind: _,
144 } => {
ba9703b0 145 self.mutate_place(location, *drop_place, Deep, JustWrite);
dfeec247 146 self.consume_operand(location, new_value);
94b46f34
XL
147 }
148 TerminatorKind::Call {
149 ref func,
150 ref args,
ba9703b0 151 destination,
94b46f34 152 cleanup: _,
0bf4aa26 153 from_hir_call: _,
f035d41b 154 fn_span: _,
94b46f34 155 } => {
48663c56 156 self.consume_operand(location, func);
94b46f34 157 for arg in args {
48663c56 158 self.consume_operand(location, arg);
94b46f34 159 }
ba9703b0
XL
160 if let Some((dest, _ /*bb*/)) = destination {
161 self.mutate_place(location, *dest, Deep, JustWrite);
94b46f34
XL
162 }
163 }
dfeec247 164 TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => {
48663c56 165 self.consume_operand(location, cond);
ba9703b0 166 use rustc_middle::mir::AssertKind;
74b04a01 167 if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
48663c56
XL
168 self.consume_operand(location, len);
169 self.consume_operand(location, index);
94b46f34
XL
170 }
171 }
74b04a01 172 TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => {
48663c56 173 self.consume_operand(location, value);
94b46f34
XL
174
175 // Invalidate all borrows of local places
6a06907d 176 let borrow_set = self.borrow_set;
94b46f34 177 let resume = self.location_table.start_index(resume.start_location());
3dfed10e
XL
178 for (i, data) in borrow_set.iter_enumerated() {
179 if borrow_of_local_data(data.borrowed_place) {
94222f64 180 self.all_facts.loan_invalidated_at.push((resume, i));
94b46f34
XL
181 }
182 }
74b04a01 183
ba9703b0 184 self.mutate_place(location, *resume_arg, Deep, JustWrite);
94b46f34
XL
185 }
186 TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => {
187 // Invalidate all borrows of local places
6a06907d 188 let borrow_set = self.borrow_set;
94b46f34 189 let start = self.location_table.start_index(location);
3dfed10e
XL
190 for (i, data) in borrow_set.iter_enumerated() {
191 if borrow_of_local_data(data.borrowed_place) {
94222f64 192 self.all_facts.loan_invalidated_at.push((start, i));
94b46f34
XL
193 }
194 }
195 }
f9f354fc
XL
196 TerminatorKind::InlineAsm {
197 template: _,
198 ref operands,
199 options: _,
200 line_spans: _,
201 destination: _,
202 } => {
203 for op in operands {
204 match *op {
cdc7bbd5 205 InlineAsmOperand::In { reg: _, ref value } => {
f9f354fc
XL
206 self.consume_operand(location, value);
207 }
208 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
209 if let Some(place) = place {
210 self.mutate_place(location, place, Shallow(None), JustWrite);
211 }
212 }
213 InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => {
214 self.consume_operand(location, in_value);
215 if let Some(out_place) = out_place {
216 self.mutate_place(location, out_place, Shallow(None), JustWrite);
217 }
218 }
cdc7bbd5
XL
219 InlineAsmOperand::Const { value: _ }
220 | InlineAsmOperand::SymFn { value: _ }
f035d41b 221 | InlineAsmOperand::SymStatic { def_id: _ } => {}
f9f354fc
XL
222 }
223 }
224 }
94b46f34
XL
225 TerminatorKind::Goto { target: _ }
226 | TerminatorKind::Abort
227 | TerminatorKind::Unreachable
f035d41b 228 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
dfeec247 229 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
94b46f34
XL
230 // no data used, thus irrelevant to borrowck
231 }
232 }
233
f035d41b 234 self.super_terminator(terminator, location);
94b46f34
XL
235 }
236}
237
dc9dc135 238impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> {
9fa01778 239 /// Simulates mutation of a place.
94b46f34
XL
240 fn mutate_place(
241 &mut self,
48663c56 242 location: Location,
ba9703b0 243 place: Place<'tcx>,
0bf4aa26 244 kind: AccessDepth,
94b46f34
XL
245 _mode: MutateMode,
246 ) {
247 self.access_place(
48663c56 248 location,
94b46f34
XL
249 place,
250 (kind, Write(WriteKind::Mutate)),
251 LocalMutationIsAllowed::ExceptUpvars,
252 );
253 }
254
9fa01778 255 /// Simulates consumption of an operand.
dfeec247 256 fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
94b46f34 257 match *operand {
ba9703b0 258 Operand::Copy(place) => {
94b46f34 259 self.access_place(
48663c56 260 location,
94b46f34
XL
261 place,
262 (Deep, Read(ReadKind::Copy)),
263 LocalMutationIsAllowed::No,
264 );
265 }
ba9703b0 266 Operand::Move(place) => {
94b46f34 267 self.access_place(
48663c56 268 location,
94b46f34
XL
269 place,
270 (Deep, Write(WriteKind::Move)),
271 LocalMutationIsAllowed::Yes,
272 );
273 }
274 Operand::Constant(_) => {}
275 }
276 }
277
278 // Simulates consumption of an rvalue
dfeec247 279 fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
94b46f34 280 match *rvalue {
ba9703b0 281 Rvalue::Ref(_ /*rgn*/, bk, place) => {
94b46f34 282 let access_kind = match bk {
0bf4aa26
XL
283 BorrowKind::Shallow => {
284 (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk)))
dfeec247 285 }
94b46f34
XL
286 BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))),
287 BorrowKind::Unique | BorrowKind::Mut { .. } => {
288 let wk = WriteKind::MutableBorrow(bk);
48663c56 289 if allow_two_phase_borrow(bk) {
94b46f34
XL
290 (Deep, Reservation(wk))
291 } else {
292 (Deep, Write(wk))
293 }
294 }
295 };
296
dfeec247
XL
297 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
298 }
299
ba9703b0 300 Rvalue::AddressOf(mutability, place) => {
dfeec247
XL
301 let access_kind = match mutability {
302 Mutability::Mut => (
303 Deep,
304 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
305 allow_two_phase_borrow: false,
306 })),
307 ),
308 Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
309 };
310
311 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
94b46f34
XL
312 }
313
f9f354fc
XL
314 Rvalue::ThreadLocalRef(_) => {}
315
94b46f34
XL
316 Rvalue::Use(ref operand)
317 | Rvalue::Repeat(ref operand, _)
318 | Rvalue::UnaryOp(_ /*un_op*/, ref operand)
c295e0f8
XL
319 | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/)
320 | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => {
48663c56 321 self.consume_operand(location, operand)
94b46f34
XL
322 }
323
ba9703b0 324 Rvalue::Len(place) | Rvalue::Discriminant(place) => {
94b46f34 325 let af = match *rvalue {
0731742a
XL
326 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
327 Rvalue::Discriminant(..) => None,
94b46f34
XL
328 _ => unreachable!(),
329 };
330 self.access_place(
48663c56 331 location,
94b46f34 332 place,
0731742a 333 (Shallow(af), Read(ReadKind::Copy)),
94b46f34
XL
334 LocalMutationIsAllowed::No,
335 );
336 }
337
6a06907d
XL
338 Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2))
339 | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => {
48663c56
XL
340 self.consume_operand(location, operand1);
341 self.consume_operand(location, operand2);
94b46f34
XL
342 }
343
dfeec247 344 Rvalue::NullaryOp(_op, _ty) => {}
94b46f34
XL
345
346 Rvalue::Aggregate(_, ref operands) => {
347 for operand in operands {
48663c56 348 self.consume_operand(location, operand);
94b46f34
XL
349 }
350 }
351 }
352 }
353
9fa01778 354 /// Simulates an access to a place.
94b46f34
XL
355 fn access_place(
356 &mut self,
48663c56 357 location: Location,
ba9703b0 358 place: Place<'tcx>,
0bf4aa26 359 kind: (AccessDepth, ReadOrWrite),
94b46f34
XL
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
48663c56 364 self.check_access_for_conflict(location, place, sd, rw);
94b46f34
XL
365 }
366
367 fn check_access_for_conflict(
368 &mut self,
48663c56 369 location: Location,
ba9703b0 370 place: Place<'tcx>,
0bf4aa26 371 sd: AccessDepth,
94b46f34
XL
372 rw: ReadOrWrite,
373 ) {
374 debug!(
48663c56 375 "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \
94b46f34 376 rw={:?})",
dfeec247 377 location, place, sd, rw,
94b46f34 378 );
0bf4aa26 379 let tcx = self.tcx;
dc9dc135 380 let body = self.body;
6a06907d 381 let borrow_set = self.borrow_set;
3dfed10e 382 let indices = self.borrow_set.indices();
94b46f34
XL
383 each_borrow_involving_path(
384 self,
385 tcx,
dc9dc135 386 body,
48663c56 387 location,
94b46f34 388 (sd, place),
6a06907d 389 borrow_set,
94b46f34
XL
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
ba9703b0
XL
404 (Read(_), BorrowKind::Shallow | BorrowKind::Shared)
405 | (
406 Read(ReadKind::Borrow(BorrowKind::Shallow)),
407 BorrowKind::Unique | BorrowKind::Mut { .. },
408 ) => {
532ac7d7 409 // Reads don't invalidate shared or shallow borrows
94b46f34
XL
410 }
411
ba9703b0 412 (Read(_), BorrowKind::Unique | BorrowKind::Mut { .. }) => {
94b46f34 413 // Reading from mere reservations of mutable-borrows is OK.
48663c56 414 if !is_active(&this.dominators, borrow, location) {
94b46f34 415 // If the borrow isn't active yet, reads don't invalidate it
48663c56 416 assert!(allow_two_phase_borrow(borrow.kind));
94b46f34
XL
417 return Control::Continue;
418 }
419
420 // Unique and mutable borrows are invalidated by reads from any
421 // involved path
94222f64 422 this.emit_loan_invalidated_at(borrow_index, location);
94b46f34
XL
423 }
424
ba9703b0 425 (Reservation(_) | Activation(_, _) | Write(_), _) => {
532ac7d7
XL
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?
94222f64 430 this.emit_loan_invalidated_at(borrow_index, location);
532ac7d7 431 }
94b46f34
XL
432 }
433 Control::Continue
434 },
435 );
436 }
437
94222f64
XL
438 /// Generates a new `loan_invalidated_at(L, B)` fact.
439 fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
0bf4aa26 440 let lidx = self.location_table.start_index(l);
94222f64 441 self.all_facts.loan_invalidated_at.push((lidx, b));
94b46f34 442 }
0731742a 443
dfeec247 444 fn check_activations(&mut self, location: Location) {
0731742a
XL
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(
48663c56 458 location,
ba9703b0 459 borrow.borrowed_place,
dfeec247 460 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
0731742a
XL
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 }
94b46f34 469}