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