rustc_borrowck/polonius/legacy/
loan_invalidations.rs1use std::ops::ControlFlow;
2
3use rustc_data_structures::graph::dominators::Dominators;
4use rustc_middle::bug;
5use rustc_middle::mir::visit::Visitor;
6use rustc_middle::mir::*;
7use rustc_middle::ty::TyCtxt;
8use tracing::debug;
9
10use super::{PoloniusFacts, PoloniusLocationTable};
11use crate::borrow_set::BorrowSet;
12use crate::path_utils::*;
13use crate::{
14 AccessDepth, Activation, ArtificialField, BorrowIndex, Deep, LocalMutationIsAllowed, Read,
15 ReadKind, ReadOrWrite, Reservation, Shallow, Write, WriteKind,
16};
17
18pub(super) fn emit_loan_invalidations<'tcx>(
20 tcx: TyCtxt<'tcx>,
21 facts: &mut PoloniusFacts,
22 body: &Body<'tcx>,
23 location_table: &PoloniusLocationTable,
24 borrow_set: &BorrowSet<'tcx>,
25) {
26 let dominators = body.basic_blocks.dominators();
27 let mut visitor =
28 LoanInvalidationsGenerator { facts, borrow_set, tcx, location_table, body, dominators };
29 visitor.visit_body(body);
30}
31
32struct LoanInvalidationsGenerator<'a, 'tcx> {
33 tcx: TyCtxt<'tcx>,
34 facts: &'a mut PoloniusFacts,
35 body: &'a Body<'tcx>,
36 location_table: &'a PoloniusLocationTable,
37 dominators: &'a Dominators<BasicBlock>,
38 borrow_set: &'a BorrowSet<'tcx>,
39}
40
41impl<'a, 'tcx> Visitor<'tcx> for LoanInvalidationsGenerator<'a, 'tcx> {
44 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
45 self.check_activations(location);
46
47 match &statement.kind {
48 StatementKind::Assign(box (lhs, rhs)) => {
49 self.consume_rvalue(location, rhs);
50
51 self.mutate_place(location, *lhs, Shallow(None));
52 }
53 StatementKind::FakeRead(box (_, _)) => {
54 }
56 StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(op)) => {
57 self.consume_operand(location, op);
58 }
59 StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
60 src,
61 dst,
62 count,
63 })) => {
64 self.consume_operand(location, src);
65 self.consume_operand(location, dst);
66 self.consume_operand(location, count);
67 }
68 StatementKind::AscribeUserType(..)
70 | StatementKind::PlaceMention(..)
72 | StatementKind::Coverage(..)
74 | StatementKind::StorageLive(..) => {}
76 StatementKind::StorageDead(local) => {
77 self.access_place(
78 location,
79 Place::from(*local),
80 (Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
81 LocalMutationIsAllowed::Yes,
82 );
83 }
84 StatementKind::ConstEvalCounter
85 | StatementKind::Nop
86 | StatementKind::Retag { .. }
87 | StatementKind::Deinit(..)
88 | StatementKind::BackwardIncompatibleDropHint { .. }
89 | StatementKind::SetDiscriminant { .. } => {
90 bug!("Statement not allowed in this MIR phase")
91 }
92 }
93
94 self.super_statement(statement, location);
95 }
96
97 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
98 self.check_activations(location);
99
100 match &terminator.kind {
101 TerminatorKind::SwitchInt { discr, targets: _ } => {
102 self.consume_operand(location, discr);
103 }
104 TerminatorKind::Drop {
105 place: drop_place,
106 target: _,
107 unwind: _,
108 replace,
109 drop: _,
110 async_fut: _,
111 } => {
112 let write_kind =
113 if *replace { WriteKind::Replace } else { WriteKind::StorageDeadOrDrop };
114 self.access_place(
115 location,
116 *drop_place,
117 (AccessDepth::Drop, Write(write_kind)),
118 LocalMutationIsAllowed::Yes,
119 );
120 }
121 TerminatorKind::Call {
122 func,
123 args,
124 destination,
125 target: _,
126 unwind: _,
127 call_source: _,
128 fn_span: _,
129 } => {
130 self.consume_operand(location, func);
131 for arg in args {
132 self.consume_operand(location, &arg.node);
133 }
134 self.mutate_place(location, *destination, Deep);
135 }
136 TerminatorKind::TailCall { func, args, .. } => {
137 self.consume_operand(location, func);
138 for arg in args {
139 self.consume_operand(location, &arg.node);
140 }
141 }
142 TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
143 self.consume_operand(location, cond);
144 use rustc_middle::mir::AssertKind;
145 if let AssertKind::BoundsCheck { len, index } = &**msg {
146 self.consume_operand(location, len);
147 self.consume_operand(location, index);
148 }
149 }
150 TerminatorKind::Yield { value, resume, resume_arg, drop: _ } => {
151 self.consume_operand(location, value);
152
153 let borrow_set = self.borrow_set;
155 let resume = self.location_table.start_index(resume.start_location());
156 for (i, data) in borrow_set.iter_enumerated() {
157 if borrow_of_local_data(data.borrowed_place) {
158 self.facts.loan_invalidated_at.push((resume, i));
159 }
160 }
161
162 self.mutate_place(location, *resume_arg, Deep);
163 }
164 TerminatorKind::UnwindResume
165 | TerminatorKind::Return
166 | TerminatorKind::CoroutineDrop => {
167 let borrow_set = self.borrow_set;
169 let start = self.location_table.start_index(location);
170 for (i, data) in borrow_set.iter_enumerated() {
171 if borrow_of_local_data(data.borrowed_place) {
172 self.facts.loan_invalidated_at.push((start, i));
173 }
174 }
175 }
176 TerminatorKind::InlineAsm {
177 asm_macro: _,
178 template: _,
179 operands,
180 options: _,
181 line_spans: _,
182 targets: _,
183 unwind: _,
184 } => {
185 for op in operands {
186 match op {
187 InlineAsmOperand::In { reg: _, value } => {
188 self.consume_operand(location, value);
189 }
190 InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
191 if let &Some(place) = place {
192 self.mutate_place(location, place, Shallow(None));
193 }
194 }
195 InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
196 self.consume_operand(location, in_value);
197 if let &Some(out_place) = out_place {
198 self.mutate_place(location, out_place, Shallow(None));
199 }
200 }
201 InlineAsmOperand::Const { value: _ }
202 | InlineAsmOperand::SymFn { value: _ }
203 | InlineAsmOperand::SymStatic { def_id: _ }
204 | InlineAsmOperand::Label { target_index: _ } => {}
205 }
206 }
207 }
208 TerminatorKind::Goto { target: _ }
209 | TerminatorKind::UnwindTerminate(_)
210 | TerminatorKind::Unreachable
211 | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ }
212 | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => {
213 }
215 }
216
217 self.super_terminator(terminator, location);
218 }
219}
220
221impl<'a, 'tcx> LoanInvalidationsGenerator<'a, 'tcx> {
222 fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) {
224 self.access_place(
225 location,
226 place,
227 (kind, Write(WriteKind::Mutate)),
228 LocalMutationIsAllowed::ExceptUpvars,
229 );
230 }
231
232 fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) {
234 match *operand {
235 Operand::Copy(place) => {
236 self.access_place(
237 location,
238 place,
239 (Deep, Read(ReadKind::Copy)),
240 LocalMutationIsAllowed::No,
241 );
242 }
243 Operand::Move(place) => {
244 self.access_place(
245 location,
246 place,
247 (Deep, Write(WriteKind::Move)),
248 LocalMutationIsAllowed::Yes,
249 );
250 }
251 Operand::Constant(_) => {}
252 }
253 }
254
255 fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) {
257 match rvalue {
258 &Rvalue::Ref(_ , bk, place) => {
259 let access_kind = match bk {
260 BorrowKind::Fake(FakeBorrowKind::Shallow) => {
261 (Shallow(Some(ArtificialField::FakeBorrow)), Read(ReadKind::Borrow(bk)))
262 }
263 BorrowKind::Shared | BorrowKind::Fake(FakeBorrowKind::Deep) => {
264 (Deep, Read(ReadKind::Borrow(bk)))
265 }
266 BorrowKind::Mut { .. } => {
267 let wk = WriteKind::MutableBorrow(bk);
268 if bk.allows_two_phase_borrow() {
269 (Deep, Reservation(wk))
270 } else {
271 (Deep, Write(wk))
272 }
273 }
274 };
275
276 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
277 }
278
279 &Rvalue::RawPtr(kind, place) => {
280 let access_kind = match kind {
281 RawPtrKind::Mut => (
282 Deep,
283 Write(WriteKind::MutableBorrow(BorrowKind::Mut {
284 kind: MutBorrowKind::Default,
285 })),
286 ),
287 RawPtrKind::Const => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))),
288 RawPtrKind::FakeForPtrMetadata => {
289 (Shallow(Some(ArtificialField::ArrayLength)), Read(ReadKind::Copy))
290 }
291 };
292
293 self.access_place(location, place, access_kind, LocalMutationIsAllowed::No);
294 }
295
296 Rvalue::ThreadLocalRef(_) => {}
297
298 Rvalue::Use(operand)
299 | Rvalue::Repeat(operand, _)
300 | Rvalue::UnaryOp(_ , operand)
301 | Rvalue::Cast(_ , operand, _ )
302 | Rvalue::ShallowInitBox(operand, _ ) => self.consume_operand(location, operand),
303
304 &Rvalue::CopyForDeref(place) => {
305 let op = &Operand::Copy(place);
306 self.consume_operand(location, op);
307 }
308
309 &(Rvalue::Len(place) | Rvalue::Discriminant(place)) => {
310 let af = match rvalue {
311 Rvalue::Len(..) => Some(ArtificialField::ArrayLength),
312 Rvalue::Discriminant(..) => None,
313 _ => unreachable!(),
314 };
315 self.access_place(
316 location,
317 place,
318 (Shallow(af), Read(ReadKind::Copy)),
319 LocalMutationIsAllowed::No,
320 );
321 }
322
323 Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
324 self.consume_operand(location, operand1);
325 self.consume_operand(location, operand2);
326 }
327
328 Rvalue::NullaryOp(_op, _ty) => {}
329
330 Rvalue::Aggregate(_, operands) => {
331 for operand in operands {
332 self.consume_operand(location, operand);
333 }
334 }
335
336 Rvalue::WrapUnsafeBinder(op, _) => {
337 self.consume_operand(location, op);
338 }
339 }
340 }
341
342 fn access_place(
344 &mut self,
345 location: Location,
346 place: Place<'tcx>,
347 kind: (AccessDepth, ReadOrWrite),
348 _is_local_mutation_allowed: LocalMutationIsAllowed,
349 ) {
350 let (sd, rw) = kind;
351 self.check_access_for_conflict(location, place, sd, rw);
353 }
354
355 fn check_access_for_conflict(
356 &mut self,
357 location: Location,
358 place: Place<'tcx>,
359 sd: AccessDepth,
360 rw: ReadOrWrite,
361 ) {
362 debug!(
363 "check_access_for_conflict(location={:?}, place={:?}, sd={:?}, rw={:?})",
364 location, place, sd, rw,
365 );
366 each_borrow_involving_path(
367 self,
368 self.tcx,
369 self.body,
370 (sd, place),
371 self.borrow_set,
372 |_| true,
373 |this, borrow_index, borrow| {
374 match (rw, borrow.kind) {
375 (Activation(_, activating), _) if activating == borrow_index => {
382 }
385
386 (Read(_), BorrowKind::Fake(_) | BorrowKind::Shared)
387 | (
388 Read(ReadKind::Borrow(BorrowKind::Fake(FakeBorrowKind::Shallow))),
389 BorrowKind::Mut { .. },
390 ) => {
391 }
393
394 (Read(_), BorrowKind::Mut { .. }) => {
395 if !is_active(this.dominators, borrow, location) {
397 assert!(borrow.kind.allows_two_phase_borrow());
399 return ControlFlow::Continue(());
400 }
401
402 this.emit_loan_invalidated_at(borrow_index, location);
405 }
406
407 (Reservation(_) | Activation(_, _) | Write(_), _) => {
408 this.emit_loan_invalidated_at(borrow_index, location);
413 }
414 }
415 ControlFlow::Continue(())
416 },
417 );
418 }
419
420 fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) {
422 let lidx = self.location_table.start_index(l);
423 self.facts.loan_invalidated_at.push((lidx, b));
424 }
425
426 fn check_activations(&mut self, location: Location) {
427 for &borrow_index in self.borrow_set.activations_at_location(location) {
431 let borrow = &self.borrow_set[borrow_index];
432
433 assert!(match borrow.kind {
435 BorrowKind::Shared | BorrowKind::Fake(_) => false,
436 BorrowKind::Mut { .. } => true,
437 });
438
439 self.access_place(
440 location,
441 borrow.borrowed_place,
442 (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
443 LocalMutationIsAllowed::No,
444 );
445
446 }
450 }
451}