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