]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_clone.rs
Auto merge of #7734 - Manishearth:doc-unsafe-trait, r=camsteffen
[rust.git] / clippy_lints / src / redundant_clone.rs
1 use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
2 use clippy_utils::source::snippet_opt;
3 use clippy_utils::ty::{has_drop, is_copy, is_type_diagnostic_item, walk_ptrs_ty_depth};
4 use clippy_utils::{fn_has_unsatisfiable_preds, match_def_path, paths};
5 use if_chain::if_chain;
6 use rustc_data_structures::{fx::FxHashMap, transitive_relation::TransitiveRelation};
7 use rustc_errors::Applicability;
8 use rustc_hir::intravisit::FnKind;
9 use rustc_hir::{def_id, Body, FnDecl, HirId};
10 use rustc_index::bit_set::{BitSet, HybridBitSet};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::mir::{
13     self, traversal,
14     visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor as _},
15     Mutability,
16 };
17 use rustc_middle::ty::{self, fold::TypeVisitor, Ty, TyCtxt};
18 use rustc_mir_dataflow::{Analysis, AnalysisDomain, GenKill, GenKillAnalysis, ResultsCursor};
19 use rustc_session::{declare_lint_pass, declare_tool_lint};
20 use rustc_span::source_map::{BytePos, Span};
21 use rustc_span::sym;
22 use std::convert::TryFrom;
23 use std::ops::ControlFlow;
24
25 macro_rules! unwrap_or_continue {
26     ($x:expr) => {
27         match $x {
28             Some(x) => x,
29             None => continue,
30         }
31     };
32 }
33
34 declare_clippy_lint! {
35     /// ### What it does
36     /// Checks for a redundant `clone()` (and its relatives) which clones an owned
37     /// value that is going to be dropped without further use.
38     ///
39     /// ### Why is this bad?
40     /// It is not always possible for the compiler to eliminate useless
41     /// allocations and deallocations generated by redundant `clone()`s.
42     ///
43     /// ### Known problems
44     /// False-negatives: analysis performed by this lint is conservative and limited.
45     ///
46     /// ### Example
47     /// ```rust
48     /// # use std::path::Path;
49     /// # #[derive(Clone)]
50     /// # struct Foo;
51     /// # impl Foo {
52     /// #     fn new() -> Self { Foo {} }
53     /// # }
54     /// # fn call(x: Foo) {}
55     /// {
56     ///     let x = Foo::new();
57     ///     call(x.clone());
58     ///     call(x.clone()); // this can just pass `x`
59     /// }
60     ///
61     /// ["lorem", "ipsum"].join(" ").to_string();
62     ///
63     /// Path::new("/a/b").join("c").to_path_buf();
64     /// ```
65     pub REDUNDANT_CLONE,
66     perf,
67     "`clone()` of an owned value that is going to be dropped immediately"
68 }
69
70 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
71
72 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
73     #[allow(clippy::too_many_lines)]
74     fn check_fn(
75         &mut self,
76         cx: &LateContext<'tcx>,
77         _: FnKind<'tcx>,
78         _: &'tcx FnDecl<'_>,
79         body: &'tcx Body<'_>,
80         _: Span,
81         _: HirId,
82     ) {
83         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
84
85         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
86         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
87             return;
88         }
89
90         let mir = cx.tcx.optimized_mir(def_id.to_def_id());
91
92         let possible_origin = {
93             let mut vis = PossibleOriginVisitor::new(mir);
94             vis.visit_body(mir);
95             vis.into_map(cx)
96         };
97         let maybe_storage_live_result = MaybeStorageLive
98             .into_engine(cx.tcx, mir)
99             .pass_name("redundant_clone")
100             .iterate_to_fixpoint()
101             .into_results_cursor(mir);
102         let mut possible_borrower = {
103             let mut vis = PossibleBorrowerVisitor::new(cx, mir, possible_origin);
104             vis.visit_body(mir);
105             vis.into_map(cx, maybe_storage_live_result)
106         };
107
108         for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
109             let terminator = bbdata.terminator();
110
111             if terminator.source_info.span.from_expansion() {
112                 continue;
113             }
114
115             // Give up on loops
116             if terminator.successors().any(|s| *s == bb) {
117                 continue;
118             }
119
120             let (fn_def_id, arg, arg_ty, clone_ret) =
121                 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
122
123             let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
124                 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
125                 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD)
126                     && is_type_diagnostic_item(cx, arg_ty, sym::string_type));
127
128             let from_deref = !from_borrow
129                 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
130                     || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
131
132             if !from_borrow && !from_deref {
133                 continue;
134             }
135
136             if let ty::Adt(def, _) = arg_ty.kind() {
137                 if match_def_path(cx, def.did, &paths::MEM_MANUALLY_DROP) {
138                     continue;
139                 }
140             }
141
142             // `{ arg = &cloned; clone(move arg); }` or `{ arg = &cloned; to_path_buf(arg); }`
143             let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
144
145             let loc = mir::Location {
146                 block: bb,
147                 statement_index: bbdata.statements.len(),
148             };
149
150             // `Local` to be cloned, and a local of `clone` call's destination
151             let (local, ret_local) = if from_borrow {
152                 // `res = clone(arg)` can be turned into `res = move arg;`
153                 // if `arg` is the only borrow of `cloned` at this point.
154
155                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
156                     continue;
157                 }
158
159                 (cloned, clone_ret)
160             } else {
161                 // `arg` is a reference as it is `.deref()`ed in the previous block.
162                 // Look into the predecessor block and find out the source of deref.
163
164                 let ps = &mir.predecessors()[bb];
165                 if ps.len() != 1 {
166                     continue;
167                 }
168                 let pred_terminator = mir[ps[0]].terminator();
169
170                 // receiver of the `deref()` call
171                 let (pred_arg, deref_clone_ret) = if_chain! {
172                     if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, res)) =
173                         is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
174                     if res == cloned;
175                     if cx.tcx.is_diagnostic_item(sym::deref_method, pred_fn_def_id);
176                     if is_type_diagnostic_item(cx, pred_arg_ty, sym::PathBuf)
177                         || is_type_diagnostic_item(cx, pred_arg_ty, sym::OsString);
178                     then {
179                         (pred_arg, res)
180                     } else {
181                         continue;
182                     }
183                 };
184
185                 let (local, cannot_move_out) =
186                     unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
187                 let loc = mir::Location {
188                     block: bb,
189                     statement_index: mir.basic_blocks()[bb].statements.len(),
190                 };
191
192                 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
193                 // at the last statement:
194                 //
195                 // ```
196                 // pred_arg = &local;
197                 // cloned = deref(pred_arg);
198                 // arg = &cloned;
199                 // StorageDead(pred_arg);
200                 // res = to_path_buf(cloned);
201                 // ```
202                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
203                     continue;
204                 }
205
206                 (local, deref_clone_ret)
207             };
208
209             let clone_usage = if local == ret_local {
210                 CloneUsage {
211                     cloned_used: false,
212                     cloned_consume_or_mutate_loc: None,
213                     clone_consumed_or_mutated: true,
214                 }
215             } else {
216                 let clone_usage = visit_clone_usage(local, ret_local, mir, bb);
217                 if clone_usage.cloned_used && clone_usage.clone_consumed_or_mutated {
218                     // cloned value is used, and the clone is modified or moved
219                     continue;
220                 } else if let Some(loc) = clone_usage.cloned_consume_or_mutate_loc {
221                     // cloned value is mutated, and the clone is alive.
222                     if possible_borrower.is_alive_at(ret_local, loc) {
223                         continue;
224                     }
225                 }
226                 clone_usage
227             };
228
229             let span = terminator.source_info.span;
230             let scope = terminator.source_info.scope;
231             let node = mir.source_scopes[scope]
232                 .local_data
233                 .as_ref()
234                 .assert_crate_local()
235                 .lint_root;
236
237             if_chain! {
238                 if let Some(snip) = snippet_opt(cx, span);
239                 if let Some(dot) = snip.rfind('.');
240                 then {
241                     let sugg_span = span.with_lo(
242                         span.lo() + BytePos(u32::try_from(dot).unwrap())
243                     );
244                     let mut app = Applicability::MaybeIncorrect;
245
246                     let call_snip = &snip[dot + 1..];
247                     // Machine applicable when `call_snip` looks like `foobar()`
248                     if let Some(call_snip) = call_snip.strip_suffix("()").map(str::trim) {
249                         if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
250                             app = Applicability::MachineApplicable;
251                         }
252                     }
253
254                     span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
255                         diag.span_suggestion(
256                             sugg_span,
257                             "remove this",
258                             String::new(),
259                             app,
260                         );
261                         if clone_usage.cloned_used {
262                             diag.span_note(
263                                 span,
264                                 "cloned value is neither consumed nor mutated",
265                             );
266                         } else {
267                             diag.span_note(
268                                 span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
269                                 "this value is dropped without further use",
270                             );
271                         }
272                     });
273                 } else {
274                     span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
275                 }
276             }
277         }
278     }
279 }
280
281 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
282 fn is_call_with_ref_arg<'tcx>(
283     cx: &LateContext<'tcx>,
284     mir: &'tcx mir::Body<'tcx>,
285     kind: &'tcx mir::TerminatorKind<'tcx>,
286 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, mir::Local)> {
287     if_chain! {
288         if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
289         if args.len() == 1;
290         if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
291         if let ty::FnDef(def_id, _) = *func.ty(&*mir, cx.tcx).kind();
292         if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
293         if !is_copy(cx, inner_ty);
294         then {
295             Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
296         } else {
297             None
298         }
299     }
300 }
301
302 type CannotMoveOut = bool;
303
304 /// Finds the first `to = (&)from`, and returns
305 /// ``Some((from, whether `from` cannot be moved out))``.
306 fn find_stmt_assigns_to<'tcx>(
307     cx: &LateContext<'tcx>,
308     mir: &mir::Body<'tcx>,
309     to_local: mir::Local,
310     by_ref: bool,
311     bb: mir::BasicBlock,
312 ) -> Option<(mir::Local, CannotMoveOut)> {
313     let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
314         if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
315             return if *local == to_local { Some(v) } else { None };
316         }
317
318         None
319     })?;
320
321     match (by_ref, &*rvalue) {
322         (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
323             Some(base_local_and_movability(cx, mir, *place))
324         },
325         (false, mir::Rvalue::Ref(_, _, place)) => {
326             if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
327                 Some(base_local_and_movability(cx, mir, *place))
328             } else {
329                 None
330             }
331         },
332         _ => None,
333     }
334 }
335
336 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
337 /// if it is already a `Local`.
338 ///
339 /// Also reports whether given `place` cannot be moved out.
340 fn base_local_and_movability<'tcx>(
341     cx: &LateContext<'tcx>,
342     mir: &mir::Body<'tcx>,
343     place: mir::Place<'tcx>,
344 ) -> (mir::Local, CannotMoveOut) {
345     use rustc_middle::mir::PlaceRef;
346
347     // Dereference. You cannot move things out from a borrowed value.
348     let mut deref = false;
349     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
350     let mut field = false;
351     // If projection is a slice index then clone can be removed only if the
352     // underlying type implements Copy
353     let mut slice = false;
354
355     let PlaceRef { local, mut projection } = place.as_ref();
356     while let [base @ .., elem] = projection {
357         projection = base;
358         deref |= matches!(elem, mir::ProjectionElem::Deref);
359         field |= matches!(elem, mir::ProjectionElem::Field(..))
360             && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
361         slice |= matches!(elem, mir::ProjectionElem::Index(..))
362             && !is_copy(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
363     }
364
365     (local, deref || field || slice)
366 }
367
368 #[derive(Default)]
369 struct CloneUsage {
370     /// Whether the cloned value is used after the clone.
371     cloned_used: bool,
372     /// The first location where the cloned value is consumed or mutated, if any.
373     cloned_consume_or_mutate_loc: Option<mir::Location>,
374     /// Whether the clone value is mutated.
375     clone_consumed_or_mutated: bool,
376 }
377 fn visit_clone_usage(cloned: mir::Local, clone: mir::Local, mir: &mir::Body<'_>, bb: mir::BasicBlock) -> CloneUsage {
378     struct V {
379         cloned: mir::Local,
380         clone: mir::Local,
381         result: CloneUsage,
382     }
383     impl<'tcx> mir::visit::Visitor<'tcx> for V {
384         fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
385             let statements = &data.statements;
386             for (statement_index, statement) in statements.iter().enumerate() {
387                 self.visit_statement(statement, mir::Location { block, statement_index });
388             }
389
390             self.visit_terminator(
391                 data.terminator(),
392                 mir::Location {
393                     block,
394                     statement_index: statements.len(),
395                 },
396             );
397         }
398
399         fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, loc: mir::Location) {
400             let local = place.local;
401
402             if local == self.cloned
403                 && !matches!(
404                     ctx,
405                     PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_)
406                 )
407             {
408                 self.result.cloned_used = true;
409                 self.result.cloned_consume_or_mutate_loc = self.result.cloned_consume_or_mutate_loc.or_else(|| {
410                     matches!(
411                         ctx,
412                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
413                             | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
414                     )
415                     .then(|| loc)
416                 });
417             } else if local == self.clone {
418                 match ctx {
419                     PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
420                     | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
421                         self.result.clone_consumed_or_mutated = true;
422                     },
423                     _ => {},
424                 }
425             }
426         }
427     }
428
429     let init = CloneUsage {
430         cloned_used: false,
431         cloned_consume_or_mutate_loc: None,
432         // Consider non-temporary clones consumed.
433         // TODO: Actually check for mutation of non-temporaries.
434         clone_consumed_or_mutated: mir.local_kind(clone) != mir::LocalKind::Temp,
435     };
436     traversal::ReversePostorder::new(mir, bb)
437         .skip(1)
438         .fold(init, |usage, (tbb, tdata)| {
439             // Short-circuit
440             if (usage.cloned_used && usage.clone_consumed_or_mutated) ||
441                 // Give up on loops
442                 tdata.terminator().successors().any(|s| *s == bb)
443             {
444                 return CloneUsage {
445                     cloned_used: true,
446                     clone_consumed_or_mutated: true,
447                     ..usage
448                 };
449             }
450
451             let mut v = V {
452                 cloned,
453                 clone,
454                 result: usage,
455             };
456             v.visit_basic_block_data(tbb, tdata);
457             v.result
458         })
459 }
460
461 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
462 #[derive(Copy, Clone)]
463 struct MaybeStorageLive;
464
465 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
466     type Domain = BitSet<mir::Local>;
467     const NAME: &'static str = "maybe_storage_live";
468
469     fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
470         // bottom = dead
471         BitSet::new_empty(body.local_decls.len())
472     }
473
474     fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain) {
475         for arg in body.args_iter() {
476             state.insert(arg);
477         }
478     }
479 }
480
481 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
482     type Idx = mir::Local;
483
484     fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
485         match stmt.kind {
486             mir::StatementKind::StorageLive(l) => trans.gen(l),
487             mir::StatementKind::StorageDead(l) => trans.kill(l),
488             _ => (),
489         }
490     }
491
492     fn terminator_effect(
493         &self,
494         _trans: &mut impl GenKill<Self::Idx>,
495         _terminator: &mir::Terminator<'tcx>,
496         _loc: mir::Location,
497     ) {
498     }
499
500     fn call_return_effect(
501         &self,
502         _in_out: &mut impl GenKill<Self::Idx>,
503         _block: mir::BasicBlock,
504         _func: &mir::Operand<'tcx>,
505         _args: &[mir::Operand<'tcx>],
506         _return_place: mir::Place<'tcx>,
507     ) {
508         // Nothing to do when a call returns successfully
509     }
510 }
511
512 /// Collects the possible borrowers of each local.
513 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
514 /// possible borrowers of `a`.
515 struct PossibleBorrowerVisitor<'a, 'tcx> {
516     possible_borrower: TransitiveRelation<mir::Local>,
517     body: &'a mir::Body<'tcx>,
518     cx: &'a LateContext<'tcx>,
519     possible_origin: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
520 }
521
522 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
523     fn new(
524         cx: &'a LateContext<'tcx>,
525         body: &'a mir::Body<'tcx>,
526         possible_origin: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
527     ) -> Self {
528         Self {
529             possible_borrower: TransitiveRelation::default(),
530             cx,
531             body,
532             possible_origin,
533         }
534     }
535
536     fn into_map(
537         self,
538         cx: &LateContext<'tcx>,
539         maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
540     ) -> PossibleBorrowerMap<'a, 'tcx> {
541         let mut map = FxHashMap::default();
542         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
543             if is_copy(cx, self.body.local_decls[row].ty) {
544                 continue;
545             }
546
547             let borrowers = self.possible_borrower.reachable_from(&row);
548             if !borrowers.is_empty() {
549                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
550                 for &c in borrowers {
551                     if c != mir::Local::from_usize(0) {
552                         bs.insert(c);
553                     }
554                 }
555
556                 if !bs.is_empty() {
557                     map.insert(row, bs);
558                 }
559             }
560         }
561
562         let bs = BitSet::new_empty(self.body.local_decls.len());
563         PossibleBorrowerMap {
564             map,
565             maybe_live,
566             bitset: (bs.clone(), bs),
567         }
568     }
569 }
570
571 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
572     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
573         let lhs = place.local;
574         match rvalue {
575             mir::Rvalue::Ref(_, _, borrowed) => {
576                 self.possible_borrower.add(borrowed.local, lhs);
577             },
578             other => {
579                 if ContainsRegion(self.cx.tcx)
580                     .visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty)
581                     .is_continue()
582                 {
583                     return;
584                 }
585                 rvalue_locals(other, |rhs| {
586                     if lhs != rhs {
587                         self.possible_borrower.add(rhs, lhs);
588                     }
589                 });
590             },
591         }
592     }
593
594     fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
595         if let mir::TerminatorKind::Call {
596             args,
597             destination: Some((mir::Place { local: dest, .. }, _)),
598             ..
599         } = &terminator.kind
600         {
601             // TODO add doc
602             // If the call returns something with lifetimes,
603             // let's conservatively assume the returned value contains lifetime of all the arguments.
604             // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
605
606             let mut immutable_borrowers = vec![];
607             let mut mutable_borrowers = vec![];
608
609             for op in args {
610                 match op {
611                     mir::Operand::Copy(p) | mir::Operand::Move(p) => {
612                         if let ty::Ref(_, _, Mutability::Mut) = self.body.local_decls[p.local].ty.kind() {
613                             mutable_borrowers.push(p.local);
614                         } else {
615                             immutable_borrowers.push(p.local);
616                         }
617                     },
618                     mir::Operand::Constant(..) => (),
619                 }
620             }
621
622             let mut mutable_variables: Vec<mir::Local> = mutable_borrowers
623                 .iter()
624                 .filter_map(|r| self.possible_origin.get(r))
625                 .flat_map(HybridBitSet::iter)
626                 .collect();
627
628             if ContainsRegion(self.cx.tcx)
629                 .visit_ty(self.body.local_decls[*dest].ty)
630                 .is_break()
631             {
632                 mutable_variables.push(*dest);
633             }
634
635             for y in mutable_variables {
636                 for x in &immutable_borrowers {
637                     self.possible_borrower.add(*x, y);
638                 }
639                 for x in &mutable_borrowers {
640                     self.possible_borrower.add(*x, y);
641                 }
642             }
643         }
644     }
645 }
646
647 /// Collect possible borrowed for every `&mut` local.
648 /// For exampel, `_1 = &mut _2` generate _1: {_2,...}
649 /// Known Problems: not sure all borrowed are tracked
650 struct PossibleOriginVisitor<'a, 'tcx> {
651     possible_origin: TransitiveRelation<mir::Local>,
652     body: &'a mir::Body<'tcx>,
653 }
654
655 impl<'a, 'tcx> PossibleOriginVisitor<'a, 'tcx> {
656     fn new(body: &'a mir::Body<'tcx>) -> Self {
657         Self {
658             possible_origin: TransitiveRelation::default(),
659             body,
660         }
661     }
662
663     fn into_map(self, cx: &LateContext<'tcx>) -> FxHashMap<mir::Local, HybridBitSet<mir::Local>> {
664         let mut map = FxHashMap::default();
665         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
666             if is_copy(cx, self.body.local_decls[row].ty) {
667                 continue;
668             }
669
670             let borrowers = self.possible_origin.reachable_from(&row);
671             if !borrowers.is_empty() {
672                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
673                 for &c in borrowers {
674                     if c != mir::Local::from_usize(0) {
675                         bs.insert(c);
676                     }
677                 }
678
679                 if !bs.is_empty() {
680                     map.insert(row, bs);
681                 }
682             }
683         }
684         map
685     }
686 }
687
688 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleOriginVisitor<'a, 'tcx> {
689     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
690         let lhs = place.local;
691         match rvalue {
692             // Only consider `&mut`, which can modify origin place
693             mir::Rvalue::Ref(_, rustc_middle::mir::BorrowKind::Mut { .. }, borrowed) |
694             // _2: &mut _;
695             // _3 = move _2
696             mir::Rvalue::Use(mir::Operand::Move(borrowed))  |
697             // _3 = move _2 as &mut _;
698             mir::Rvalue::Cast(_, mir::Operand::Move(borrowed), _)
699                 => {
700                 self.possible_origin.add(lhs, borrowed.local);
701             },
702             _ => {},
703         }
704     }
705 }
706
707 struct ContainsRegion<'tcx>(TyCtxt<'tcx>);
708
709 impl<'tcx> TypeVisitor<'tcx> for ContainsRegion<'tcx> {
710     type BreakTy = ();
711     fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
712         Some(self.0)
713     }
714
715     fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
716         ControlFlow::BREAK
717     }
718 }
719
720 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
721     use rustc_middle::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
722
723     let mut visit_op = |op: &mir::Operand<'_>| match op {
724         mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
725         mir::Operand::Constant(..) => (),
726     };
727
728     match rvalue {
729         Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
730         Aggregate(_, ops) => ops.iter().for_each(visit_op),
731         BinaryOp(_, box (lhs, rhs)) | CheckedBinaryOp(_, box (lhs, rhs)) => {
732             visit_op(lhs);
733             visit_op(rhs);
734         },
735         _ => (),
736     }
737 }
738
739 /// Result of `PossibleBorrowerVisitor`.
740 struct PossibleBorrowerMap<'a, 'tcx> {
741     /// Mapping `Local -> its possible borrowers`
742     map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
743     maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
744     // Caches to avoid allocation of `BitSet` on every query
745     bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
746 }
747
748 impl PossibleBorrowerMap<'_, '_> {
749     /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
750     fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
751         self.maybe_live.seek_after_primary_effect(at);
752
753         self.bitset.0.clear();
754         let maybe_live = &mut self.maybe_live;
755         if let Some(bitset) = self.map.get(&borrowed) {
756             for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
757                 self.bitset.0.insert(b);
758             }
759         } else {
760             return false;
761         }
762
763         self.bitset.1.clear();
764         for b in borrowers {
765             self.bitset.1.insert(*b);
766         }
767
768         self.bitset.0 == self.bitset.1
769     }
770
771     fn is_alive_at(&mut self, local: mir::Local, at: mir::Location) -> bool {
772         self.maybe_live.seek_after_primary_effect(at);
773         self.maybe_live.contains(local)
774     }
775 }