]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/redundant_clone.rs
Rollup merge of #75954 - ArekPiekarz:unstable_book_ffi_tracking_issues, r=steveklabnik
[rust.git] / src / tools / clippy / clippy_lints / src / redundant_clone.rs
1 use crate::utils::{
2     fn_has_unsatisfiable_preds, has_drop, is_copy, is_type_diagnostic_item, match_def_path, match_type, paths,
3     snippet_opt, span_lint_hir, span_lint_hir_and_then, walk_ptrs_ty_depth,
4 };
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 };
16 use rustc_middle::ty::{self, fold::TypeVisitor, Ty};
17 use rustc_mir::dataflow::BottomValue;
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 std::convert::TryFrom;
22
23 macro_rules! unwrap_or_continue {
24     ($x:expr) => {
25         match $x {
26             Some(x) => x,
27             None => continue,
28         }
29     };
30 }
31
32 declare_clippy_lint! {
33     /// **What it does:** Checks for a redundant `clone()` (and its relatives) which clones an owned
34     /// value that is going to be dropped without further use.
35     ///
36     /// **Why is this bad?** It is not always possible for the compiler to eliminate useless
37     /// allocations and deallocations generated by redundant `clone()`s.
38     ///
39     /// **Known problems:**
40     ///
41     /// False-negatives: analysis performed by this lint is conservative and limited.
42     ///
43     /// **Example:**
44     /// ```rust
45     /// # use std::path::Path;
46     /// # #[derive(Clone)]
47     /// # struct Foo;
48     /// # impl Foo {
49     /// #     fn new() -> Self { Foo {} }
50     /// # }
51     /// # fn call(x: Foo) {}
52     /// {
53     ///     let x = Foo::new();
54     ///     call(x.clone());
55     ///     call(x.clone()); // this can just pass `x`
56     /// }
57     ///
58     /// ["lorem", "ipsum"].join(" ").to_string();
59     ///
60     /// Path::new("/a/b").join("c").to_path_buf();
61     /// ```
62     pub REDUNDANT_CLONE,
63     perf,
64     "`clone()` of an owned value that is going to be dropped immediately"
65 }
66
67 declare_lint_pass!(RedundantClone => [REDUNDANT_CLONE]);
68
69 impl<'tcx> LateLintPass<'tcx> for RedundantClone {
70     #[allow(clippy::too_many_lines)]
71     fn check_fn(
72         &mut self,
73         cx: &LateContext<'tcx>,
74         _: FnKind<'tcx>,
75         _: &'tcx FnDecl<'_>,
76         body: &'tcx Body<'_>,
77         _: Span,
78         _: HirId,
79     ) {
80         let def_id = cx.tcx.hir().body_owner_def_id(body.id());
81
82         // Building MIR for `fn`s with unsatisfiable preds results in ICE.
83         if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
84             return;
85         }
86
87         let mir = cx.tcx.optimized_mir(def_id.to_def_id());
88
89         let maybe_storage_live_result = MaybeStorageLive
90             .into_engine(cx.tcx, mir, def_id.to_def_id())
91             .iterate_to_fixpoint()
92             .into_results_cursor(mir);
93         let mut possible_borrower = {
94             let mut vis = PossibleBorrowerVisitor::new(cx, mir);
95             vis.visit_body(&mir);
96             vis.into_map(cx, maybe_storage_live_result)
97         };
98
99         for (bb, bbdata) in mir.basic_blocks().iter_enumerated() {
100             let terminator = bbdata.terminator();
101
102             if terminator.source_info.span.from_expansion() {
103                 continue;
104             }
105
106             // Give up on loops
107             if terminator.successors().any(|s| *s == bb) {
108                 continue;
109             }
110
111             let (fn_def_id, arg, arg_ty, clone_ret) =
112                 unwrap_or_continue!(is_call_with_ref_arg(cx, mir, &terminator.kind));
113
114             let from_borrow = match_def_path(cx, fn_def_id, &paths::CLONE_TRAIT_METHOD)
115                 || match_def_path(cx, fn_def_id, &paths::TO_OWNED_METHOD)
116                 || (match_def_path(cx, fn_def_id, &paths::TO_STRING_METHOD)
117                     && is_type_diagnostic_item(cx, arg_ty, sym!(string_type)));
118
119             let from_deref = !from_borrow
120                 && (match_def_path(cx, fn_def_id, &paths::PATH_TO_PATH_BUF)
121                     || match_def_path(cx, fn_def_id, &paths::OS_STR_TO_OS_STRING));
122
123             if !from_borrow && !from_deref {
124                 continue;
125             }
126
127             if let ty::Adt(ref def, _) = arg_ty.kind() {
128                 if match_def_path(cx, def.did, &paths::MEM_MANUALLY_DROP) {
129                     continue;
130                 }
131             }
132
133             // `{ cloned = &arg; clone(move cloned); }` or `{ cloned = &arg; to_path_buf(cloned); }`
134             let (cloned, cannot_move_out) = unwrap_or_continue!(find_stmt_assigns_to(cx, mir, arg, from_borrow, bb));
135
136             let loc = mir::Location {
137                 block: bb,
138                 statement_index: bbdata.statements.len(),
139             };
140
141             // `Local` to be cloned, and a local of `clone` call's destination
142             let (local, ret_local) = if from_borrow {
143                 // `res = clone(arg)` can be turned into `res = move arg;`
144                 // if `arg` is the only borrow of `cloned` at this point.
145
146                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg], cloned, loc) {
147                     continue;
148                 }
149
150                 (cloned, clone_ret)
151             } else {
152                 // `arg` is a reference as it is `.deref()`ed in the previous block.
153                 // Look into the predecessor block and find out the source of deref.
154
155                 let ps = &mir.predecessors()[bb];
156                 if ps.len() != 1 {
157                     continue;
158                 }
159                 let pred_terminator = mir[ps[0]].terminator();
160
161                 // receiver of the `deref()` call
162                 let (pred_arg, deref_clone_ret) = if_chain! {
163                     if let Some((pred_fn_def_id, pred_arg, pred_arg_ty, res)) =
164                         is_call_with_ref_arg(cx, mir, &pred_terminator.kind);
165                     if res == cloned;
166                     if match_def_path(cx, pred_fn_def_id, &paths::DEREF_TRAIT_METHOD);
167                     if match_type(cx, pred_arg_ty, &paths::PATH_BUF)
168                         || match_type(cx, pred_arg_ty, &paths::OS_STRING);
169                     then {
170                         (pred_arg, res)
171                     } else {
172                         continue;
173                     }
174                 };
175
176                 let (local, cannot_move_out) =
177                     unwrap_or_continue!(find_stmt_assigns_to(cx, mir, pred_arg, true, ps[0]));
178                 let loc = mir::Location {
179                     block: bb,
180                     statement_index: mir.basic_blocks()[bb].statements.len(),
181                 };
182
183                 // This can be turned into `res = move local` if `arg` and `cloned` are not borrowed
184                 // at the last statement:
185                 //
186                 // ```
187                 // pred_arg = &local;
188                 // cloned = deref(pred_arg);
189                 // arg = &cloned;
190                 // StorageDead(pred_arg);
191                 // res = to_path_buf(cloned);
192                 // ```
193                 if cannot_move_out || !possible_borrower.only_borrowers(&[arg, cloned], local, loc) {
194                     continue;
195                 }
196
197                 (local, deref_clone_ret)
198             };
199
200             let is_temp = mir.local_kind(ret_local) == mir::LocalKind::Temp;
201
202             // 1. `local` can be moved out if it is not used later.
203             // 2. If `ret_local` is a temporary and is neither consumed nor mutated, we can remove this `clone`
204             // call anyway.
205             let (used, consumed_or_mutated) = traversal::ReversePostorder::new(&mir, bb).skip(1).fold(
206                 (false, !is_temp),
207                 |(used, consumed), (tbb, tdata)| {
208                     // Short-circuit
209                     if (used && consumed) ||
210                         // Give up on loops
211                         tdata.terminator().successors().any(|s| *s == bb)
212                     {
213                         return (true, true);
214                     }
215
216                     let mut vis = LocalUseVisitor {
217                         used: (local, false),
218                         consumed_or_mutated: (ret_local, false),
219                     };
220                     vis.visit_basic_block_data(tbb, tdata);
221                     (used || vis.used.1, consumed || vis.consumed_or_mutated.1)
222                 },
223             );
224
225             if !used || !consumed_or_mutated {
226                 let span = terminator.source_info.span;
227                 let scope = terminator.source_info.scope;
228                 let node = mir.source_scopes[scope]
229                     .local_data
230                     .as_ref()
231                     .assert_crate_local()
232                     .lint_root;
233
234                 if_chain! {
235                     if let Some(snip) = snippet_opt(cx, span);
236                     if let Some(dot) = snip.rfind('.');
237                     then {
238                         let sugg_span = span.with_lo(
239                             span.lo() + BytePos(u32::try_from(dot).unwrap())
240                         );
241                         let mut app = Applicability::MaybeIncorrect;
242
243                         let mut call_snip = &snip[dot + 1..];
244                         // Machine applicable when `call_snip` looks like `foobar()`
245                         if call_snip.ends_with("()") {
246                             call_snip = call_snip[..call_snip.len()-2].trim();
247                             if call_snip.as_bytes().iter().all(|b| b.is_ascii_alphabetic() || *b == b'_') {
248                                 app = Applicability::MachineApplicable;
249                             }
250                         }
251
252                         span_lint_hir_and_then(cx, REDUNDANT_CLONE, node, sugg_span, "redundant clone", |diag| {
253                             diag.span_suggestion(
254                                 sugg_span,
255                                 "remove this",
256                                 String::new(),
257                                 app,
258                             );
259                             if used {
260                                 diag.span_note(
261                                     span,
262                                     "cloned value is neither consumed nor mutated",
263                                 );
264                             } else {
265                                 diag.span_note(
266                                     span.with_hi(span.lo() + BytePos(u32::try_from(dot).unwrap())),
267                                     "this value is dropped without further use",
268                                 );
269                             }
270                         });
271                     } else {
272                         span_lint_hir(cx, REDUNDANT_CLONE, node, span, "redundant clone");
273                     }
274                 }
275             }
276         }
277     }
278 }
279
280 /// If `kind` is `y = func(x: &T)` where `T: !Copy`, returns `(DefId of func, x, T, y)`.
281 fn is_call_with_ref_arg<'tcx>(
282     cx: &LateContext<'tcx>,
283     mir: &'tcx mir::Body<'tcx>,
284     kind: &'tcx mir::TerminatorKind<'tcx>,
285 ) -> Option<(def_id::DefId, mir::Local, Ty<'tcx>, mir::Local)> {
286     if_chain! {
287         if let mir::TerminatorKind::Call { func, args, destination, .. } = kind;
288         if args.len() == 1;
289         if let mir::Operand::Move(mir::Place { local, .. }) = &args[0];
290         if let ty::FnDef(def_id, _) = *func.ty(&*mir, cx.tcx).kind();
291         if let (inner_ty, 1) = walk_ptrs_ty_depth(args[0].ty(&*mir, cx.tcx));
292         if !is_copy(cx, inner_ty);
293         then {
294             Some((def_id, *local, inner_ty, destination.as_ref().map(|(dest, _)| dest)?.as_local()?))
295         } else {
296             None
297         }
298     }
299 }
300
301 type CannotMoveOut = bool;
302
303 /// Finds the first `to = (&)from`, and returns
304 /// ``Some((from, whether `from` cannot be moved out))``.
305 fn find_stmt_assigns_to<'tcx>(
306     cx: &LateContext<'tcx>,
307     mir: &mir::Body<'tcx>,
308     to_local: mir::Local,
309     by_ref: bool,
310     bb: mir::BasicBlock,
311 ) -> Option<(mir::Local, CannotMoveOut)> {
312     let rvalue = mir.basic_blocks()[bb].statements.iter().rev().find_map(|stmt| {
313         if let mir::StatementKind::Assign(box (mir::Place { local, .. }, v)) = &stmt.kind {
314             return if *local == to_local { Some(v) } else { None };
315         }
316
317         None
318     })?;
319
320     match (by_ref, &*rvalue) {
321         (true, mir::Rvalue::Ref(_, _, place)) | (false, mir::Rvalue::Use(mir::Operand::Copy(place))) => {
322             base_local_and_movability(cx, mir, *place)
323         },
324         (false, mir::Rvalue::Ref(_, _, place)) => {
325             if let [mir::ProjectionElem::Deref] = place.as_ref().projection {
326                 base_local_and_movability(cx, mir, *place)
327             } else {
328                 None
329             }
330         },
331         _ => None,
332     }
333 }
334
335 /// Extracts and returns the undermost base `Local` of given `place`. Returns `place` itself
336 /// if it is already a `Local`.
337 ///
338 /// Also reports whether given `place` cannot be moved out.
339 fn base_local_and_movability<'tcx>(
340     cx: &LateContext<'tcx>,
341     mir: &mir::Body<'tcx>,
342     place: mir::Place<'tcx>,
343 ) -> Option<(mir::Local, CannotMoveOut)> {
344     use rustc_middle::mir::PlaceRef;
345
346     // Dereference. You cannot move things out from a borrowed value.
347     let mut deref = false;
348     // Accessing a field of an ADT that has `Drop`. Moving the field out will cause E0509.
349     let mut field = false;
350     // If projection is a slice index then clone can be removed only if the
351     // underlying type implements Copy
352     let mut slice = false;
353
354     let PlaceRef { local, mut projection } = place.as_ref();
355     while let [base @ .., elem] = projection {
356         projection = base;
357         deref |= matches!(elem, mir::ProjectionElem::Deref);
358         field |= matches!(elem, mir::ProjectionElem::Field(..))
359             && has_drop(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
360         slice |= matches!(elem, mir::ProjectionElem::Index(..))
361             && !is_copy(cx, mir::Place::ty_from(local, projection, &mir.local_decls, cx.tcx).ty);
362     }
363
364     Some((local, deref || field || slice))
365 }
366
367 struct LocalUseVisitor {
368     used: (mir::Local, bool),
369     consumed_or_mutated: (mir::Local, bool),
370 }
371
372 impl<'tcx> mir::visit::Visitor<'tcx> for LocalUseVisitor {
373     fn visit_basic_block_data(&mut self, block: mir::BasicBlock, data: &mir::BasicBlockData<'tcx>) {
374         let statements = &data.statements;
375         for (statement_index, statement) in statements.iter().enumerate() {
376             self.visit_statement(statement, mir::Location { block, statement_index });
377         }
378
379         self.visit_terminator(
380             data.terminator(),
381             mir::Location {
382                 block,
383                 statement_index: statements.len(),
384             },
385         );
386     }
387
388     fn visit_place(&mut self, place: &mir::Place<'tcx>, ctx: PlaceContext, _: mir::Location) {
389         let local = place.local;
390
391         if local == self.used.0
392             && !matches!(ctx, PlaceContext::MutatingUse(MutatingUseContext::Drop) | PlaceContext::NonUse(_))
393         {
394             self.used.1 = true;
395         }
396
397         if local == self.consumed_or_mutated.0 {
398             match ctx {
399                 PlaceContext::NonMutatingUse(NonMutatingUseContext::Move)
400                 | PlaceContext::MutatingUse(MutatingUseContext::Borrow) => {
401                     self.consumed_or_mutated.1 = true;
402                 },
403                 _ => {},
404             }
405         }
406     }
407 }
408
409 /// Determines liveness of each local purely based on `StorageLive`/`Dead`.
410 #[derive(Copy, Clone)]
411 struct MaybeStorageLive;
412
413 impl<'tcx> AnalysisDomain<'tcx> for MaybeStorageLive {
414     type Idx = mir::Local;
415     const NAME: &'static str = "maybe_storage_live";
416
417     fn bits_per_block(&self, body: &mir::Body<'tcx>) -> usize {
418         body.local_decls.len()
419     }
420
421     fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut BitSet<Self::Idx>) {
422         for arg in body.args_iter() {
423             state.insert(arg);
424         }
425     }
426 }
427
428 impl<'tcx> GenKillAnalysis<'tcx> for MaybeStorageLive {
429     fn statement_effect(&self, trans: &mut impl GenKill<Self::Idx>, stmt: &mir::Statement<'tcx>, _: mir::Location) {
430         match stmt.kind {
431             mir::StatementKind::StorageLive(l) => trans.gen(l),
432             mir::StatementKind::StorageDead(l) => trans.kill(l),
433             _ => (),
434         }
435     }
436
437     fn terminator_effect(
438         &self,
439         _trans: &mut impl GenKill<Self::Idx>,
440         _terminator: &mir::Terminator<'tcx>,
441         _loc: mir::Location,
442     ) {
443     }
444
445     fn call_return_effect(
446         &self,
447         _in_out: &mut impl GenKill<Self::Idx>,
448         _block: mir::BasicBlock,
449         _func: &mir::Operand<'tcx>,
450         _args: &[mir::Operand<'tcx>],
451         _return_place: mir::Place<'tcx>,
452     ) {
453         // Nothing to do when a call returns successfully
454     }
455 }
456
457 impl BottomValue for MaybeStorageLive {
458     /// bottom = dead
459     const BOTTOM_VALUE: bool = false;
460 }
461
462 /// Collects the possible borrowers of each local.
463 /// For example, `b = &a; c = &a;` will make `b` and (transitively) `c`
464 /// possible borrowers of `a`.
465 struct PossibleBorrowerVisitor<'a, 'tcx> {
466     possible_borrower: TransitiveRelation<mir::Local>,
467     body: &'a mir::Body<'tcx>,
468     cx: &'a LateContext<'tcx>,
469 }
470
471 impl<'a, 'tcx> PossibleBorrowerVisitor<'a, 'tcx> {
472     fn new(cx: &'a LateContext<'tcx>, body: &'a mir::Body<'tcx>) -> Self {
473         Self {
474             possible_borrower: TransitiveRelation::default(),
475             cx,
476             body,
477         }
478     }
479
480     fn into_map(
481         self,
482         cx: &LateContext<'tcx>,
483         maybe_live: ResultsCursor<'tcx, 'tcx, MaybeStorageLive>,
484     ) -> PossibleBorrowerMap<'a, 'tcx> {
485         let mut map = FxHashMap::default();
486         for row in (1..self.body.local_decls.len()).map(mir::Local::from_usize) {
487             if is_copy(cx, self.body.local_decls[row].ty) {
488                 continue;
489             }
490
491             let borrowers = self.possible_borrower.reachable_from(&row);
492             if !borrowers.is_empty() {
493                 let mut bs = HybridBitSet::new_empty(self.body.local_decls.len());
494                 for &c in borrowers {
495                     if c != mir::Local::from_usize(0) {
496                         bs.insert(c);
497                     }
498                 }
499
500                 if !bs.is_empty() {
501                     map.insert(row, bs);
502                 }
503             }
504         }
505
506         let bs = BitSet::new_empty(self.body.local_decls.len());
507         PossibleBorrowerMap {
508             map,
509             maybe_live,
510             bitset: (bs.clone(), bs),
511         }
512     }
513 }
514
515 impl<'a, 'tcx> mir::visit::Visitor<'tcx> for PossibleBorrowerVisitor<'a, 'tcx> {
516     fn visit_assign(&mut self, place: &mir::Place<'tcx>, rvalue: &mir::Rvalue<'_>, _location: mir::Location) {
517         let lhs = place.local;
518         match rvalue {
519             mir::Rvalue::Ref(_, _, borrowed) => {
520                 self.possible_borrower.add(borrowed.local, lhs);
521             },
522             other => {
523                 if !ContainsRegion.visit_ty(place.ty(&self.body.local_decls, self.cx.tcx).ty) {
524                     return;
525                 }
526                 rvalue_locals(other, |rhs| {
527                     if lhs != rhs {
528                         self.possible_borrower.add(rhs, lhs);
529                     }
530                 });
531             },
532         }
533     }
534
535     fn visit_terminator(&mut self, terminator: &mir::Terminator<'_>, _loc: mir::Location) {
536         if let mir::TerminatorKind::Call {
537             args,
538             destination: Some((mir::Place { local: dest, .. }, _)),
539             ..
540         } = &terminator.kind
541         {
542             // If the call returns something with lifetimes,
543             // let's conservatively assume the returned value contains lifetime of all the arguments.
544             // For example, given `let y: Foo<'a> = foo(x)`, `y` is considered to be a possible borrower of `x`.
545             if !ContainsRegion.visit_ty(&self.body.local_decls[*dest].ty) {
546                 return;
547             }
548
549             for op in args {
550                 match op {
551                     mir::Operand::Copy(p) | mir::Operand::Move(p) => {
552                         self.possible_borrower.add(p.local, *dest);
553                     },
554                     _ => (),
555                 }
556             }
557         }
558     }
559 }
560
561 struct ContainsRegion;
562
563 impl TypeVisitor<'_> for ContainsRegion {
564     fn visit_region(&mut self, _: ty::Region<'_>) -> bool {
565         true
566     }
567 }
568
569 fn rvalue_locals(rvalue: &mir::Rvalue<'_>, mut visit: impl FnMut(mir::Local)) {
570     use rustc_middle::mir::Rvalue::{Aggregate, BinaryOp, Cast, CheckedBinaryOp, Repeat, UnaryOp, Use};
571
572     let mut visit_op = |op: &mir::Operand<'_>| match op {
573         mir::Operand::Copy(p) | mir::Operand::Move(p) => visit(p.local),
574         _ => (),
575     };
576
577     match rvalue {
578         Use(op) | Repeat(op, _) | Cast(_, op, _) | UnaryOp(_, op) => visit_op(op),
579         Aggregate(_, ops) => ops.iter().for_each(visit_op),
580         BinaryOp(_, lhs, rhs) | CheckedBinaryOp(_, lhs, rhs) => {
581             visit_op(lhs);
582             visit_op(rhs);
583         },
584         _ => (),
585     }
586 }
587
588 /// Result of `PossibleBorrowerVisitor`.
589 struct PossibleBorrowerMap<'a, 'tcx> {
590     /// Mapping `Local -> its possible borrowers`
591     map: FxHashMap<mir::Local, HybridBitSet<mir::Local>>,
592     maybe_live: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
593     // Caches to avoid allocation of `BitSet` on every query
594     bitset: (BitSet<mir::Local>, BitSet<mir::Local>),
595 }
596
597 impl PossibleBorrowerMap<'_, '_> {
598     /// Returns true if the set of borrowers of `borrowed` living at `at` matches with `borrowers`.
599     fn only_borrowers(&mut self, borrowers: &[mir::Local], borrowed: mir::Local, at: mir::Location) -> bool {
600         self.maybe_live.seek_after_primary_effect(at);
601
602         self.bitset.0.clear();
603         let maybe_live = &mut self.maybe_live;
604         if let Some(bitset) = self.map.get(&borrowed) {
605             for b in bitset.iter().filter(move |b| maybe_live.contains(*b)) {
606                 self.bitset.0.insert(b);
607             }
608         } else {
609             return false;
610         }
611
612         self.bitset.1.clear();
613         for b in borrowers {
614             self.bitset.1.insert(*b);
615         }
616
617         self.bitset.0 == self.bitset.1
618     }
619 }