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