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