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