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